A first Google sign-in mints an account only under an app's invite grant #18

Merged
eureka merged 6 commits from hands/heimdall-invite-grant-mints into main 2026-11-29 20:04:07 +00:00
5 changed files with 213 additions and 11 deletions

View file

@ -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 <Heimdall access token>` 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

View file

@ -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"] },

View file

@ -103,6 +103,7 @@ function buildOAuthStateToken(options: {
entitlementPolicy: OAuthEntitlementPolicy | undefined;
requestedScopes: string[] | undefined;
stepUp: boolean | undefined;
firstLoginGrant: "invite" | undefined;
keys: ReturnType<typeof createRuntimeKeyMaterial>;
}): { 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<string, unknown>, options.keys);
@ -190,7 +192,8 @@ function parseOAuthStatePayload(payload: Record<string, unknown>): 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<string, unknown>): 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<FastifyIn
},
initiatingAccountId: { type: "string", minLength: 1 },
stepUp: { type: "boolean" },
firstLoginGrant: { type: "string", enum: ["invite"] },
handoff: {
type: "object",
required: ["kind"],
@ -2013,6 +2032,7 @@ export async function buildApp(options: BuildAppOptions = {}): Promise<FastifyIn
});
const nowIso = new Date().toISOString();
let account = await store.findAccountByLinkedIdentity(identity.provider, identity.providerUserId);
let mintedByGrant = false;
// One person, one account. A link attaches the provider identity to the
// account the signed state names, and to no other: an identity another
// account holds is a refusal, never a quiet sign-in as that account or a
@ -2033,7 +2053,11 @@ export async function buildApp(options: BuildAppOptions = {}): Promise<FastifyIn
}
}
} else if (!account && callbackDescriptor.firstLogin === "requires_link") {
throw new LinkRefusal("identity_not_linked", "No account holds this identity; sign in another way and link it first.");
// Only the app's signed invite mints; with an account already holding the identity this branch is never reached.
if (statePayload.first_login_grant !== "invite") {
throw new LinkRefusal("identity_not_linked", "No account holds this identity; sign in another way and link it first.");
}
mintedByGrant = true;
}
const buildLinkedIdentityInput = (accountId: string): UpsertLinkedIdentityInput => {
@ -2142,6 +2166,15 @@ export async function buildApp(options: BuildAppOptions = {}): Promise<FastifyIn
createAccountInput.primaryEmail = identity.primaryEmail;
}
account = await store.createAccount(createAccountInput);
if (mintedByGrant) {
await store.createAuditEvent({
accountId: account.id,
appSlug: statePayload.app_slug,
eventType: "account_minted_by_grant",
eventPayloadJson: { provider: identity.provider, appSlug: statePayload.app_slug },
createdAt: nowIso,
});
}
} else {
const accountUpdates: { displayName?: string; primaryEmail?: string } = {};
const displayName = identity.displayName ?? identity.username;

View file

@ -80,6 +80,12 @@ export interface OAuthStartRequest {
entitlementPolicy?: OAuthEntitlementPolicy;
/** Sign_in only, app-authenticated: ask the provider for a real re-authentication. Off when absent. */
stepUp?: boolean;
/**
* Sign_in only, from an app whose profile may grant (`mayGrantFirstLogin`): the app has
* invited this person, so a provider that otherwise requires a link may mint the
* first account. Carried in the signed state; never read from a browser.
*/
firstLoginGrant?: "invite";
}
export interface OAuthStatePayload {
@ -103,6 +109,8 @@ export interface OAuthStatePayload {
requested_scopes: string[] | null;
/** The start's step-up request. Signed, so the launch hop reads it here and nowhere else; null when not asked. */
step_up: true | null;
/** The start's first-login grant. Signed, so only the app's own start can set it; null when not granted. */
first_login_grant: "invite" | null;
}
export interface LinkedIdentityInput {

View file

@ -25,7 +25,7 @@ function config(): HeimdallConfig {
storage: { backend: "memory", applySchemaOnStartup: true },
tokenEncryptionKeyBase64: Buffer.alloc(32, 7).toString("base64"),
bootstrapSigningPrivateKeyOnMissing: true,
appSharedSecrets: { ...base.appSharedSecrets, bifrost: "bifrost-secret" },
appSharedSecrets: { ...base.appSharedSecrets, bifrost: "bifrost-secret", repixelizer: "repixelizer-secret" },
providers: {
...base.providers,
google: { clientId: CLIENT_ID, clientSecret: "google-secret" },
@ -535,3 +535,141 @@ describe("Google as a Heimdall OIDC provider", () => {
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<string, unknown> = {}, headers: Record<string, string> = 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<string, unknown>) {
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<string, { eventType: string; eventPayloadJson?: unknown }> }).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);
});
});