diff --git a/src/app.ts b/src/app.ts index 2707bbe..c4d8e93 100644 --- a/src/app.ts +++ b/src/app.ts @@ -26,6 +26,7 @@ import { import { issueAccessClaim, type IssueAccessClaimInput } from "./claims.js"; import { builtInAppProfiles, getAppProfile, isAllowedReturnOrigin, serializeAppProfile, admitsProviderForMode, callbackMint } from "./app-profiles.js"; import { renderBrowserHandoffPage } from "./browser-handoff.js"; +import { consentDigest, grantViews, GRANTS_PATH, renderConsentPage, renderGrantsPage, type ConsentAsk } from "./consent.js"; import { type HeimdallConfig, loadConfig } from "./config.js"; import { createTokenCustody, type TokenCustody } from "./custody.js"; import { grantFact } from "./facts.js"; @@ -37,7 +38,7 @@ import { type OAuthRuntimeRegistry, } from "./oauth.js"; import { ManagedCredentialRefreshFailed, refreshManagedCredential } from "./managed-credential.js"; -import { buildAuthorizationUrl, providerCatalog, providerExpectedEnv } from "./providers.js"; +import { authorizationScopes, buildAuthorizationUrl, providerCatalog, providerExpectedEnv } from "./providers.js"; import { createRuntimeKeyMaterial, signJwt, verifyJwt } from "./signing.js"; import { createStore, type HeimdallStore } from "./store/index.js"; import { @@ -809,6 +810,47 @@ async function resolveLinkAccount( return claims.account_id; } +/** The account a Heimdall access token for any app names, when the token and its session are live. */ +async function resolveAccessAccount( + ctx: Pick, + authorization: string | undefined +): Promise { + const token = /^Bearer\s+(\S+)$/i.exec(authorization ?? "")?.[1]; + if (!token) return null; + const verification = verifyJwt(token, ctx.keys.publicKey); + if (!verification.valid) return null; + const audience = verification.payload.aud; + return isAppSlug(audience) ? resolveLinkAccount(ctx, audience, authorization) : null; +} + +const grantsPageTokenType = "heimdall_grants_page"; +const grantsPageTokenTtlSeconds = 600; + +/** A short, purpose-bound proof of a signed-in account, so the grants page can be opened and its forms posted by a browser that holds no session. */ +function signGrantsPageToken(config: HeimdallConfig, keys: ReturnType, accountId: string): string { + const iat = nowEpochSeconds(); + return signJwt({ typ: grantsPageTokenType, iss: config.issuer, account_id: accountId, iat, exp: iat + grantsPageTokenTtlSeconds }, keys); +} + +function grantsPageTokenAccount(config: HeimdallConfig, keys: ReturnType, token: unknown): string | null { + if (typeof token !== "string") return null; + const verification = verifyJwt(token, keys.publicKey); + if (!verification.valid) return null; + const { typ, iss, account_id: accountId, exp } = verification.payload; + return typ === grantsPageTokenType && iss === config.issuer && typeof accountId === "string" && typeof exp === "number" && exp > nowEpochSeconds() + ? accountId + : null; +} + +function consentAskFor(state: OAuthStatePayload): ConsentAsk { + return { + appSlug: state.app_slug, + provider: state.provider, + scopes: authorizationScopes(state.provider, state.requested_scopes ?? undefined), + returnOrigin: new URL(state.return_to).origin, + }; +} + /** * Session refresh, extracted for the same reason as startOAuthFlow: the HTTP * route and the plane's `refreshAuth` (which owns Ghostlight identity) call @@ -948,6 +990,10 @@ export async function buildApp(options: BuildAppOptions = {}): Promise { + done(null, Object.fromEntries(new URLSearchParams(body as string))); + }); app.get("/healthz", async () => ({ ok: true, @@ -1126,6 +1172,106 @@ export async function buildApp(options: BuildAppOptions = {}): Promise => { + const handoff = state.handoff ?? { kind: "browser_completion" }; + if (handoff.kind !== "browser_completion" || !handoff.attemptId) return; + await store.updateAuthAttempt(state.app_slug, handoff.attemptId, { + status: "denied", + at: new Date().toISOString(), + denialCode, + }); + }; + + /** + * The person said no, at Heimdall's ask (`viewer`) or at the provider + * (`provider`, a returned access_denied). It is its own result, never a + * provider_error: the app and the audit log can tell a refusal from a fault. + * Nothing is stored beyond an audit row that names no one. + */ + const refuseConsent = async (request: FastifyRequest, reply: FastifyReply, state: OAuthStatePayload, by: "viewer" | "provider") => { + const handoff = state.handoff ?? { kind: "browser_completion" }; + await denyAttempt(state, "consent_refused"); + await store.createAuditEvent({ + appSlug: state.app_slug, + eventType: "consent_refused", + eventPayloadJson: { provider: state.provider, mode: state.mode, by }, + createdAt: new Date().toISOString(), + }); + if (handoff.kind === "backend_callback") { + await maybeDeliverBackendHandoff(handoff, { + source: "heimdall", + kind: "oauth_result", + handoffKind: "backend_callback", + attemptId: handoff.attemptId, + status: "error", + provider: state.provider, + appSlug: state.app_slug, + mode: state.mode, + returnTo: state.return_to, + connection: state.connection, + error: "consent_refused", + by, + }); + } + if (prefersHtml(request.headers.accept)) { + reply.type("text/html; charset=utf-8"); + return reply.send( + renderBrowserHandoffPage({ + handoffKind: handoff.kind, + status: "error", + provider: state.provider, + appSlug: state.app_slug, + mode: state.mode, + returnTo: state.return_to, + ...(handoff.kind === "backend_callback" ? { attemptId: handoff.attemptId } : {}), + error: "consent_refused", + by, + }) + ); + } + reply.code(400); + return { error: "consent_refused", by, provider: state.provider, returnTo: state.return_to }; + }; + + const providerNotConfigured = (reply: FastifyReply, state: OAuthStatePayload) => { + reply.code(503); + return { error: "provider_not_configured", provider: state.provider, expectedEnv: providerExpectedEnv(state.provider) }; + }; + + /** Claim the launch use, bind the browser, and send it to the provider. */ + const beginProviderRedirect = async (request: FastifyRequest, reply: FastifyReply, state: OAuthStatePayload, rawState: string) => { + const clientId = config.providers[state.provider].clientId; + if (!clientId) { + return providerNotConfigured(reply, state); + } + const first = await store.claimOAuthStateUse({ + jti: state.jti, + phase: "launch", + appSlug: state.app_slug, + usedAt: new Date().toISOString(), + expiresAt: new Date(state.exp * 1000).toISOString(), + }); + if (!first) { + return refuseVerifiedState(request, reply, state, "state_already_launched"); + } + + const oidc = providerCatalog[state.provider].oidc ? deriveOidcSecrets(state.jti, keys.privateKey) : undefined; + setOAuthBindingCookie(reply, state, signOAuthBinding(config, keys, state), state.exp - nowEpochSeconds()); + reply.header("Cache-Control", "no-store"); + reply.header("Referrer-Policy", "no-referrer"); + return reply.redirect( + buildAuthorizationUrl({ + provider: state.provider, + clientId, + redirectUri: oauthCallbackUrl(config, state.provider), + state: rawState, + requestedScopes: state.requested_scopes ?? undefined, + ...(oidc ? { oidc: { nonce: oidc.nonce, codeChallenge: oidc.codeChallenge } } : {}), + }), + 302 + ); + }; + app.get<{ Params: { provider: Provider }; Querystring: { state: string }; @@ -1158,38 +1304,82 @@ export async function buildApp(options: BuildAppOptions = {}): Promise( + "/v1/oauth/:provider/consent", + { + schema: { + params: { + type: "object", + required: ["provider"], + additionalProperties: false, + properties: { provider: { type: "string", enum: [...providers] } }, + }, + body: { + type: "object", + required: ["state", "decision"], + additionalProperties: false, + properties: { + state: { type: "string", minLength: 1 }, + decision: { type: "string", enum: ["continue", "decline"] }, + }, + }, + }, + }, + async (request, reply) => { + const verified = verifyOAuthState(config, keys, request.body.state, request.params.provider); + if (!verified.ok) { + reply.code(400); + return { error: verified.error }; + } + const state = verified.payload; + const profile = getAppProfile(state.app_slug); + if (!profile || callbackMint(profile, state.provider, state.mode, state.connection) !== "custody_only") { + reply.code(400); + return { error: "consent_not_required" }; + } + // Either answer must come from the browser the ask was shown to. + if (!oauthBindingHolds(config, keys, request.cookies[oauthBindingCookieName(state.jti)], state)) { + return refuseVerifiedState(request, reply, state, "state_not_bound"); + } + if (request.body.decision === "continue") { + return beginProviderRedirect(request, reply, state, request.body.state); + } + // A decline spends both uses of the state: it can neither launch nor complete afterwards. + const usedAt = new Date().toISOString(); + const expiresAt = new Date(state.exp * 1000).toISOString(); + if (!(await store.claimOAuthStateUse({ jti: state.jti, phase: "launch", appSlug: state.app_slug, usedAt, expiresAt }))) { return refuseVerifiedState(request, reply, state, "state_already_launched"); } - - const oidc = providerCatalog[state.provider].oidc ? deriveOidcSecrets(state.jti, keys.privateKey) : undefined; - setOAuthBindingCookie(reply, state, signOAuthBinding(config, keys, state), state.exp - nowEpochSeconds()); - reply.header("Cache-Control", "no-store"); - reply.header("Referrer-Policy", "no-referrer"); - return reply.redirect( - buildAuthorizationUrl({ - provider: state.provider, - clientId, - redirectUri: oauthCallbackUrl(config, state.provider), - state: request.query.state, - requestedScopes: state.requested_scopes ?? undefined, - ...(oidc ? { oidc: { nonce: oidc.nonce, codeChallenge: oidc.codeChallenge } } : {}), - }), - 302 - ); + await store.claimOAuthStateUse({ jti: state.jti, phase: "callback", appSlug: state.app_slug, usedAt, expiresAt }); + setOAuthBindingCookie(reply, state, "", 0); + return refuseConsent(request, reply, state, "viewer"); } ); @@ -1233,14 +1423,7 @@ export async function buildApp(options: BuildAppOptions = {}): Promise => { - if (handoff.kind !== "browser_completion" || !handoff.attemptId) return; - await store.updateAuthAttempt(statePayload.app_slug, handoff.attemptId, { - status: "denied", - at: new Date().toISOString(), - denialCode, - }); - }; + const denyBrowserAttempt = (denialCode: string): Promise => denyAttempt(statePayload, denialCode); // The cookie is checked before the claim: a stranger without it must not be // able to burn the state that the browser that launched it still needs. // The attempt is denied, though: a launcher whose cookie lapsed can never @@ -1262,6 +1445,9 @@ export async function buildApp(options: BuildAppOptions = {}): Promise => + (await resolveAccessAccount({ config, keys, store }, request.headers.authorization)) ?? + grantsPageTokenAccount(config, keys, pageToken); + + const grantsReply = (reply: FastifyReply) => { + reply.header("Cache-Control", "no-store"); + reply.header("Referrer-Policy", "no-referrer"); + reply.header("X-Frame-Options", "DENY"); + reply.header("Content-Security-Policy", "default-src 'none'; style-src 'unsafe-inline'; frame-ancestors 'none'; base-uri 'none'; form-action 'self'"); + }; + + const signInRequired = (reply: FastifyReply) => { + reply.code(401); + return { error: "sign_in_required", detail: "Send a Heimdall access token as a Bearer token, or open a link from POST /v1/me/grants/link." }; + }; + + // The signed-in surface for consent: every grant and receipt the account + // holds, and the one-click way to take each back. + app.get<{ Querystring: { t?: string } }>( + GRANTS_PATH, + { schema: { querystring: { type: "object", additionalProperties: false, properties: { t: { type: "string" } } } } }, + async (request, reply) => { + const accountId = await grantsAccount(request, request.query.t); + if (!accountId) return signInRequired(reply); + grantsReply(reply); + const receipts = await store.listConsentReceipts(accountId); + if (prefersHtml(request.headers.accept)) { + reply.type("text/html; charset=utf-8"); + return reply.send(renderGrantsPage(grantViews(receipts), signGrantsPageToken(config, keys, accountId))); + } + return { grants: grantViews(receipts), receipts }; + } + ); + + // A link a browser can open: short-lived, opens the grants page and nothing else. + app.post(`${GRANTS_PATH}/link`, async (request, reply) => { + const accountId = await resolveAccessAccount({ config, keys, store }, request.headers.authorization); + if (!accountId) return signInRequired(reply); + grantsReply(reply); + reply.code(201); + return { + url: `${config.publicBaseUrl}${GRANTS_PATH}?t=${encodeURIComponent(signGrantsPageToken(config, keys, accountId))}`, + expiresInSeconds: grantsPageTokenTtlSeconds, + }; + }); + + app.post<{ Params: { grantId: string }; Body?: { t?: string } }>( + `${GRANTS_PATH}/:grantId/revoke`, + { + schema: { + params: { type: "object", required: ["grantId"], additionalProperties: false, properties: { grantId: { type: "string", minLength: 1 } } }, + body: { type: ["object", "null"], additionalProperties: false, properties: { t: { type: "string" } } }, + }, + }, + async (request, reply) => { + const accountId = await grantsAccount(request, request.body?.t); + if (!accountId) return signInRequired(reply); + grantsReply(reply); + const receipts = await store.listConsentReceipts(accountId); + const grant = grantViews(receipts).find((view) => view.id === request.params.grantId); + if (!grant) { + reply.code(404); + return { error: "grant_not_found" }; + } + const revoked: string[] = []; + if (grant.status === "active") { + // The credential is one row per account and provider, whichever app + // asked, so taking it back ends every live grant that rests on it. + // It is stripped first: a failure after that leaves a receipt that + // still reads active over a credential that is gone, never the reverse. + const identity = await store.findStoredLinkedIdentityForAccount(accountId, grant.provider); + const at = new Date().toISOString(); + if (identity) { + await store.updateLinkedIdentityCredential(identity.id, async () => ({ kind: "revoke", updatedAt: at })); + } + for (const live of grantViews(receipts).filter((view) => view.provider === grant.provider && view.status === "active")) { + await store.createConsentReceipt({ + kind: "revocation", + accountId, + appSlug: live.appSlug, + provider: live.provider, + createdAt: at, + revokesReceiptId: live.id, + }); + revoked.push(live.id); + } + await store.createAuditEvent({ + accountId, + eventType: "consent_revoked", + eventPayloadJson: { provider: grant.provider, grantIds: revoked }, + createdAt: at, + }); + } + if (prefersHtml(request.headers.accept) || request.headers["content-type"]?.startsWith("application/x-www-form-urlencoded")) { + reply.type("text/html; charset=utf-8"); + const views = grantViews(await store.listConsentReceipts(accountId)); + return reply.send(renderGrantsPage(views, signGrantsPageToken(config, keys, accountId), revoked.length ? "Taken back." : "Already taken back.")); + } + return { revoked, grants: grantViews(await store.listConsentReceipts(accountId)) }; + } + ); + return app; } diff --git a/src/backend-handoff.ts b/src/backend-handoff.ts index d49a125..b26a59f 100644 --- a/src/backend-handoff.ts +++ b/src/backend-handoff.ts @@ -30,6 +30,8 @@ export interface BackendHandoffSuccessPayload mode: OAuthMode; account: AccountSummary; entitlements: EntitlementEvaluation; + /** The receipt of the consent a managed connection rests on. */ + consentReceiptId?: string; } export interface BackendHandoffErrorPayload extends BackendHandoffBase { @@ -37,6 +39,8 @@ export interface BackendHandoffErrorPayload extends BackendHandoffBase { mode?: OAuthMode; error: string; errorDescription?: string; + /** Who said no, when `error` is consent_refused. */ + by?: "viewer" | "provider"; } /** A verified link that waits for the initiating account's confirm: no session, no tokens. */ diff --git a/src/browser-handoff.ts b/src/browser-handoff.ts index c21c01e..b8da567 100644 --- a/src/browser-handoff.ts +++ b/src/browser-handoff.ts @@ -15,6 +15,8 @@ export interface BrowserHandoffSuccess extends BrowserHandoffBase { /** A verified link waiting for its initiator's confirm; carries no session. */ pendingLinkId?: string; attemptId?: string; + /** The receipt of the consent a managed connection rests on. */ + consentReceiptId?: string; } export interface BrowserHandoffError extends BrowserHandoffBase { @@ -22,6 +24,8 @@ export interface BrowserHandoffError extends BrowserHandoffBase { error: string; errorDescription?: string; attemptId?: string; + /** Who said no, when `error` is consent_refused. */ + by?: "viewer" | "provider"; } export type BrowserHandoffPayload = BrowserHandoffSuccess | BrowserHandoffError; @@ -47,6 +51,9 @@ function buildBrowserFallbackUrl(payload: BrowserHandoffPayload): string { fragment.set("heimdall_attempt_id", payload.attemptId); } + if (payload.status === "success" && payload.consentReceiptId) { + fragment.set("heimdall_consent_receipt_id", payload.consentReceiptId); + } if (payload.status === "success" && payload.completionCode) { fragment.set("heimdall_completion_code", payload.completionCode); } else if (payload.status === "success" && payload.pendingLinkId) { @@ -54,6 +61,9 @@ function buildBrowserFallbackUrl(payload: BrowserHandoffPayload): string { } else { if (payload.status === "error") { fragment.set("heimdall_error", payload.error); + if (payload.by) { + fragment.set("heimdall_refused_by", payload.by); + } if (payload.errorDescription) { fragment.set("heimdall_error_description", payload.errorDescription); } @@ -77,14 +87,19 @@ export function renderBrowserHandoffPage(payload: BrowserHandoffPayload): string }); const scriptOrigin = serializeForScript(targetOrigin); const scriptFallbackUrl = serializeForScript(fallbackUrl); - const scriptTitle = serializeForScript( - payload.status === "success" ? "Authentication Complete" : "Authentication Failed" - ); + const refused = payload.status === "error" && payload.error === "consent_refused"; + const pageTitle = refused ? "Not Connected" : payload.status === "success" ? "Authentication Complete" : "Authentication Failed"; + const scriptTitle = serializeForScript(pageTitle); const scriptBody = serializeForScript( - payload.status === "success" - ? payload.handoffKind === "backend_callback" - ? "The app backend has the auth result already. You can return to the app now." - : "You can return to the app now." + refused + ? "Nothing was connected and nothing was kept. You can return to the app." + : payload.status === "success" + ? (payload.handoffKind === "backend_callback" + ? "The app backend has the auth result already. You can return to the app now." + : "You can return to the app now.") + + (payload.consentReceiptId + ? ` Your consent is recorded as receipt ${payload.consentReceiptId}; you can review it and take it back from your Heimdall connections page.` + : "") : "The authentication flow failed. Return to the app to continue." ); @@ -93,7 +108,7 @@ export function renderBrowserHandoffPage(payload: BrowserHandoffPayload): string - ${payload.status === "success" ? "Authentication Complete" : "Authentication Failed"} + ${pageTitle} + + +
+${body} +
+ +`; +} + +/** The ask. Two POST forms carry the signed state; the page runs no script. */ +export function renderConsentPage(ask: ConsentAsk, state: string): string { + const lines = consentLines(ask); + const provider = providerCatalog[ask.provider].displayName; + const [headline, ...rest] = lines; + const form = (decision: "continue" | "decline", label: string) => + ``; + return page( + `${appName(ask.appSlug)} wants to connect ${provider}`, + `

${escapeHtml(headline!)}

+
    +${rest.map((line) => `
  • ${escapeHtml(line)}
  • `).join("\n")} +
+
+ + ${form("continue", `Continue to ${provider}`)} + ${form("decline", "No, return to the app")} +
` + ); +} + +export interface GrantView { + id: string; + appSlug: AppSlug; + provider: Provider; + scopesAsked: string[]; + scopesGranted: string[]; + grantedAt: string; + consentPageDigest: string; + status: "active" | "revoked"; + revokedAt?: string; + revocationReceiptId?: string; +} + +/** Every grant the receipts hold, each live unless a revocation names it. */ +export function grantViews(receipts: readonly StoredConsentReceipt[]): GrantView[] { + const revocations = new Map(); + for (const receipt of receipts) { + if (receipt.kind === "revocation") revocations.set(receipt.revokesReceiptId, receipt); + } + const views: GrantView[] = []; + for (const receipt of receipts) { + if (receipt.kind !== "grant") continue; + const revocation = revocations.get(receipt.id); + views.push({ + id: receipt.id, + appSlug: receipt.appSlug, + provider: receipt.provider, + scopesAsked: receipt.scopesAsked, + scopesGranted: receipt.scopesGranted, + grantedAt: receipt.createdAt, + consentPageDigest: receipt.consentPageDigest, + status: revocation ? "revoked" : "active", + ...(revocation ? { revokedAt: revocation.createdAt, revocationReceiptId: revocation.id } : {}), + }); + } + return views; +} + +/** The signed-in page: every grant with its receipt, one button each to take it back. */ +export function renderGrantsPage(grants: readonly GrantView[], pageToken: string, notice?: string): string { + const cards = grants.length + ? grants + .map((grant) => { + const provider = providerCatalog[grant.provider].displayName; + const header = `${escapeHtml(appName(grant.appSlug))} → ${escapeHtml(provider)}`; + const detail = `granted ${escapeHtml(grant.grantedAt)}; permissions ${escapeHtml(grant.scopesGranted.join(", ") || "none returned")}; receipt ${escapeHtml(grant.id)}; wording ${escapeHtml(grant.consentPageDigest.slice(0, 12))}`; + if (grant.status === "revoked") { + return `
${header} taken back ${escapeHtml(grant.revokedAt ?? "")}; receipt ${escapeHtml(grant.revocationReceiptId ?? "")}
${detail}
`; + } + return `
${header} active
${detail} +
+ + +
`; + }) + .join("\n") + : `

You have not connected anything through Heimdall.

`; + return page( + "Your connections", + `

Your connections

+${notice ? `

${escapeHtml(notice)}

\n` : ""}${cards} +

Taking a connection back deletes Heimdall's copy of the tokens. The app's next request for a token is refused. The permission stays with the provider until you remove it in the provider's settings.

` + ); +} diff --git a/src/providers.ts b/src/providers.ts index b649ede..01f749f 100644 --- a/src/providers.ts +++ b/src/providers.ts @@ -167,6 +167,11 @@ export const providerCatalog: Record = { }, }; +/** The scopes an authorization request carries: the caller's, or the provider's defaults. */ +export function authorizationScopes(provider: Provider, requested: readonly string[] | undefined): string[] { + return requested?.length ? [...requested] : [...providerCatalog[provider].defaultScopes]; +} + export function buildAuthorizationUrl(options: { provider: Provider; clientId: string; @@ -178,7 +183,7 @@ export function buildAuthorizationUrl(options: { }): string { const descriptor = providerCatalog[options.provider]; const url = new URL(descriptor.authorizationEndpoint); - const scopes = options.requestedScopes?.length ? options.requestedScopes : descriptor.defaultScopes; + const scopes = authorizationScopes(options.provider, options.requestedScopes); url.searchParams.set("client_id", options.clientId); url.searchParams.set("redirect_uri", options.redirectUri); diff --git a/src/store/in-memory.ts b/src/store/in-memory.ts index eafaea5..c31b098 100644 --- a/src/store/in-memory.ts +++ b/src/store/in-memory.ts @@ -5,7 +5,9 @@ import { type CreateAuthAttemptInput, type ClaimOAuthStateUseInput, type CreateAuthCompletionInput, + type CreateConsentReceiptInput, type CreatePendingLinkInput, + type StoredConsentReceipt, type StoredPendingLink, type CreateAuditEventInput, type CreateCapabilityGrantInput, @@ -59,6 +61,7 @@ export class InMemoryStore implements HeimdallStore { private readonly oauthStateUses = new Map(); private readonly entitlementSnapshots = new Map(); private readonly auditEvents = new Map(); + private readonly consentReceipts: StoredConsentReceipt[] = []; async ensureSchema(): Promise { return; @@ -482,4 +485,14 @@ export class InMemoryStore implements HeimdallStore { }); this.auditEvents.set(event.id ?? randomUUID(), event); } + + async createConsentReceipt(input: CreateConsentReceiptInput): Promise { + const receipt = { id: randomUUID(), ...clone(input) } as StoredConsentReceipt; + this.consentReceipts.push(clone(receipt)); + return clone(receipt); + } + + async listConsentReceipts(accountId: string): Promise { + return this.consentReceipts.filter((receipt) => receipt.accountId === accountId).map(clone); + } } diff --git a/src/store/postgres.ts b/src/store/postgres.ts index e3a1c4d..45240a5 100644 --- a/src/store/postgres.ts +++ b/src/store/postgres.ts @@ -7,7 +7,9 @@ import { type CreateAuthAttemptInput, type ClaimOAuthStateUseInput, type CreateAuthCompletionInput, + type CreateConsentReceiptInput, type CreatePendingLinkInput, + type StoredConsentReceipt, type StoredPendingLink, type CreateAuditEventInput, type CreateCapabilityGrantInput, @@ -248,6 +250,39 @@ function mapSessionRow(row: SessionRow): StoredSession { }; } +interface ConsentReceiptRow { + id: string; + kind: "grant" | "revocation"; + account_id: string; + app_slug: AppSlug; + provider: Provider; + created_at: Date | string; + scopes_asked: string | null; + scopes_granted: string | null; + consent_page_digest: string | null; + revokes_receipt_id: string | null; +} + +function mapConsentReceiptRow(row: ConsentReceiptRow): StoredConsentReceipt { + const base = { + id: row.id, + accountId: row.account_id, + appSlug: row.app_slug, + provider: row.provider, + createdAt: normalizeTimestamp(row.created_at), + }; + if (row.kind === "revocation") { + return { ...base, kind: "revocation", revokesReceiptId: row.revokes_receipt_id ?? "" }; + } + return { + ...base, + kind: "grant", + scopesAsked: parseScopes(row.scopes_asked ?? ""), + scopesGranted: parseScopes(row.scopes_granted ?? ""), + consentPageDigest: row.consent_page_digest ?? "", + }; +} + function mapPendingLinkRow(row: PendingLinkRow): StoredPendingLink { const link: StoredPendingLink = { id: row.id, @@ -421,6 +456,7 @@ export const STORE_TABLE_PRIVILEGES: Readonly { + const grant = input.kind === "grant" ? input : null; + const result = await this.pool.query( + ` + INSERT INTO consent_receipts ( + id, kind, account_id, app_slug, provider, created_at, + scopes_asked, scopes_granted, consent_page_digest, revokes_receipt_id + ) + VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10) + RETURNING * + `, + [ + randomUUID(), + input.kind, + input.accountId, + input.appSlug, + input.provider, + input.createdAt, + grant ? grant.scopesAsked.join(" ") : null, + grant ? grant.scopesGranted.join(" ") : null, + grant ? grant.consentPageDigest : null, + input.kind === "revocation" ? input.revokesReceiptId : null, + ] + ); + return mapConsentReceiptRow(expectRow(result.rows[0], "createConsentReceipt")); + } + + async listConsentReceipts(accountId: string): Promise { + const result = await this.pool.query( + `SELECT * FROM consent_receipts WHERE account_id = $1 ORDER BY created_at, id`, + [accountId] + ); + return result.rows.map(mapConsentReceiptRow); + } + async createAuditEvent(input: CreateAuditEventInput): Promise { await this.pool.query( ` diff --git a/src/store/schema.ts b/src/store/schema.ts index 607445c..9c87dff 100644 --- a/src/store/schema.ts +++ b/src/store/schema.ts @@ -180,6 +180,24 @@ CREATE TABLE IF NOT EXISTS entitlement_snapshots ( UNIQUE(account_id, provider, scope) ); +-- Consent receipts are append-only (the store role has INSERT and SELECT +-- only): a revocation is a row that names the grant it takes back. +CREATE TABLE IF NOT EXISTS consent_receipts ( + id TEXT PRIMARY KEY, + kind TEXT NOT NULL, + account_id TEXT NOT NULL REFERENCES accounts(id) ON DELETE CASCADE, + app_slug TEXT NOT NULL, + provider TEXT NOT NULL, + created_at TIMESTAMPTZ NOT NULL, + scopes_asked TEXT, + scopes_granted TEXT, + consent_page_digest TEXT, + revokes_receipt_id TEXT +); + +CREATE INDEX IF NOT EXISTS consent_receipts_account_idx + ON consent_receipts(account_id, created_at); + CREATE TABLE IF NOT EXISTS audit_events ( id TEXT PRIMARY KEY, account_id TEXT, diff --git a/src/store/types.ts b/src/store/types.ts index 982bccc..4c4ce17 100644 --- a/src/store/types.ts +++ b/src/store/types.ts @@ -252,6 +252,31 @@ export interface StoredPrivateCommandReceipt { export type CreatePrivateCommandReceiptInput = StoredPrivateCommandReceipt; +/** + * What a person agreed to, or took back. Append-only: a grant row is never + * edited, and a revocation is a second row naming it, so a grant is live + * exactly when no revocation names it. `scopesAsked` is what Heimdall sent the + * provider, `scopesGranted` what the provider returned, `consentPageDigest` + * the hash of the wording the person was shown. + */ +export type StoredConsentReceipt = { + id: string; + accountId: string; + appSlug: AppSlug; + provider: Provider; + createdAt: string; +} & ( + | { kind: "grant"; scopesAsked: string[]; scopesGranted: string[]; consentPageDigest: string } + | { kind: "revocation"; revokesReceiptId: string } +); + +/** The store mints `id`; a caller cannot choose it. */ +export type CreateConsentReceiptInput = StoredConsentReceipt extends infer R + ? R extends StoredConsentReceipt + ? Omit + : never + : never; + export interface HeimdallStore { ensureSchema(): Promise; close(): Promise; @@ -325,4 +350,7 @@ export interface HeimdallStore { */ claimOAuthStateUse(input: ClaimOAuthStateUseInput): Promise; createAuditEvent(input: CreateAuditEventInput): Promise; + createConsentReceipt(input: CreateConsentReceiptInput): Promise; + /** Every receipt the account holds, oldest first. */ + listConsentReceipts(accountId: string): Promise; } diff --git a/tests/joystick-consent.test.ts b/tests/joystick-consent.test.ts index 6881f8f..3d4691f 100644 --- a/tests/joystick-consent.test.ts +++ b/tests/joystick-consent.test.ts @@ -1,62 +1,441 @@ -import { afterEach, describe, expect, it } from "vitest"; +import { createHash } from "node:crypto"; +import { afterEach, describe, expect, it, vi } from "vitest"; import { type FastifyInstance } from "fastify"; import { buildApp } from "../src/app.js"; -import { createTestConfig } from "./oauth-flow.js"; +import { consentDigest, consentLines, type ConsentAsk } from "../src/consent.js"; +import { type OAuthProviderRuntime } from "../src/oauth.js"; +import { providerCatalog } from "../src/providers.js"; +import { InMemoryStore } from "../src/store/index.js"; +import { createTestConfig, setCookieOf, stateOf } from "./oauth-flow.js"; -// SKETCH for docs/joystick-consent-flow.md. Skipped: every test here names a -// behaviour the consent cut must build. Remove `.skip` as each one lands. +// The consent cut for managed custody (docs/joystick-consent-flow.md): the ask, +// the typed refusal, the receipt, and the signed-in page that lists and revokes. const apps: FastifyInstance[] = []; afterEach(async () => { + vi.restoreAllMocks(); while (apps.length) await apps.pop()?.close(); }); -async function creatorConnectStart(app: FastifyInstance) { +const defaultScopes = providerCatalog.joystick.defaultScopes; +const secret = { "x-heimdall-app-secret": "streampixels-secret" }; +const form = { "content-type": "application/x-www-form-urlencoded" }; + +/** A Joystick that returns whatever `code-` names, granting only `granted`. */ +function joystick(granted: string[] = ["identity:read", "stream:read"]): OAuthProviderRuntime { + return { + async exchangeAuthorizationCode({ code }) { + return { accessToken: `joy-access-${code}`, refreshToken: `joy-refresh-${code}`, tokenType: "Bearer", scope: granted, expiresAt: "2099-01-01T00:00:00.000Z", raw: {} }; + }, + async resolveIdentity({ accessToken }) { + const id = accessToken.replace("joy-access-code-", ""); + return { provider: "joystick", providerUserId: `joy-${id}`, username: id, profile: { id } }; + }, + async evaluateEntitlements() { + return { facts: [], snapshots: [] }; + }, + }; +} + +async function newApp(options: { granted?: string[]; callbacks?: string[] } = {}) { + const store = new InMemoryStore(); + const config = createTestConfig(); + if (options.callbacks) config.appBackendCallbacks = { streampixels: options.callbacks }; + const app = await buildApp({ config, store, oauthRuntimes: { joystick: joystick(options.granted) } }); + apps.push(app); + return { app, store }; +} + +async function startConnect(app: FastifyInstance, handoff: Record = { kind: "browser_completion" }) { const response = await app.inject({ method: "POST", url: "/v1/oauth/joystick/start", - headers: { "x-heimdall-app-secret": "streampixels-secret" }, + headers: secret, payload: { appSlug: "streampixels", mode: "connect", connection: { kind: "creator", targetId: "creator-1" }, returnTo: "https://streampixels.gamecult.org/settings", - handoff: { kind: "browser_completion" }, + handoff, }, }); expect(response.statusCode).toBe(201); - const url = new URL(response.json().authorizationUrl as string); - return `${url.pathname}${url.search}`; + return stateOf(response.json()); } -describe.skip("Joystick consent flow (draft)", () => { - it("launch shows a Heimdall ask naming app, provider and scopes, and does not redirect", async () => { - const app = await buildApp({ config: createTestConfig() }); - apps.push(app); - const launch = await app.inject({ method: "GET", url: await creatorConnectStart(app), headers: { accept: "text/html" } }); - expect(launch.statusCode).toBe(200); - expect(launch.headers.location).toBeUndefined(); - for (const needle of ["StreamPixels", "Joystick", "identity:read", "subscribers:read", "refresh token"]) { - expect(launch.body).toContain(needle); +const launchUrl = (state: string) => `/v1/oauth/joystick/launch?state=${encodeURIComponent(state)}`; +const cookieOf = (response: { headers: Record }) => + setCookieOf(response).find((value) => value.startsWith("__Host-heimdall-oauth-"))!.split(";")[0]!; + +/** The browser is shown the ask. */ +async function seeAsk(app: FastifyInstance, state: string) { + const response = await app.inject({ method: "GET", url: launchUrl(state), headers: { accept: "text/html" } }); + expect(response.statusCode).toBe(200); + return { page: response, cookie: cookieOf(response) }; +} + +function answer(app: FastifyInstance, state: string, decision: "continue" | "decline", cookie?: string, accept = "text/html") { + return app.inject({ + method: "POST", + url: "/v1/oauth/joystick/consent", + headers: { ...form, accept, ...(cookie ? { cookie } : {}) }, + payload: new URLSearchParams({ state, decision }).toString(), + }); +} + +function callback(app: FastifyInstance, state: string, cookie: string, query: string, accept = "application/json") { + return app.inject({ + method: "GET", + url: `/v1/oauth/joystick/callback?state=${encodeURIComponent(state)}&${query}`, + headers: { cookie, accept }, + }); +} + +/** Ask, accept, and complete as Joystick user `user`; returns the callback's JSON. */ +async function grantAs(app: FastifyInstance, user: string) { + const state = await startConnect(app); + const { cookie } = await seeAsk(app, state); + const go = await answer(app, state, "continue", cookie); + expect(go.statusCode).toBe(302); + const done = await callback(app, state, cookie, `code=code-${user}`); + expect(done.statusCode).toBe(201); + return done.json() as { accessToken: string; consentReceiptId: string; account: { id: string }; session: { accountId: string } }; +} + +const bearer = (token: string) => ({ authorization: `Bearer ${token}` }); +const grantsOf = async (app: FastifyInstance, token: string) => + (await app.inject({ method: "GET", url: "/v1/me/grants", headers: bearer(token) })).json() as { grants: Array>; receipts: Array> }; +const resolveCredential = (app: FastifyInstance, accountId: string) => + app.inject({ method: "POST", url: "/v1/apps/streampixels/managed-credentials/resolve", headers: secret, payload: { accountId, provider: "joystick" } }); + +describe("the ask", () => { + it("launch shows a Heimdall page naming app, provider, scopes and custody, and does not redirect", async () => { + const { app } = await newApp(); + const { page } = await seeAsk(app, await startConnect(app)); + expect(page.headers.location).toBeUndefined(); + for (const needle of ["StreamPixels", "Joystick", ...defaultScopes, "refresh token", "streampixels.gamecult.org", "Continue to Joystick", "No, return to the app"]) { + expect(page.body).toContain(needle); } + expect(page.body).not.toContain(" { - // POST the decline form from the launch page with the binding cookie; - // expect result {error: "consent_refused", by: "viewer"}, an audit event - // "consent_refused", no managed credential row, and a second launch refused. - expect.fail("not built"); + it("viewing the ask claims nothing: the launch is still spendable once after any number of views", async () => { + const { app } = await newApp(); + const state = await startConnect(app); + await seeAsk(app, state); + const { cookie } = await seeAsk(app, state); + expect((await answer(app, state, "continue", cookie)).statusCode).toBe(302); + const again = await answer(app, state, "continue", cookie, "application/json"); + expect(again.statusCode).toBe(400); + expect(again.json()).toEqual({ error: "state_already_launched" }); }); - it("a provider access_denied is consent_refused by provider, distinct from provider_error", async () => { - expect.fail("not built"); + it("Continue sends exactly the scopes the page listed", async () => { + const { app } = await newApp(); + const state = await startConnect(app); + const { cookie } = await seeAsk(app, state); + const go = await answer(app, state, "continue", cookie); + expect(go.statusCode).toBe(302); + const target = new URL(go.headers.location as string); + expect(target.origin).toBe("https://joystick.tv"); + expect(target.searchParams.get("scope")).toBe(defaultScopes.join(" ")); }); - it("a granted completion writes one receipt with asked and granted scopes and the page digest", async () => { - expect.fail("not built"); + it("a flow with no custody (sign-in through an identity provider) gets no ask and redirects as before", async () => { + const { app } = await newApp(); + const start = await app.inject({ + method: "POST", + url: "/v1/oauth/twitch/start", + headers: secret, + payload: { appSlug: "streampixels", mode: "sign_in", returnTo: "https://streampixels.gamecult.org/", handoff: { kind: "browser_completion" } }, + }); + expect(start.statusCode).toBe(201); + const launch = await app.inject({ method: "GET", url: `/v1/oauth/twitch/launch?state=${encodeURIComponent(stateOf(start.json()))}`, headers: { accept: "text/html" } }); + expect(launch.statusCode).toBe(302); }); - it("the receipt page is readable only by the browser or account that consented, and revoke stamps revokedAt without editing the grant row", async () => { - expect.fail("not built"); + it("an answer without the cookie the ask set is refused and spends nothing", async () => { + const { app } = await newApp(); + const state = await startConnect(app); + const { cookie } = await seeAsk(app, state); + for (const decision of ["continue", "decline"] as const) { + const stranger = await answer(app, state, decision, undefined, "application/json"); + expect(stranger.statusCode, decision).toBe(400); + expect(stranger.json(), decision).toEqual({ error: "state_not_bound" }); + } + expect((await answer(app, state, "continue", cookie)).statusCode).toBe(302); + }); + + it("the consent route refuses a flow that has no ask", async () => { + const { app } = await newApp(); + const start = await app.inject({ + method: "POST", + url: "/v1/oauth/twitch/start", + headers: secret, + payload: { appSlug: "streampixels", mode: "sign_in", returnTo: "https://streampixels.gamecult.org/", handoff: { kind: "browser_completion" } }, + }); + const state = stateOf(start.json()); + const response = await app.inject({ + method: "POST", + url: "/v1/oauth/twitch/consent", + headers: form, + payload: new URLSearchParams({ state, decision: "continue" }).toString(), + }); + expect(response.statusCode).toBe(400); + expect(response.json()).toEqual({ error: "consent_not_required" }); + }); +}); + +describe("the wording digest", () => { + const ask: ConsentAsk = { appSlug: "streampixels", provider: "joystick", scopes: ["identity:read"], returnOrigin: "https://streampixels.gamecult.org" }; + it("is the sha-256 of the lines shown, and moves with the app, provider, scopes and origin", () => { + expect(consentDigest(ask)).toBe(createHash("sha256").update(consentLines(ask).join("\n"), "utf8").digest("hex")); + const variants: ConsentAsk[] = [ + { ...ask, appSlug: "bifrost" }, + { ...ask, provider: "twitch" }, + { ...ask, scopes: ["identity:read", "chat:read"] }, + { ...ask, returnOrigin: "https://elsewhere.example" }, + ]; + for (const variant of variants) expect(consentDigest(variant)).not.toBe(consentDigest(ask)); + }); +}); + +describe("refusal", () => { + it("declining yields consent_refused by the viewer, stores nothing, and spends the state", async () => { + const { app, store } = await newApp(); + const state = await startConnect(app); + const { cookie } = await seeAsk(app, state); + const no = await answer(app, state, "decline", cookie, "application/json"); + expect(no.statusCode).toBe(400); + expect(no.json()).toMatchObject({ error: "consent_refused", by: "viewer", provider: "joystick" }); + + // Nothing launches or completes afterwards, and nothing was kept. + expect((await answer(app, state, "continue", cookie, "application/json")).json()).toEqual({ error: "state_already_launched" }); + expect((await callback(app, state, cookie, "code=code-a")).json()).toEqual({ error: "state_already_used" }); + expect(await store.findStoredLinkedIdentity("joystick", "joy-a")).toBeNull(); + const events = [...(store as unknown as { auditEvents: Map }).auditEvents.values()]; + expect(events.filter((event) => event.eventType === "consent_refused").map((event) => event.eventPayloadJson)).toEqual([ + { provider: "joystick", mode: "connect", by: "viewer" }, + ]); + }); + + it("the browser sees a 'Not Connected' page, not an authentication failure", async () => { + const { app } = await newApp(); + const state = await startConnect(app); + const { cookie } = await seeAsk(app, state); + const no = await answer(app, state, "decline", cookie); + expect(no.statusCode).toBe(200); + expect(no.body).toContain("Not Connected"); + expect(no.body).toContain("consent_refused"); + expect(no.body).not.toContain("Authentication Failed"); + }); + + it("an access_denied from the provider is consent_refused by the provider, distinct from provider_error", async () => { + const { app, store } = await newApp(); + const denied = await newFlow(app); + const response = await callback(app, denied.state, denied.cookie, "error=access_denied"); + expect(response.statusCode).toBe(400); + expect(response.json()).toMatchObject({ error: "consent_refused", by: "provider" }); + + const faulty = await newFlow(app); + expect((await callback(app, faulty.state, faulty.cookie, "error=server_error")).json().error).toBe("provider_error"); + const events = [...(store as unknown as { auditEvents: Map }).auditEvents.values()]; + expect(events.filter((event) => event.eventType === "consent_refused")).toHaveLength(1); + }); + + it("a backend_callback app is told, with who refused", async () => { + const callbackUrl = "https://streampixels.gamecult.org/api/heimdall/callback"; + const { app } = await newApp({ callbacks: [callbackUrl] }); + const delivered: Array> = []; + vi.spyOn(globalThis, "fetch").mockImplementation(async (_url, init) => { + delivered.push(JSON.parse(String(init?.body))); + return new Response("ok", { status: 200 }); + }); + const handoff = { kind: "backend_callback", callbackUrl, attemptId: "attempt-1" }; + + const byViewer = await startConnect(app, handoff); + const { cookie } = await seeAsk(app, byViewer); + await answer(app, byViewer, "decline", cookie); + const byProvider = await startConnect(app, handoff); + const second = await seeAsk(app, byProvider); + await answer(app, byProvider, "continue", second.cookie); + await callback(app, byProvider, second.cookie, "error=access_denied"); + + expect(delivered.map((payload) => [payload.status, payload.error, payload.by])).toEqual([ + ["error", "consent_refused", "viewer"], + ["error", "consent_refused", "provider"], + ]); + }); +}); + +async function newFlow(app: FastifyInstance) { + const state = await startConnect(app); + const { cookie } = await seeAsk(app, state); + expect((await answer(app, state, "continue", cookie)).statusCode).toBe(302); + return { state, cookie }; +} + +describe("the receipt", () => { + it("a granted completion writes one receipt with asked and granted scopes and the digest of the wording shown", async () => { + const { app, store } = await newApp({ granted: ["identity:read", "stream:read"] }); + const done = await grantAs(app, "a"); + const receipts = await store.listConsentReceipts(done.account.id); + expect(receipts).toHaveLength(1); + const ask: ConsentAsk = { appSlug: "streampixels", provider: "joystick", scopes: defaultScopes, returnOrigin: "https://streampixels.gamecult.org" }; + expect(receipts[0]).toMatchObject({ + id: done.consentReceiptId, + kind: "grant", + accountId: done.account.id, + appSlug: "streampixels", + provider: "joystick", + scopesAsked: defaultScopes, + scopesGranted: ["identity:read", "stream:read"], + consentPageDigest: consentDigest(ask), + }); + }); + + it("a refusal leaves no receipt", async () => { + const { app, store } = await newApp(); + const state = await startConnect(app); + const { cookie } = await seeAsk(app, state); + await answer(app, state, "decline", cookie); + expect(await store.listConsentReceipts("anyone")).toEqual([]); + expect((await store.findStoredLinkedIdentity("joystick", "joy-a"))).toBeNull(); + }); + + it("the success page names the receipt", async () => { + const { app } = await newApp(); + const state = await startConnect(app); + const { cookie } = await seeAsk(app, state); + await answer(app, state, "continue", cookie); + const page = await callback(app, state, cookie, "code=code-a", "text/html"); + expect(page.statusCode).toBe(200); + expect(page.body).toMatch(/receipt [0-9a-f-]{36}/); + }); +}); + +describe("my grants", () => { + it("is closed to anyone without a live Heimdall access token", async () => { + const { app } = await newApp(); + for (const headers of [{}, bearer("not-a-token")]) { + const response = await app.inject({ method: "GET", url: "/v1/me/grants", headers }); + expect(response.statusCode).toBe(401); + expect(response.json().error).toBe("sign_in_required"); + } + const link = await app.inject({ method: "POST", url: "/v1/me/grants/link" }); + expect(link.statusCode).toBe(401); + const revoke = await app.inject({ method: "POST", url: "/v1/me/grants/x/revoke" }); + expect(revoke.statusCode).toBe(401); + }); + + it("lists the signed-in account's grants and receipts, and no one else's", async () => { + const { app } = await newApp(); + const a = await grantAs(app, "a"); + const b = await grantAs(app, "b"); + const mine = await grantsOf(app, a.accessToken); + expect(mine.grants).toHaveLength(1); + expect(mine.grants[0]).toMatchObject({ id: a.consentReceiptId, status: "active", provider: "joystick", appSlug: "streampixels", scopesGranted: ["identity:read", "stream:read"] }); + expect(JSON.stringify(mine)).not.toContain(b.consentReceiptId); + expect(mine.receipts.map((receipt) => receipt.accountId)).toEqual([a.account.id]); + }); + + it("revoke takes effect on the next token use, edits no row, and receipts the revocation", async () => { + const { app, store } = await newApp(); + const a = await grantAs(app, "a"); + expect((await resolveCredential(app, a.account.id)).statusCode).toBe(200); + const before = await store.listConsentReceipts(a.account.id); + + const revoke = await app.inject({ method: "POST", url: `/v1/me/grants/${a.consentReceiptId}/revoke`, headers: bearer(a.accessToken) }); + expect(revoke.statusCode).toBe(200); + expect(revoke.json().revoked).toEqual([a.consentReceiptId]); + + const next = await resolveCredential(app, a.account.id); + expect(next.statusCode).toBe(410); + expect(next.json().error).toBe("managed_credential_revoked"); + + const after = await store.listConsentReceipts(a.account.id); + expect(after).toHaveLength(2); + expect(after[0]).toEqual(before[0]); + expect(after[1]).toMatchObject({ kind: "revocation", revokesReceiptId: a.consentReceiptId, accountId: a.account.id }); + const view = (await grantsOf(app, a.accessToken)).grants[0]!; + expect(view).toMatchObject({ status: "revoked", revocationReceiptId: after[1]!.id }); + expect(view.revokedAt).toBe(after[1]!.createdAt); + }); + + it("revoke is the owner's alone: another account's grant id is not found and its credential is untouched", async () => { + const { app } = await newApp(); + const a = await grantAs(app, "a"); + const b = await grantAs(app, "b"); + const attempt = await app.inject({ method: "POST", url: `/v1/me/grants/${a.consentReceiptId}/revoke`, headers: bearer(b.accessToken) }); + expect(attempt.statusCode).toBe(404); + expect((await resolveCredential(app, a.account.id)).statusCode).toBe(200); + expect((await resolveCredential(app, b.account.id)).statusCode).toBe(200); + }); + + it("revoking twice changes nothing the second time", async () => { + const { app, store } = await newApp(); + const a = await grantAs(app, "a"); + const url = `/v1/me/grants/${a.consentReceiptId}/revoke`; + await app.inject({ method: "POST", url, headers: bearer(a.accessToken) }); + const second = await app.inject({ method: "POST", url, headers: bearer(a.accessToken) }); + expect(second.statusCode).toBe(200); + expect(second.json().revoked).toEqual([]); + expect(await store.listConsentReceipts(a.account.id)).toHaveLength(2); + }); + + it("a fresh connection after a revoke is a new grant, live again, and the old one stays revoked", async () => { + const { app } = await newApp(); + const first = await grantAs(app, "a"); + await app.inject({ method: "POST", url: `/v1/me/grants/${first.consentReceiptId}/revoke`, headers: bearer(first.accessToken) }); + const second = await grantAs(app, "a"); + expect(second.consentReceiptId).not.toBe(first.consentReceiptId); + expect((await resolveCredential(app, second.account.id)).statusCode).toBe(200); + const grants = (await grantsOf(app, second.accessToken)).grants; + expect(grants.map((grant) => [grant.id, grant.status])).toEqual([ + [first.consentReceiptId, "revoked"], + [second.consentReceiptId, "active"], + ]); + }); + + it("a browser with no session opens the page from a minted link and revokes with one form post", async () => { + const { app } = await newApp(); + const a = await grantAs(app, "a"); + const link = await app.inject({ method: "POST", url: "/v1/me/grants/link", headers: bearer(a.accessToken) }); + expect(link.statusCode).toBe(201); + const url = new URL(link.json().url as string); + const page = await app.inject({ method: "GET", url: `${url.pathname}${url.search}`, headers: { accept: "text/html" } }); + expect(page.statusCode).toBe(200); + expect(page.body).toContain(a.consentReceiptId); + expect(page.body).toContain("Take this back"); + expect(page.body).not.toContain(" { + const { app } = await newApp(); + const a = await grantAs(app, "a"); + for (const t of [a.accessToken, "garbage", ""]) { + const response = await app.inject({ method: "GET", url: `/v1/me/grants?t=${encodeURIComponent(t)}` }); + expect(response.statusCode, t).toBe(401); + const revoke = await app.inject({ + method: "POST", + url: `/v1/me/grants/${a.consentReceiptId}/revoke`, + headers: form, + payload: new URLSearchParams({ t }).toString(), + }); + expect(revoke.statusCode, t).toBe(401); + } + expect((await resolveCredential(app, a.account.id)).statusCode).toBe(200); }); }); diff --git a/tests/oauth-flow.ts b/tests/oauth-flow.ts index 1a7fbf4..b85b2ce 100644 --- a/tests/oauth-flow.ts +++ b/tests/oauth-flow.ts @@ -117,7 +117,18 @@ export function setCookieOf(response: { headers: Record }): str async function followLaunch(app: FastifyInstance, state: string): Promise { const provider = decodeJwt(state).payload.provider as string; - const response = await app.inject({ method: "GET", url: `/v1/oauth/${provider}/launch?state=${encodeURIComponent(state)}` }); + let response = await app.inject({ method: "GET", url: `/v1/oauth/${provider}/launch?state=${encodeURIComponent(state)}` }); + if (response.statusCode === 200) { + // Heimdall's ask (managed custody): the person says Continue, with the cookie the ask set. + const asked = setCookieOf(response).find((value) => value.startsWith("__Host-heimdall-oauth-")); + expect(asked, "the ask sets the binding cookie").toBeDefined(); + response = await app.inject({ + method: "POST", + url: `/v1/oauth/${provider}/consent`, + headers: { "content-type": "application/x-www-form-urlencoded", cookie: (asked as string).split(";")[0] as string }, + payload: new URLSearchParams({ state, decision: "continue" }).toString(), + }); + } expect(response.statusCode, "launch").toBe(302); const set = setCookieOf(response).find((value) => value.startsWith("__Host-heimdall-oauth-")); expect(set, "launch sets the binding cookie").toBeDefined(); @@ -143,8 +154,5 @@ export async function launchWithRedirect(app: FastifyInstance, start: StartBody) /** The provider URL a browser is redirected to once it has followed authorizationUrl through the launch hop. */ export async function providerRedirect(app: FastifyInstance, start: StartBody): Promise { - const url = new URL(start.authorizationUrl); - const response = await app.inject({ method: "GET", url: `${url.pathname}${url.search}` }); - expect(response.statusCode, "launch").toBe(302); - return new URL(response.headers.location as string); + return (await followLaunch(app, stateOf(start))).providerUrl; } diff --git a/tests/oauth-state-binding.test.ts b/tests/oauth-state-binding.test.ts index 9f576e8..1bffc19 100644 --- a/tests/oauth-state-binding.test.ts +++ b/tests/oauth-state-binding.test.ts @@ -299,14 +299,15 @@ describe("OAuth state binding", () => { expect(await claim("a", 1_000_000 + 30_000)).toBe(true); }); - it("a provider error from the launching browser still denies the attempt, once", async () => { + it("a provider refusal from the launching browser still denies the attempt, once", async () => { const app = await newApp(); const start = await bifrostStart(app); const victim = await launchFlow(app, start); const denied = await callback(app, victim.state, victim.cookie, "error=access_denied"); expect(denied.statusCode).toBe(400); - expect(denied.json().error).toBe("provider_error"); + expect(denied.json().error).toBe("consent_refused"); + expect(denied.json().by).toBe("provider"); const replay = await callback(app, victim.state, victim.cookie, "error=access_denied"); expect(replay.json()).toEqual({ error: "state_already_used" }); }); diff --git a/tests/store.test.ts b/tests/store.test.ts index f17a834..684aa41 100644 --- a/tests/store.test.ts +++ b/tests/store.test.ts @@ -270,9 +270,10 @@ describe("PostgresStore.checkSchema", () => { "oauth_state_uses", "capability_grants", "entitlement_snapshots", + "consent_receipts", "audit_events", ]); - expect(REQUIRED_COLUMNS).toHaveLength(101); + expect(REQUIRED_COLUMNS).toHaveLength(111); expect(REQUIRED_COLUMNS).toEqual( expect.arrayContaining([ { table: "auth_completions", column: "code", type: "TEXT", nullable: false }, @@ -283,7 +284,7 @@ describe("PostgresStore.checkSchema", () => { { table: "auth_completions", column: "attempt_id", type: "TEXT", nullable: true }, ]) ); - expect(REQUIRED_KEYS).toHaveLength(14); + expect(REQUIRED_KEYS).toHaveLength(15); expect(REQUIRED_KEYS).toEqual( expect.arrayContaining([ { table: "linked_identities", columns: "provider,provider_user_id", predicate: "" }, @@ -418,6 +419,9 @@ async function exerciseStore(store: PostgresStore): Promise> { expect(await s.claimOAuthStateUse(stateUse)).toBe(true); expect(await s.claimOAuthStateUse(stateUse)).toBe(false); expect(await s.claimOAuthStateUse({ ...stateUse, phase: "callback" })).toBe(true); + const grant = await s.createConsentReceipt({ kind: "grant", accountId: account.id, appSlug: "streampixels", provider: "joystick", createdAt: now, scopesAsked: ["a", "b"], scopesGranted: ["a"], consentPageDigest: "d" }); + await s.createConsentReceipt({ kind: "revocation", accountId: account.id, appSlug: "streampixels", provider: "joystick", createdAt: later, revokesReceiptId: grant.id }); + expect((await s.listConsentReceipts(account.id)).map((r) => r.kind)).toEqual(["grant", "revocation"]); await s.createAuditEvent({ eventType: "probe", eventPayloadJson: {}, createdAt: now }); return called; }