From 2bcb2ca4e7fb640e07deae42302b0919a62e5bc4 Mon Sep 17 00:00:00 2001 From: Eureka Date: Sun, 29 Nov 2026 20:04:06 +0000 Subject: [PATCH] A first Google sign-in mints an account only under an app's invite grant (#18) --- docs/service-contract.md | 28 ++++++-- src/app-profiles.ts | 9 +++ src/app.ts | 39 ++++++++++- src/contracts.ts | 8 +++ tests/google-link.test.ts | 140 +++++++++++++++++++++++++++++++++++++- 5 files changed, 213 insertions(+), 11 deletions(-) diff --git a/docs/service-contract.md b/docs/service-contract.md index 6b77caa..2412fbb 100644 --- a/docs/service-contract.md +++ b/docs/service-contract.md @@ -236,10 +236,11 @@ Launch note: implemented yet - Repixelizer launch can configure Discord and Patreon on its provider buttons -### Google (OpenID Connect, link-only) +### Google (OpenID Connect, link-only; mints only under an invite grant) -`google` is an identity provider that never mints an account. It is a second -door into a person who already has one. +`google` is an identity provider that does not mint an account by itself. It is +a second door into a person who already has one, and a first door only for a +person an app has invited (see the invite grant below). - Callback redirect URI (register exactly this in the Google Cloud OAuth client): `{GC_ACCESS_BASE_URL}/v1/oauth/google/callback`, which is @@ -256,10 +257,23 @@ door into a person who already has one. - `mode: "link"` needs `Authorization: Bearer ` for the same app; the identity attaches to that token's account and to no other. `mode: "sign_in"` signs in an account the `sub` is already linked to. -- A `sub` no account holds, arriving with `sign_in`, is refused and mints - nothing. A `sub` linked to another account is refused and never moved. - Both audit as `oauth_callback_failed` with error class `LinkRefusal` - and the code `identity_not_linked` or `link_initiator_mismatch`. +- A `sub` no account holds, arriving with `sign_in` and no invite grant, is + refused and mints nothing. A `sub` linked to another account is refused and + never moved. Both audit as `oauth_callback_failed` with error class + `LinkRefusal` and the code `identity_not_linked` or `link_initiator_mismatch`. +- Invite grant. An app whose profile sets `mayGrantFirstLogin` (only `bifrost`) + may start `mode: "sign_in"` with `firstLoginGrant: "invite"`, saying it has + invited this person. The start must carry that app's own secret: any other + caller, including a public start, is `401 app_auth_required`. An app whose + profile may not grant, any other mode, or any other value is + `400 first_login_grant_refused`. The grant rides only in the signed state + (`first_login_grant`), so nothing a browser sends can set it, and the state + stays single-use. At the callback a `sub` no account holds, under a grant, + mints one account with that identity linked, and audits + `account_minted_by_grant` with `{ provider, appSlug }`. A `sub` an account + already holds signs in to that account exactly as without a grant; the grant + never attaches an identity to an existing account and never moves one. + `mode: "link"` takes no grant and is unchanged. - Link is two-phase. The callback verifies the identity and records a pending link (TTL `completionTtlSeconds`), answering `status: "link_pending"` with a `pendingLinkId` and no session; it writes no linked identity. The app calls diff --git a/src/app-profiles.ts b/src/app-profiles.ts index a77f76a..b388ce2 100644 --- a/src/app-profiles.ts +++ b/src/app-profiles.ts @@ -56,6 +56,14 @@ export interface AppProfile { * state. Absent for apps whose browser starts are public by design. */ startRequiresAppCaller?: boolean; + /** + * The app decides who is invited. Its authenticated sign_in start may carry + * `firstLoginGrant: "invite"`, which lets a provider that otherwise requires a + * link (Google) mint the account for an identity no account holds. The grant + * never attaches an identity to an existing account. Absent for every app that + * may not grant. + */ + mayGrantFirstLogin?: true; /** * The app may assert, with its secret and a member's live bearer, that the * member just passed a factor the app itself checked (POST @@ -170,6 +178,7 @@ const bifrostProfile: AppProfile = { managedConnectionProviders: [], allowedReturnOrigins: ["https://bifrost.gamecult.org"], startRequiresAppCaller: true, + mayGrantFirstLogin: true, stepUpAssertion: { methods: ["bifrost-passkey", "bifrost-email-code"] }, // A passkey proves the account; an email code proves an inbox, which is one login's worth at most. identityMoves: { accountProofMethods: ["bifrost-passkey"] }, diff --git a/src/app.ts b/src/app.ts index b3c7755..5e327cf 100644 --- a/src/app.ts +++ b/src/app.ts @@ -103,6 +103,7 @@ function buildOAuthStateToken(options: { entitlementPolicy: OAuthEntitlementPolicy | undefined; requestedScopes: string[] | undefined; stepUp: boolean | undefined; + firstLoginGrant: "invite" | undefined; keys: ReturnType; }): { token: string; jti: string; expiresAt: string } { const issuedAt = nowEpochSeconds(); @@ -126,6 +127,7 @@ function buildOAuthStateToken(options: { entitlement_policy: options.entitlementPolicy ?? null, requested_scopes: options.requestedScopes ?? null, step_up: options.stepUp ? true : null, + first_login_grant: options.firstLoginGrant ?? null, }; const token = signJwt(payload as unknown as Record, options.keys); @@ -190,7 +192,8 @@ function parseOAuthStatePayload(payload: Record): OAuthStatePay !entitlementPolicyIsValid || !(payload.initiator_account_id === undefined || payload.initiator_account_id === null || typeof payload.initiator_account_id === "string") || !requestedScopesAreValid || - !(payload.step_up === undefined || payload.step_up === null || payload.step_up === true) + !(payload.step_up === undefined || payload.step_up === null || payload.step_up === true) || + !(payload.first_login_grant === undefined || payload.first_login_grant === null || (payload.first_login_grant === "invite" && payload.mode === "sign_in")) ) { return null; } @@ -211,6 +214,9 @@ function parseOAuthStatePayload(payload: Record): OAuthStatePay if (!normalizedPayload.step_up) { normalizedPayload.step_up = null; } + if (!normalizedPayload.first_login_grant) { + normalizedPayload.first_login_grant = null; + } return normalizedPayload; } @@ -823,10 +829,21 @@ export async function startOAuthFlow( if (options?.trustedBrowserAttemptId && handoff.kind === "browser_completion") { handoff = { kind: "browser_completion", attemptId: options.trustedBrowserAttemptId }; } - if ((entitlementPolicy || profile.startRequiresAppCaller || (input.mode === "connect" && input.connection !== undefined)) && (!isAppCaller(caller) || caller.appSlug !== profile.slug)) { + if ((entitlementPolicy || profile.startRequiresAppCaller || input.firstLoginGrant !== undefined || (input.mode === "connect" && input.connection !== undefined)) && (!isAppCaller(caller) || caller.appSlug !== profile.slug)) { return { statusCode: 401, body: { error: "app_auth_required" } }; } + // A grant is the app's word that it invited this person: the app-caller gate above has already admitted only the profile's own app, + // and a caller without the secret learns nothing about what a grant needs. Here: only a profile that may grant, only on sign_in. + if (input.firstLoginGrant !== undefined) { + if (!(input.firstLoginGrant === "invite" && input.mode === "sign_in" && profile.mayGrantFirstLogin === true)) { + return { + statusCode: 400, + body: { error: "first_login_grant_refused", detail: "firstLoginGrant needs the app's own sign_in start, from an app that may grant." }, + }; + } + } + // After the app-secret gate, so a caller without the secret learns nothing about what a target must look like. if (input.connection !== undefined && !isUsableConnectionTarget(input.connection.targetId)) { return { @@ -865,6 +882,7 @@ export async function startOAuthFlow( entitlementPolicy, requestedScopes: input.requestedScopes, stepUp: input.stepUp, + firstLoginGrant: input.firstLoginGrant, keys, }); return { @@ -1509,6 +1527,7 @@ export async function buildApp(options: BuildAppOptions = {}): Promise { @@ -2142,6 +2166,15 @@ export async function buildApp(options: BuildAppOptions = {}): Promise { expect(accountCount(store)).toBe(1); }); }); + +describe("an invite grant lets Bifrost's sign-in start mint the first Google account", () => { + const RETURN = "https://bifrost.gamecult.org/auth/heimdall/complete"; + + function startGrant(app: FastifyInstance, extra: Record = {}, headers: Record = BIFROST_APP) { + return app.inject({ + method: "POST", + url: "/v1/oauth/google/start", + headers, + payload: { appSlug: "bifrost", mode: "sign_in", returnTo: RETURN, firstLoginGrant: "invite", ...extra }, + }); + } + + async function googleCallback(app: FastifyInstance, start: { json(): never }, claims?: Record) { + const flow = await launchWithRedirect(app, start.json()); + fakeGoogle({ nonceFrom: () => flow.url.searchParams.get("nonce") ?? undefined, ...(claims ? { claims } : {}) }); + return { flow, done: await callbackGoogle(app, flow) }; + } + + const auditEvents = (store: InMemoryStore) => + [...(store as unknown as { auditEvents: Map }).auditEvents.values()]; + + it("google_first_login_without_grant_refused: no grant, identity_not_linked, nothing minted", async () => { + const { app, store } = await build(); + const start = await startGoogle(app, undefined, "sign_in"); + const { done } = await googleCallback(app, start); + expect([done.statusCode, done.json().error]).toEqual([403, "identity_not_linked"]); + expect(accountCount(store)).toBe(0); + }); + + it("google_first_login_with_bifrost_grant_mints: one account, the identity linked to it, audited", async () => { + const { app, store } = await build(); + const start = await startGrant(app); + expect(start.statusCode).toBe(201); + const { done } = await googleCallback(app, start); + expect(done.statusCode).toBe(201); + expect(accountCount(store)).toBe(1); + expect((await store.findStoredLinkedIdentity("google", "g-sub-1"))?.accountId).toBe(done.json().account.id); + const minted = auditEvents(store).filter((e) => e.eventType === "account_minted_by_grant"); + expect(minted.map((e) => e.eventPayloadJson)).toEqual([{ provider: "google", appSlug: "bifrost" }]); + }); + + it("a granted state is single-use: replaying the callback mints nothing more", async () => { + const { app, store } = await build(); + const start = await startGrant(app); + const { flow } = await googleCallback(app, start); + const again = await callbackGoogle(app, flow); + expect(again.statusCode).toBeGreaterThanOrEqual(400); + expect(accountCount(store)).toBe(1); + }); + + it("grant_from_other_app_refused: an app whose profile may not grant gets first_login_grant_refused", async () => { + const { app, store } = await build(); + const res = await app.inject({ + method: "POST", + url: "/v1/oauth/discord/start", + headers: { "x-heimdall-app-secret": "repixelizer-secret" }, + payload: { appSlug: "repixelizer", mode: "sign_in", returnTo: "https://repixelizer.gamecult.org/app/", firstLoginGrant: "invite" }, + }); + expect([res.statusCode, res.json().error]).toEqual([400, "first_login_grant_refused"]); + // Another app's secret on Bifrost's start is no Bifrost caller. + const other = await startGrant(app, {}, { "x-heimdall-app-secret": "repixelizer-secret" }); + expect(other.statusCode).toBe(401); + expect(accountCount(store)).toBe(0); + }); + + it("grant_without_app_caller_refused: a public start with firstLoginGrant is refused", async () => { + const { app, store } = await build(); + for (const headers of [{}, { "x-heimdall-app-secret": "wrong" }]) { + const res = await startGrant(app, {}, headers); + expect(res.statusCode, JSON.stringify(headers)).toBeGreaterThanOrEqual(400); + expect(res.json().authorizationUrl).toBeUndefined(); + } + // An app that does not require a caller is still refused: a grant is a start only the app itself may make. + const open = await app.inject({ + method: "POST", + url: "/v1/oauth/discord/start", + payload: { appSlug: "repixelizer", mode: "sign_in", returnTo: "https://repixelizer.gamecult.org/app/", firstLoginGrant: "invite" }, + }); + expect([open.statusCode, open.json().error]).toEqual([401, "app_auth_required"]); + expect(accountCount(store)).toBe(0); + }); + + it("refuses a grant on link mode and a grant value other than invite", async () => { + const { app } = await build(); + const { accessToken } = await signInWithDiscord(app); + const link = await app.inject({ + method: "POST", + url: "/v1/oauth/google/start", + headers: { ...BIFROST_APP, authorization: `Bearer ${accessToken}` }, + payload: { appSlug: "bifrost", mode: "link", returnTo: RETURN, firstLoginGrant: "invite" }, + }); + expect([link.statusCode, link.json().error]).toEqual([400, "first_login_grant_refused"]); + expect((await startGrant(app, { firstLoginGrant: "admin" })).statusCode).toBe(400); + }); + + it("grant_ignored_for_existing_account: a Google identity already held signs in to its account, no second account", async () => { + const { app, store } = await build(); + const { accessToken, accountId } = await signInWithDiscord(app); + await linkGoogle(app, accessToken); + const start = await startGrant(app); + const { done } = await googleCallback(app, start); + expect(done.statusCode).toBe(201); + expect(done.json().account.id).toBe(accountId); + expect(accountCount(store)).toBe(1); + expect(auditEvents(store).some((e) => e.eventType === "account_minted_by_grant")).toBe(false); + }); + + it("a grant never attaches an identity to an existing account: a new sub mints its own account and an held sub is never moved", async () => { + const store = new InMemoryStore(); + const first = await build(store, "discord-1"); + const a = await signInWithDiscord(first.app, "discord-1"); + await linkGoogle(first.app, a.accessToken); + const second = await build(store, "discord-2"); + const b = await signInWithDiscord(second.app, "discord-2"); + const start = await startGrant(second.app); + const { done } = await googleCallback(second.app, start, { sub: "g-sub-new" }); + expect(done.statusCode).toBe(201); + expect(done.json().account.id).not.toBe(a.accountId); + expect(done.json().account.id).not.toBe(b.accountId); + expect((await store.findStoredLinkedIdentity("google", "g-sub-1"))?.accountId).toBe(a.accountId); + expect((await store.findStoredLinkedIdentity("google", "g-sub-new"))?.accountId).toBe(done.json().account.id); + }); + + it("grant_tampered_state_refused: a first_login_grant added to a signed state fails verification", async () => { + const { app, store } = await build(); + const plain = await startGoogle(app, undefined, "sign_in"); + const [head, body, sig] = stateOf(plain.json()).split("."); + const payload = JSON.parse(Buffer.from(body!, "base64url").toString()); + const forged = [head, Buffer.from(JSON.stringify({ ...payload, first_login_grant: "invite" })).toString("base64url"), sig].join("."); + const launched = await app.inject({ method: "GET", url: `/v1/oauth/google/launch?state=${encodeURIComponent(forged)}` }); + expect(launched.statusCode).toBe(400); + expect(launched.headers.location).toBeUndefined(); + const cb = await app.inject({ method: "GET", url: `/v1/oauth/google/callback?code=g-code&state=${encodeURIComponent(forged)}` }); + expect(cb.statusCode).toBeGreaterThanOrEqual(400); + expect(accountCount(store)).toBe(0); + }); +});