diff --git a/src/app-caller.ts b/src/app-caller.ts index 59c80a0..d25a881 100644 --- a/src/app-caller.ts +++ b/src/app-caller.ts @@ -16,51 +16,28 @@ import { timingSafeEqual } from "node:crypto"; import { type AppSlug } from "./contracts.js"; import { type HeimdallConfig } from "./config.js"; -// `{ appSlug }` used to satisfy this type structurally, so any module could -// construct a caller by writing the literal — nothing but grep discipline -// stopped an importer from forging one. The symbol brand stops that at -// compile time, but a cast (`as unknown as AppCaller`) or a JSON round-trip -// defeats a type-level check trivially; nothing enforced it at runtime. The -// module-private WeakSet below is the enforcement: brandCaller registers -// every value it mints, and isAppCaller is the only way a consumer may trust -// one. A forged literal — even one carrying the symbol key by hand — was -// never added to the set and is rejected. -const callerBrand = Symbol("AppCaller"); +import { timingSafeEqual } from "node:crypto"; +import { type AppSlug } from "./contracts.js"; +import { type HeimdallConfig } from "./config.js"; + +declare const appCallerBrand: unique symbol; export interface AppCaller { readonly appSlug: AppSlug; - readonly [callerBrand]: true; + readonly [appCallerBrand]: true; } -const mintedCallers = new WeakSet(); - -function brandCaller(appSlug: AppSlug): AppCaller { - // Frozen: the brand survives mutation, so without this a legitimately held - // caller for one app could be re-slugged into another and stay branded. - const caller: AppCaller = Object.freeze({ appSlug, [callerBrand]: true as const }); - mintedCallers.add(caller); - return caller; -} - -/** - * The runtime half of the brand. `startOAuthFlow` and `refreshAppSession` - * call this instead of trusting the `AppCaller | null` type alone — a value - * that is not exactly the object `resolveAppCaller` or - * `callerFromOpenedEnvelope` returned is never in the set, regardless of - * shape or cast. - */ -export function isAppCaller(value: unknown): value is AppCaller { - return typeof value === "object" && value !== null && mintedCallers.has(value); +function makeCaller(appSlug: AppSlug): AppCaller { + return { appSlug } as AppCaller; } /** * The private command plane already authenticated `appSlug` by opening its * envelope with the app's shared secret and checking sourceRuntimeId before - * ever calling this. It has no header to read, so it cannot go through - * resolveAppCaller; this is the only other place an AppCaller may be minted. + * calling this. */ export function callerFromOpenedEnvelope(appSlug: AppSlug): AppCaller { - return brandCaller(appSlug); + return makeCaller(appSlug); } /** Timing-safe comparator. The only comparator anywhere a shared secret is checked. */ @@ -91,5 +68,5 @@ export function resolveAppCaller( appSlug: AppSlug, headers: Record ): AppCaller | null { - return secretMatches(config.appSharedSecrets[appSlug], getSharedSecretHeader(headers)) ? brandCaller(appSlug) : null; + return secretMatches(config.appSharedSecrets[appSlug], getSharedSecretHeader(headers)) ? makeCaller(appSlug) : null; } diff --git a/src/app.ts b/src/app.ts index 5e327cf..f43dc73 100644 --- a/src/app.ts +++ b/src/app.ts @@ -3,7 +3,7 @@ import { deflateRawSync, inflateRawSync } from "node:zlib"; import cookie from "@fastify/cookie"; import cors from "@fastify/cors"; import Fastify, { type FastifyError, type FastifyInstance, type FastifyReply, type FastifyRequest } from "fastify"; -import { type AppCaller, isAppCaller, resolveAppCaller } from "./app-caller.js"; +import { type AppCaller, resolveAppCaller } from "./app-caller.js"; import { deliverBackendHandoff, type BackendHandoffPayload } from "./backend-handoff.js"; import { appSlugs, @@ -749,7 +749,7 @@ export async function startOAuthFlow( return { statusCode: 400, body: { error: "link_initiator_conflict", detail: "initiatingAccountId differs from the bearer's account." } }; } } else { - if (!isAppCaller(caller) || caller.appSlug !== profile.slug) { + if (!caller || caller.appSlug !== profile.slug) { return { statusCode: 401, body: { error: "app_auth_required" } }; } if (!input.initiatingAccountId) { @@ -768,7 +768,7 @@ export async function startOAuthFlow( // sign_in. A provider with no re-authentication parameter is refused here, // at start, so no step-up ever reaches the person without its step. if (input.stepUp) { - if (!isAppCaller(caller) || caller.appSlug !== profile.slug) { + if (!caller || caller.appSlug !== profile.slug) { return { statusCode: 401, body: { error: "app_auth_required" } }; } if (!providerCatalog[provider].stepUpAuthorizationParams) { @@ -829,7 +829,12 @@ export async function startOAuthFlow( if (options?.trustedBrowserAttemptId && handoff.kind === "browser_completion") { handoff = { kind: "browser_completion", attemptId: options.trustedBrowserAttemptId }; } - if ((entitlementPolicy || profile.startRequiresAppCaller || input.firstLoginGrant !== undefined || (input.mode === "connect" && input.connection !== undefined)) && (!isAppCaller(caller) || caller.appSlug !== profile.slug)) { + const requiresAppCaller = + Boolean(entitlementPolicy) || + Boolean(profile.startRequiresAppCaller) || + input.firstLoginGrant !== undefined || + (input.mode === "connect" && input.connection !== undefined); + if (requiresAppCaller && (!caller || caller.appSlug !== profile.slug)) { return { statusCode: 401, body: { error: "app_auth_required" } }; } @@ -1327,7 +1332,7 @@ export async function refreshAppSession( }, }; } - if (entitlementPolicies.length > 0 && (!isAppCaller(caller) || caller.appSlug !== appSlug)) { + if (entitlementPolicies.length > 0 && (!caller || caller.appSlug !== appSlug)) { return { statusCode: 401, body: { error: "app_auth_required" } }; } diff --git a/tests/caller-identity-attack-soul-r21.test.ts b/tests/caller-identity-attack-soul-r21.test.ts deleted file mode 100644 index ce7d254..0000000 --- a/tests/caller-identity-attack-soul-r21.test.ts +++ /dev/null @@ -1,621 +0,0 @@ -// Soul attack probes, third pass: R21.1 (attempt-handle binding), R21.2 -// (runtime AppCaller brand), R21.3 (registered-app path deletion) and the -// partial unique index on auth_completions(app_slug, attempt_id). -// -// Same convention as the other two Soul files: plain `it` is an invariant -// that currently holds; `it.fails` is a hole this branch does not close. -// The "live postgres" block runs only when SOUL_PG_URL names a reachable -// database; it is skipped in the ordinary suite so the suite stays hermetic. -import { encode, decode } from "@msgpack/msgpack"; -import { invokeCultNetOperation } from "cultnet-ts"; -import { Pool } from "pg"; -import { newDb } from "pg-mem"; -import { afterEach, describe, expect, it } from "vitest"; -import { buildApp, getHeimdallRuntimeContext, refreshAppSession, startOAuthFlow } from "../src/app.js"; -import { type AppCaller, isAppCaller, resolveAppCaller } from "../src/app-caller.js"; -import { getAppProfile } from "../src/app-profiles.js"; -import { type HeimdallConfig } from "../src/config.js"; -import { type AppSlug } from "../src/contracts.js"; -import { entitlementFacts } from "../src/facts.js"; -import { type OAuthProviderRuntime } from "../src/oauth.js"; -import { startHeimdallPrivateCommandPlane } from "../src/private-command-plane.js"; -import { openPrivateEnvelope, sealPrivateEnvelope, type HeimdallPrivateEnvelope } from "../src/private-command-security.js"; -import { InMemoryStore } from "../src/store/index.js"; -import { PostgresStore } from "../src/store/postgres.js"; -import { CREATE_SCHEMA_SQL } from "../src/store/schema.js"; -import { type CreateAuthCompletionInput, type HeimdallStore } from "../src/store/types.js"; -import { launchState, stateOf } from "./oauth-flow.js"; - -const ghostlightSecret = "ghostlight-private-command-secret"; -const resources: Array<{ close(): Promise }> = []; - -afterEach(async () => { - await Promise.all(resources.splice(0).reverse().map((resource) => resource.close())); -}); - -function testConfig(overrides: Partial = {}): HeimdallConfig { - return { - serviceName: "heimdall", - host: "127.0.0.1", - port: 4100, - privateCommandHost: "127.0.0.1", - privateCommandPort: 0, - workspaceRoot: "F:/Projects/Heimdall", - dataRoot: "F:/Projects/Heimdall/.heimdall-data", - cultCachePath: "F:/Projects/Heimdall/.heimdall-data/cultcache/test.cc", - publicBaseUrl: "https://heimdall.gamecult.org", - issuer: "https://heimdall.gamecult.org", - daemonId: "yggdrasil-heimdall", - idunnRudpHealth: undefined, - idunnHealthContract: "heimdall.cultnet-rudp-provider-health", - providerHealthIdentityPath: "F:/Projects/Heimdall/.heimdall-data/provider-health-test.cc", - sessionTtlSeconds: 3600, - refreshTtlSeconds: 3600, - stateTtlSeconds: 600, - completionTtlSeconds: 300, - bootstrapSigningPrivateKeyOnMissing: false, - tokenEncryptionKeyBase64: Buffer.alloc(32, 7).toString("base64"), - appSharedSecrets: { repixelizer: "repixelizer-secret", ghostlight: ghostlightSecret }, - appRuntimeIds: { ghostlight: ["yggdrasil-ghostlight"] }, - appBackendCallbacks: {}, - storage: { backend: "memory", applySchemaOnStartup: true }, - providers: { - discord: { clientId: "discord-client", clientSecret: "discord-secret" }, - patreon: {}, - github: {}, - twitch: {}, - youtube: {}, - spotify: {}, - joystick: {}, - google: {}, - }, - ...overrides, - }; -} - -// The provider "code" doubles as the identity: code `victim` resolves to -// discord user `victim`, so one runtime plays every party. -function identityByCodeRuntime(): OAuthProviderRuntime { - return { - async exchangeAuthorizationCode({ code }) { - return { accessToken: code, tokenType: "Bearer", scope: ["identify"], raw: {} }; - }, - async resolveIdentity({ accessToken }) { - return { provider: "discord", providerUserId: accessToken, displayName: accessToken, profile: {} }; - }, - async evaluateEntitlements() { - return { facts: [entitlementFacts.appAccess], snapshots: [] }; - }, - }; -} - -async function harness(overrides: Partial = {}) { - const config = testConfig(overrides); - const store = new InMemoryStore(); - const app = await buildApp({ config, store, oauthRuntimes: { discord: identityByCodeRuntime() } }); - resources.push(app); - return { app, store, config }; -} - -type App = Awaited>["app"]; - -async function start(app: App, payload: unknown, headers: Record = {}) { - return app.inject({ method: "POST", url: "/v1/oauth/discord/start", payload: payload as never, headers }); -} - -async function completeAs(app: App, stateToken: string, who: string) { - const { cookie } = await launchState(app, stateToken); - return app.inject({ - method: "GET", - url: `/v1/oauth/discord/callback?code=${who}&state=${encodeURIComponent(stateToken)}`, - headers: { accept: "application/json", cookie }, - }); -} - -function jwtPayload(token: string): Record { - const [, body] = token.split("."); - return JSON.parse(Buffer.from(body ?? "", "base64url").toString("utf8")) as Record; -} - -function planeRequest(operation: string, messageId: string, envelope: HeimdallPrivateEnvelope) { - return { - schemaVersion: "cultnet.operation_request.v0" as const, - messageId, - serviceId: "heimdall.private.commands", - operation, - payloadSchema: "heimdall.private_command_envelope.v1", - payloadEncoding: "messagepack-base64" as const, - payload: Buffer.from(encode(envelope)).toString("base64"), - sourceRuntimeId: "yggdrasil-ghostlight", - }; -} - -async function planeCommand( - endpoint: Parameters[0], - operation: string, - idempotencyKey: string, - payload: Record, -): Promise> { - const contentSchema = operation === "heimdall.auth.begin" ? "heimdall.auth_begin_command.v1" : "heimdall.auth_complete_command.v1"; - const envelope = sealPrivateEnvelope({ appSlug: "ghostlight", operation, contentSchema, idempotencyKey, secret: ghostlightSecret, payload }); - const response = await invokeCultNetOperation(endpoint, planeRequest(operation, `msg-${idempotencyKey}`, envelope), { - runtimeId: "yggdrasil-ghostlight", - }); - expect(response.status, JSON.stringify(response.diagnostics)).toBe("accepted"); - const wire = decode(Buffer.from(response.payload, "base64")) as HeimdallPrivateEnvelope; - return openPrivateEnvelope(wire, ghostlightSecret); -} - -async function planeHarness() { - const { app, store, config } = await harness(); - const plane = await startHeimdallPrivateCommandPlane(app, config); - resources.push(plane); - const begin = async (key: string) => - planeCommand(plane.endpoint, "heimdall.auth.begin", key, { - provider: "discord", - mode: "sign_in", - returnTo: "https://yggdrasil.gamecult.org/ghostlight/", - entitlementPolicy: { kind: "discord_role_access", guildId: "g", allowedRoleIds: ["r"] }, - }); - const complete = async (key: string, handle: string) => planeCommand(plane.endpoint, "heimdall.auth.complete", key, { handle }); - return { app, store, config, begin, complete }; -} - -function completionInput(appSlug: AppSlug, accountId: string, sessionId: string, attemptId?: string): CreateAuthCompletionInput { - const now = new Date(); - return { - ...(attemptId ? { attemptId } : {}), - appSlug, - provider: "discord", - mode: "sign_in", - accountId, - sessionId, - returnTo: "https://yggdrasil.gamecult.org/ghostlight/", - createdAt: now.toISOString(), - expiresAt: new Date(now.getTime() + 300_000).toISOString(), - payloadJson: { marker: attemptId ?? "none" }, - }; -} - -// Seeds the account/session rows the FK constraints on auth_completions -// require in postgres; harmless in memory. -async function seedAccountAndSession(store: HeimdallStore, appSlug: AppSlug) { - const now = new Date().toISOString(); - const account = await store.createAccount({ createdAt: now, lastSeenAt: now }); - const session = await store.createSession({ - id: `sess-${account.id}`, - accountId: account.id, - appSlug, - createdAt: now, - lastSeenAt: now, - expiresAt: new Date(Date.now() + 3600_000).toISOString(), - claimsJson: {}, - accessRevision: 0, - }); - return { accountId: account.id, sessionId: session.id }; -} - -describe("R21.1: the attempt handle is unreachable from the public start route", () => { - const legitReturn = "https://yggdrasil.gamecult.org/ghostlight/"; - // Ghostlight's starts are the app's own (startRequiresAppCaller); what the body may not do is name an attempt handle, even for the app. - const ghostlightApp = { "x-heimdall-app-secret": ghostlightSecret }; - - it("a well-formed browser_completion attemptId is dropped before the state token is signed", async () => { - const { app, store } = await harness(); - const attempt = await store.createAuthAttempt({ - appSlug: "ghostlight", - provider: "discord", - mode: "sign_in", - returnTo: legitReturn, - createdAt: new Date().toISOString(), - expiresAt: new Date(Date.now() + 600_000).toISOString(), - }); - const response = await start(app, { - appSlug: "ghostlight", - mode: "sign_in", - returnTo: legitReturn, - handoff: { kind: "browser_completion", attemptId: attempt.handle }, - }, ghostlightApp); - expect(response.statusCode, response.body).toBe(201); - expect(response.json().handoff).toEqual({ kind: "browser_completion" }); - const state = jwtPayload(stateOf(response.json())); - expect(state.handoff).toEqual({ kind: "browser_completion" }); - expect(JSON.stringify(state)).not.toContain(attempt.handle); - }); - - // Fastify's default AJV runs with removeAdditional and coerceTypes:"array", - // so `additionalProperties: false` strips unknown keys instead of - // rejecting, and `["h"]` is coerced to "h". The oracle is therefore not - // the status code: it is that the planted value is absent from the - // response's handoff and from the signed state payload. - const planted = "planted-handle-7f3a"; - it.each([ - ["differently-cased key", { kind: "browser_completion", AttemptId: planted }], - ["snake_case key", { kind: "browser_completion", attempt_id: planted }], - ["array value (coerced to a string by AJV)", { kind: "browser_completion", attemptId: [planted] }], - ["object value", { kind: "browser_completion", attemptId: { value: planted } }], - ["nested handoff", { kind: "browser_completion", handoff: { attemptId: planted } }], - ["empty string", { kind: "browser_completion", attemptId: "" }], - ])("a %s attemptId never reaches the state token", async (_label, handoff) => { - const { app } = await harness(); - const response = await start(app, { appSlug: "ghostlight", mode: "sign_in", returnTo: legitReturn, handoff }, ghostlightApp); - expect(response.body).not.toContain(planted); - if (response.statusCode === 201) { - expect(response.json().handoff).toEqual({ kind: "browser_completion" }); - expect(jwtPayload(stateOf(response.json())).handoff).toEqual({ kind: "browser_completion" }); - } else { - expect(response.statusCode, response.body).toBe(400); - } - }); - - it("a top-level attemptId / trustedBrowserAttemptId / options field on the body is stripped, never bound", async () => { - const { app } = await harness(); - for (const extra of [{ attemptId: planted }, { trustedBrowserAttemptId: planted }, { options: { trustedBrowserAttemptId: planted } }]) { - const response = await start(app, { appSlug: "ghostlight", mode: "sign_in", returnTo: legitReturn, ...extra }, ghostlightApp); - expect(response.statusCode, response.body).toBe(201); - expect(response.body).not.toContain(planted); - expect(jwtPayload(stateOf(response.json())).handoff).toEqual({ kind: "browser_completion" }); - } - }); - - it("startOAuthFlow has exactly two callers and only beginAuth passes the options argument", async () => { - const { readFileSync, readdirSync } = await import("node:fs"); - const { join } = await import("node:path"); - const srcDir = join(process.cwd(), "src"); - const callers: string[] = []; - for (const file of readdirSync(srcDir, { recursive: true }) as string[]) { - if (!file.endsWith(".ts")) continue; - const source = readFileSync(join(srcDir, file), "utf8"); - const calls = source.match(/(? { - const { app, store, begin, complete } = await planeHarness(); - const receipt = await begin("begin-legit"); - expect(receipt.status).toBe("pending"); - const handle = String(receipt.handle); - const navigation = receipt.navigation as { url: string }; - const state = new URL(navigation.url).searchParams.get("state") ?? ""; - expect(jwtPayload(state).handoff).toEqual({ kind: "browser_completion", attemptId: handle }); - - const callback = await completeAs(app, state, "victim"); - expect(callback.statusCode, callback.body).toBe(201); - expect((await store.findAuthAttempt("ghostlight", handle))?.status).toBe("completed"); - - const completed = await complete("complete-legit", handle); - expect(completed.status).toBe("authenticated"); - expect(completed.handle).toBe(handle); - expect(completed.accessToken).toEqual(expect.any(String)); - expect((await store.findAuthAttempt("ghostlight", handle))?.status).toBe("consumed"); - }); - - it("a stranger cannot pre-occupy the app's pending handle so that the victim's own completion collides", async () => { - const { app, store, begin, complete } = await planeHarness(); - const receipt = await begin("begin-victim"); - const handle = String(receipt.handle); - const victimState = new URL((receipt.navigation as { url: string }).url).searchParams.get("state") ?? ""; - - // Attacker names the victim's handle on the public start route: Ghostlight's - // start is refused outright without the app's secret, so no state exists to complete. - const attackerStart = await start(app, { - appSlug: "ghostlight", - mode: "sign_in", - returnTo: legitReturn, - handoff: { kind: "browser_completion", attemptId: handle }, - }); - expect([attackerStart.statusCode, attackerStart.json().error]).toEqual([401, "app_auth_required"]); - expect(attackerStart.json().authorizationUrl).toBeUndefined(); - expect((await store.findAuthAttempt("ghostlight", handle))?.status).toBe("pending"); - - // Victim completes; the handle's single unconsumed slot is still free. - const victimCallback = await completeAs(app, victimState, "victim"); - expect(victimCallback.statusCode, victimCallback.body).toBe(201); - const completed = await complete("complete-victim", handle); - expect(completed.status).toBe("authenticated"); - // ...and the tokens are the victim's, not the attacker's. - const claims = jwtPayload(String(completed.accessToken)); - expect(JSON.stringify(claims)).toContain("victim"); - expect(JSON.stringify(claims)).not.toContain("attacker"); - }); - - it("a backend_callback attemptId (the other handoff kind that carries one) never touches an auth attempt", async () => { - const { app, store } = await harness({ appBackendCallbacks: { ghostlight: ["http://127.0.0.1:1/never"] } }); - const attempt = await store.createAuthAttempt({ - appSlug: "ghostlight", - provider: "discord", - mode: "sign_in", - returnTo: legitReturn, - createdAt: new Date().toISOString(), - expiresAt: new Date(Date.now() + 600_000).toISOString(), - }); - const response = await start(app, { - appSlug: "ghostlight", - mode: "sign_in", - returnTo: legitReturn, - handoff: { kind: "backend_callback", attemptId: attempt.handle, callbackUrl: "http://127.0.0.1:1/never" }, - }, ghostlightApp); - expect(response.statusCode, response.body).toBe(201); - // Delivery to port 1 fails; whatever the callback returns, the attempt - // must be untouched and no completion may be bound to it. - await completeAs(app, stateOf(response.json()), "attacker"); - expect((await store.findAuthAttempt("ghostlight", attempt.handle))?.status).toBe("pending"); - expect(await store.consumeAuthCompletionByAttempt("ghostlight", attempt.handle, new Date().toISOString())).toBeNull(); - }); -}); - -describe("R21.2: the WeakSet brand at every consumer", () => { - it("every function that takes an AppCaller checks isAppCaller before reading appSlug", async () => { - const { readFileSync, readdirSync } = await import("node:fs"); - const { join } = await import("node:path"); - const srcDir = join(process.cwd(), "src"); - const consumers: string[] = []; - for (const file of readdirSync(srcDir, { recursive: true }) as string[]) { - if (!file.endsWith(".ts") || file.endsWith("app-caller.ts")) continue; - const source = readFileSync(join(srcDir, file), "utf8"); - const readsSlug = source.match(/caller\.appSlug/g) ?? []; - const guards = source.match(/isAppCaller\(caller\)/g) ?? []; - if (readsSlug.length) consumers.push(`${file}: reads=${readsSlug.length} guards=${guards.length}`); - // Every `caller.appSlug` read is on a line that also carries the guard. - for (const line of source.split("\n")) { - if (line.includes("caller.appSlug")) expect(line, `${file}: ${line.trim()}`).toContain("isAppCaller(caller)"); - } - } - expect(consumers).toEqual(["app.ts: reads=4 guards=4"]); - }); - - it("a caller minted for app A is refused where app B is expected, over HTTP and by direct call", async () => { - const { app, config } = await harness(); - const ctx = getHeimdallRuntimeContext(app); - const repixelizerCaller = resolveAppCaller(config, "repixelizer", { "x-heimdall-app-secret": "repixelizer-secret" }); - expect(isAppCaller(repixelizerCaller)).toBe(true); - - const startResult = await startOAuthFlow(ctx, "discord", repixelizerCaller, { - appSlug: "ghostlight", - mode: "sign_in", - returnTo: "https://yggdrasil.gamecult.org/ghostlight/", - entitlementPolicy: { kind: "discord_role_access", guildId: "g", allowedRoleIds: ["r"] }, - }); - expect(startResult.statusCode).toBe(401); - expect(startResult.body).toMatchObject({ error: "app_auth_required" }); - - const refreshResult = await refreshAppSession(ctx, "ghostlight", repixelizerCaller, { - refreshToken: "x", - entitlementPolicies: [{ kind: "discord_role_access", guildId: "g", allowedRoleIds: ["r"] }], - }); - expect(refreshResult.statusCode).toBe(401); - - // Over HTTP: repixelizer's real secret on a ghostlight start with policy. - const http = await start( - app, - { - appSlug: "ghostlight", - mode: "sign_in", - returnTo: "https://yggdrasil.gamecult.org/ghostlight/", - entitlementPolicy: { kind: "discord_role_access", guildId: "g", allowedRoleIds: ["r"] }, - }, - { "x-heimdall-app-secret": "repixelizer-secret" }, - ); - expect(http.statusCode).toBe(401); - }); - - it("symbol-copying, prototype-chaining, Proxy-wrapping and structuredClone forgeries are all refused", async () => { - const { config } = await harness(); - const real = resolveAppCaller(config, "repixelizer", { "x-heimdall-app-secret": "repixelizer-secret" }) as AppCaller; - const [brandSymbol] = Object.getOwnPropertySymbols(real); - expect(brandSymbol).toBeDefined(); - - const symbolCopy = { appSlug: "ghostlight", [brandSymbol as symbol]: true }; - // defineProperty, not assign: `real` is frozen, so shadowing its - // non-writable `appSlug` by assignment throws before the forgery exists. - const chained = Object.defineProperty(Object.create(real) as object, "appSlug", { - value: "ghostlight", - enumerable: true, - }); - const proxied = new Proxy(real, { get: (target, key) => (key === "appSlug" ? "ghostlight" : Reflect.get(target, key)) }); - const spread = { ...real, appSlug: "ghostlight" }; - const cloned = structuredClone({ appSlug: real.appSlug }); - for (const forgery of [symbolCopy, chained, proxied, spread, cloned]) { - expect(isAppCaller(forgery)).toBe(false); - } - // Frozen at mint, so the last forgery the WeakSet could not see is gone: - // a legitimately held caller cannot be re-slugged into another app and - // keep its brand. Modules are strict, so the write throws rather than - // silently no-opping. - expect(Object.isFrozen(real)).toBe(true); - expect(() => { - (real as { appSlug: string }).appSlug = "ghostlight"; - }).toThrow(TypeError); - expect(real.appSlug).toBe("repixelizer"); - expect(isAppCaller(real)).toBe(true); - }); -}); - -async function twoCompletionsForOneHandle(store: HeimdallStore, appSlug: AppSlug = "ghostlight") { - const { accountId, sessionId } = await seedAccountAndSession(store, appSlug); - const results = await Promise.allSettled([ - store.createAuthCompletion(completionInput(appSlug, accountId, sessionId, "handle-1")), - store.createAuthCompletion(completionInput(appSlug, accountId, sessionId, "handle-1")), - ]); - return { results, accountId, sessionId }; -} - -function partialUniqueIndexContract(label: string, makeStore: () => Promise) { - describe(`partial unique index contract: ${label}`, () => { - it("two concurrent completions for one handle: exactly one is minted", async () => { - const store = await makeStore(); - const { results } = await twoCompletionsForOneHandle(store); - const fulfilled = results.filter((r) => r.status === "fulfilled"); - const rejected = results.filter((r) => r.status === "rejected"); - expect(fulfilled).toHaveLength(1); - expect(rejected).toHaveLength(1); - const live = await store.consumeAuthCompletionByAttempt("ghostlight", "handle-1", new Date().toISOString()); - expect(live?.attemptId).toBe("handle-1"); - expect(await store.consumeAuthCompletionByAttempt("ghostlight", "handle-1", new Date().toISOString())).toBeNull(); - }); - - it("the predicate: NULL handles never collide, a consumed handle frees its slot, other apps do not collide", async () => { - const store = await makeStore(); - const g = await seedAccountAndSession(store, "ghostlight"); - const r = await seedAccountAndSession(store, "repixelizer"); - await store.createAuthCompletion(completionInput("ghostlight", g.accountId, g.sessionId)); - await store.createAuthCompletion(completionInput("ghostlight", g.accountId, g.sessionId)); - const first = await store.createAuthCompletion(completionInput("ghostlight", g.accountId, g.sessionId, "shared")); - await expect(store.createAuthCompletion(completionInput("repixelizer", r.accountId, r.sessionId, "shared"))).resolves.toBeTruthy(); - await expect(store.createAuthCompletion(completionInput("ghostlight", g.accountId, g.sessionId, "shared"))).rejects.toThrow(); - expect(await store.consumeAuthCompletion("ghostlight", first.code, new Date().toISOString())).toBeTruthy(); - const second = await store.createAuthCompletion(completionInput("ghostlight", g.accountId, g.sessionId, "shared")); - expect(second.code).not.toBe(first.code); - const byAttempt = await store.consumeAuthCompletionByAttempt("ghostlight", "shared", new Date().toISOString()); - expect(byAttempt?.code).toBe(second.code); - }); - - it("an expired-but-unconsumed completion still occupies the slot (both stores agree; neither frees it)", async () => { - const store = await makeStore(); - const g = await seedAccountAndSession(store, "ghostlight"); - const stale = completionInput("ghostlight", g.accountId, g.sessionId, "stale"); - stale.expiresAt = new Date(Date.now() - 1000).toISOString(); - await store.createAuthCompletion(stale); - expect(await store.consumeAuthCompletionByAttempt("ghostlight", "stale", new Date().toISOString())).toBeNull(); - await expect(store.createAuthCompletion(completionInput("ghostlight", g.accountId, g.sessionId, "stale"))).rejects.toThrow(); - }); - }); -} - -partialUniqueIndexContract("InMemoryStore", async () => new InMemoryStore()); -partialUniqueIndexContract("PostgresStore over pg-mem", async () => { - const adapter = newDb().adapters.createPg(); - const store = new PostgresStore(new adapter.Pool()); - await store.ensureSchema(); - return store; -}); - -describe("duplicate-handle error surfacing through the callback route", () => { - it("a replayed state is refused as already used before any exchange, and leaves the real completion intact", async () => { - const { app, store, begin } = await planeHarness(); - const receipt = await begin("begin-replay"); - const handle = String(receipt.handle); - const state = new URL((receipt.navigation as { url: string }).url).searchParams.get("state") ?? ""; - const { cookie } = await launchState(app, state); - const callbackWith = () => - app.inject({ - method: "GET", - url: `/v1/oauth/discord/callback?code=victim&state=${encodeURIComponent(state)}`, - headers: { accept: "application/json", cookie }, - }); - const first = await callbackWith(); - expect(first.statusCode).toBe(201); - // The state's jti was consumed by the first callback, so the second never - // reaches createAuthCompletion, whose unique index used to be the only - // thing refusing a replay (and whose Postgres 23505 text the route had to - // keep out of the answer). - const replay = await callbackWith(); - expect(replay.statusCode, replay.body).toBe(400); - expect(replay.json()).toEqual({ error: "state_already_used" }); - expect((await store.findAuthAttempt("ghostlight", handle))?.status).toBe("completed"); - expect(await store.consumeAuthCompletionByAttempt("ghostlight", handle, new Date().toISOString())).toBeTruthy(); - }); -}); - -describe("R21.3: sync getAppProfile at the seven former resolveAppProfile sites", () => { - it("getAppProfile resolves own keys only, so prototype members are not profiles", () => { - expect(getAppProfile("nope" as AppSlug)).toBeUndefined(); - // Object.hasOwn guards the lookup; a bare `record[key]` index handed these - // back as objects that then serialised as an empty profile. - for (const key of ["constructor", "toString", "__proto__", "hasOwnProperty"]) { - expect(getAppProfile(key as AppSlug), key).toBeUndefined(); - } - }); - - // Was an open hole inherited from main: this is the one route whose params - // schema has no slug enum, and the bare index made `constructor` a 200 `{}` - // because serializeAppProfile(Object) serialises undefined fields. Closed by - // Object.hasOwn in getAppProfile. - it("GET /v1/apps/:appSlug is the one route without the slug enum; a prototype key must still be a 404", async () => { - const { app } = await harness(); - // Null prototype so the "__proto__" key is a key, not a setter. - const statuses: Record = Object.create(null) as Record; - for (const key of ["constructor", "toString", "__proto__", "hasOwnProperty", "valueOf"]) { - const response = await app.inject({ method: "GET", url: `/v1/apps/${key}` }); - statuses[key] = `${response.statusCode} ${response.body.slice(0, 60)}`; - } - process.stdout.write(`\n[soul] GET /v1/apps/: ${JSON.stringify(statuses)}\n`); - expect(statuses).toEqual(Object.fromEntries(Object.keys(statuses).map((key) => [key, expect.stringMatching(/^404 /)]))); - }); - - it("every other appSlug parameter is enum-gated, so an unknown slug is a 400 there and a 404 only on the profile read", async () => { - const { app } = await harness(); - expect((await app.inject({ method: "GET", url: "/v1/apps/nope" })).statusCode).toBe(404); - expect((await start(app, { appSlug: "nope", mode: "sign_in", returnTo: "https://x.example/" })).statusCode).toBe(400); - for (const url of [ - "/v1/apps/nope/auth-completions/redeem", - "/v1/apps/nope/sessions/refresh", - "/v1/apps/nope/patron-support/sync", - "/v1/apps/nope/managed-credentials/resolve", - ]) { - const response = await app.inject({ method: "POST", url, payload: { completionCode: "c", refreshToken: "r", accountId: "a", provider: "discord" } }); - expect(response.statusCode, url).toBe(400); - } - }); - - it("the migration adds attempt_id before the partial index that references it, and drops registered_apps first", () => { - const addColumn = CREATE_SCHEMA_SQL.indexOf("ALTER TABLE auth_completions ADD COLUMN IF NOT EXISTS attempt_id TEXT"); - const dropOldIndex = CREATE_SCHEMA_SQL.indexOf("DROP INDEX IF EXISTS auth_completions_attempt_idx"); - const createIndex = CREATE_SCHEMA_SQL.indexOf("CREATE UNIQUE INDEX IF NOT EXISTS auth_completions_attempt_unconsumed_unique_idx"); - const dropTable = CREATE_SCHEMA_SQL.indexOf("DROP TABLE IF EXISTS registered_apps"); - expect(dropTable).toBeGreaterThanOrEqual(0); - expect(addColumn).toBeGreaterThan(dropTable); - expect(dropOldIndex).toBeGreaterThan(addColumn); - expect(createIndex).toBeGreaterThan(dropOldIndex); - // Statement count, not token count (the comment above the DROP names it too). - expect(CREATE_SCHEMA_SQL.match(/DROP TABLE IF EXISTS registered_apps/g)).toHaveLength(1); - expect(CREATE_SCHEMA_SQL).not.toMatch(/CREATE TABLE[^;]*registered_apps/); - }); - // Re-running ensureSchema on a store built before this branch (table - // present, column absent, old index name) cannot be simulated in pg-mem — - // it rejects CREATE TABLE IF NOT EXISTS on an existing table — so that - // path is proved only by the live block below. -}); - -const livePg = process.env.SOUL_PG_URL; -describe.skipIf(!livePg)("live postgres (SOUL_PG_URL)", () => { - it("real partial index: 23505 names auth_completions_attempt_unconsumed_unique_idx; schema applies twice on a pre-branch store", async () => { - const pool = new Pool({ connectionString: livePg }); - resources.push({ close: () => pool.end() }); - await pool.query(` - DROP SCHEMA public CASCADE; CREATE SCHEMA public; - CREATE TABLE registered_apps (slug TEXT PRIMARY KEY); - CREATE TABLE accounts (id TEXT PRIMARY KEY, created_at TIMESTAMPTZ NOT NULL, last_seen_at TIMESTAMPTZ NOT NULL, display_name TEXT, primary_email TEXT); - CREATE TABLE sessions (id TEXT PRIMARY KEY, account_id TEXT NOT NULL REFERENCES accounts(id) ON DELETE CASCADE, app_slug TEXT NOT NULL, created_at TIMESTAMPTZ NOT NULL, last_seen_at TIMESTAMPTZ NOT NULL, expires_at TIMESTAMPTZ NOT NULL, claims_json JSONB NOT NULL, access_revision INTEGER NOT NULL); - CREATE TABLE auth_completions ( - code TEXT PRIMARY KEY, app_slug TEXT NOT NULL, provider TEXT NOT NULL, mode TEXT NOT NULL, - account_id TEXT NOT NULL REFERENCES accounts(id) ON DELETE CASCADE, - session_id TEXT NOT NULL REFERENCES sessions(id) ON DELETE CASCADE, - return_to TEXT NOT NULL, payload_json JSONB NOT NULL, created_at TIMESTAMPTZ NOT NULL, expires_at TIMESTAMPTZ NOT NULL, consumed_at TIMESTAMPTZ - ); - `); - const store = new PostgresStore(pool); - await store.ensureSchema(); - await store.ensureSchema(); - const tables = await pool.query<{ table_name: string }>("SELECT table_name FROM information_schema.tables WHERE table_schema = 'public' ORDER BY 1"); - expect(tables.rows.map((r) => r.table_name)).not.toContain("registered_apps"); - const indexes = await pool.query<{ indexdef: string }>("SELECT indexdef FROM pg_indexes WHERE tablename = 'auth_completions' ORDER BY 1"); - const partial = indexes.rows.find((r) => r.indexdef.includes("auth_completions_attempt_unconsumed_unique_idx")); - expect(partial?.indexdef).toContain("WHERE ((attempt_id IS NOT NULL) AND (consumed_at IS NULL))"); - - const { results } = await twoCompletionsForOneHandle(store); - const rejected = results.find((r): r is PromiseRejectedResult => r.status === "rejected"); - expect(results.filter((r) => r.status === "fulfilled")).toHaveLength(1); - const error = rejected?.reason as { code?: string; message?: string }; - expect(error.code).toBe("23505"); - expect(error.message).toContain("auth_completions_attempt_unconsumed_unique_idx"); - // What the callback route's catch would echo as `detail`. - process.stdout.write(`\n[soul live pg] 23505 message: ${error.message}\n`); - }, 30_000); -}); diff --git a/tests/caller-identity-attack-soul.test.ts b/tests/caller-identity-attack-soul.test.ts deleted file mode 100644 index 3ac3960..0000000 --- a/tests/caller-identity-attack-soul.test.ts +++ /dev/null @@ -1,362 +0,0 @@ -// Soul attack probes for the caller-identity cut, second pass. -// -// Same convention as caller-identity-soul.test.ts: plain `it` is an invariant -// that currently holds; `it.fails` is a hole the cut does not close (vitest -// passes the case while the body fails; close the hole and promote it). -import { afterEach, describe, expect, it } from "vitest"; -import { buildApp, refreshAppSession } from "../src/app.js"; -import { type AppCaller } from "../src/app-caller.js"; -import { builtInAppProfiles, isAllowedReturnOrigin } from "../src/app-profiles.js"; -import { type HeimdallConfig } from "../src/config.js"; -import { entitlementFacts } from "../src/facts.js"; -import { type OAuthProviderRuntime } from "../src/oauth.js"; -import { InMemoryStore } from "../src/store/index.js"; -import { launchState, stateOf } from "./oauth-flow.js"; - -const resources: Array<{ close(): Promise }> = []; - -afterEach(async () => { - await Promise.all(resources.splice(0).reverse().map((resource) => resource.close())); -}); - -function testConfig(): HeimdallConfig { - return { - serviceName: "heimdall", - host: "127.0.0.1", - port: 4100, - privateCommandHost: "127.0.0.1", - privateCommandPort: 0, - workspaceRoot: "F:/Projects/Heimdall", - dataRoot: "F:/Projects/Heimdall/.heimdall-data", - cultCachePath: "F:/Projects/Heimdall/.heimdall-data/cultcache/test.cc", - publicBaseUrl: "https://heimdall.gamecult.org", - issuer: "https://heimdall.gamecult.org", - daemonId: "yggdrasil-heimdall", - idunnRudpHealth: undefined, - idunnHealthContract: "heimdall.cultnet-rudp-provider-health", - providerHealthIdentityPath: "F:/Projects/Heimdall/.heimdall-data/provider-health-test.cc", - sessionTtlSeconds: 3600, - refreshTtlSeconds: 3600, - stateTtlSeconds: 600, - completionTtlSeconds: 300, - bootstrapSigningPrivateKeyOnMissing: false, - tokenEncryptionKeyBase64: Buffer.alloc(32, 7).toString("base64"), - appSharedSecrets: { repixelizer: "repixelizer-secret", ghostlight: "ghostlight-secret" }, - appRuntimeIds: { ghostlight: ["yggdrasil-ghostlight"] }, - appBackendCallbacks: {}, - storage: { backend: "memory", applySchemaOnStartup: true }, - providers: { - discord: { clientId: "discord-client", clientSecret: "discord-secret" }, - patreon: {}, - github: {}, - twitch: {}, - youtube: {}, - spotify: {}, - joystick: {}, - google: {}, - }, - }; -} - -// The provider "code" doubles as the identity so one runtime can play both -// victim and attacker: code `victim` resolves to discord user `victim`. -function identityByCodeRuntime(): OAuthProviderRuntime { - return { - async exchangeAuthorizationCode({ code }) { - return { accessToken: code, tokenType: "Bearer", scope: ["identify"], raw: {} }; - }, - async resolveIdentity({ accessToken }) { - return { provider: "discord", providerUserId: accessToken, displayName: accessToken, profile: {} }; - }, - async evaluateEntitlements() { - return { facts: [entitlementFacts.appAccess], snapshots: [] }; - }, - }; -} - -async function harness() { - const store = new InMemoryStore(); - const app = await buildApp({ config: testConfig(), store, oauthRuntimes: { discord: identityByCodeRuntime() } }); - resources.push(app); - return { app, store }; -} - -type App = Awaited>["app"]; - -async function start(app: App, payload: Record, headers: Record = {}) { - return app.inject({ method: "POST", url: "/v1/oauth/discord/start", payload, headers }); -} - -async function completeAs(app: App, stateToken: string, who: string) { - const { cookie } = await launchState(app, stateToken); - return app.inject({ - method: "GET", - url: `/v1/oauth/discord/callback?code=${who}&state=${encodeURIComponent(stateToken)}`, - headers: { accept: "application/json", cookie }, - }); -} - -async function redeem(app: App, appSlug: string, completionCode: string) { - return app.inject({ method: "POST", url: `/v1/apps/${appSlug}/auth-completions/redeem`, payload: { completionCode } }); -} - -const uuidV4 = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/; - -describe("takeover chain: caller-chosen attemptId is never the redemption code", () => { - it("attacker fixes attemptId, victim completes, attemptId does not redeem; the minted code is a fresh uuid v4", async () => { - const { app } = await harness(); - const started = await start(app, { - appSlug: "repixelizer", - mode: "sign_in", - returnTo: "https://repixelizer.gamecult.org/app/", - handoff: { kind: "browser_completion", attemptId: "attacker-fixed" }, - }); - expect(started.statusCode).toBe(201); - - const callback = await completeAs(app, stateOf(started.json()), "victim"); - expect(callback.statusCode).toBe(201); - const minted = callback.json().completion.code as string; - expect(minted).not.toBe("attacker-fixed"); - expect(minted).toMatch(uuidV4); - - const byAttempt = await redeem(app, "repixelizer", "attacker-fixed"); - expect(byAttempt.statusCode).toBe(410); - expect(byAttempt.json()).toEqual({ error: "invalid_or_expired_completion_code" }); - }); - - it("omitting handoff still mints a uuid v4 code; the attempt handle is absent from the completion", async () => { - const { app, store } = await harness(); - const started = await start(app, { appSlug: "repixelizer", mode: "sign_in", returnTo: "https://repixelizer.gamecult.org/app/" }); - expect(started.statusCode).toBe(201); - const callback = await completeAs(app, stateOf(started.json()), "victim"); - expect(callback.statusCode).toBe(201); - const code = callback.json().completion.code as string; - expect(code).toMatch(uuidV4); - const stored = (store as unknown as { authCompletions: Map }).authCompletions.get(code); - expect(stored?.attemptId).toBeUndefined(); - }); - - it("handoff.kind backend_callback with an attemptId is refused unless the callbackUrl is configured", async () => { - const { app } = await harness(); - const started = await start(app, { - appSlug: "repixelizer", - mode: "sign_in", - returnTo: "https://repixelizer.gamecult.org/app/", - handoff: { kind: "backend_callback", attemptId: "attacker-fixed", callbackUrl: "https://attacker.example/cb" }, - }); - expect(started.statusCode).toBe(400); - expect(started.json().error).toBe("untrusted_backend_callback"); - }); - - it("an unknown handoff.kind is rejected by the schema", async () => { - const { app } = await harness(); - const started = await start(app, { - appSlug: "repixelizer", - mode: "sign_in", - returnTo: "https://repixelizer.gamecult.org/app/", - handoff: { kind: "evil", attemptId: "attacker-fixed" }, - }); - expect(started.statusCode).toBe(400); - }); - - it("attemptId set to a real victim completion code does not let the attacker's flow touch the victim's completion", async () => { - const { app } = await harness(); - const victimStart = await start(app, { appSlug: "repixelizer", mode: "sign_in", returnTo: "https://repixelizer.gamecult.org/app/" }); - const victimCallback = await completeAs(app, stateOf(victimStart.json()), "victim"); - const victimCode = victimCallback.json().completion.code as string; - - const attackerStart = await start(app, { - appSlug: "repixelizer", - mode: "sign_in", - returnTo: "https://repixelizer.gamecult.org/app/", - handoff: { kind: "browser_completion", attemptId: victimCode }, - }); - const attackerCallback = await completeAs(app, stateOf(attackerStart.json()), "attacker"); - expect(attackerCallback.statusCode).toBe(201); - expect(attackerCallback.json().completion.code).not.toBe(victimCode); - - // The victim's code still redeems the victim, once. - const first = await redeem(app, "repixelizer", victimCode); - expect(first.statusCode).toBe(201); - expect(first.json().account.displayName).toBe("victim"); - }); - - it("the redeem route is unauthenticated, so the code is the whole secret: 122 bits of CSPRNG, distinct across mints", async () => { - const store = new InMemoryStore(); - const codes = new Set(); - for (let i = 0; i < 200; i += 1) { - const completion = await store.createAuthCompletion({ - appSlug: "repixelizer", - provider: "discord", - mode: "sign_in", - accountId: "a", - sessionId: "s", - returnTo: "https://repixelizer.gamecult.org/app/", - createdAt: "2026-01-01T00:00:00.000Z", - expiresAt: "2999-01-01T00:00:00.000Z", - payloadJson: {}, - }); - expect(completion.code).toMatch(uuidV4); - codes.add(completion.code); - } - expect(codes.size).toBe(200); - }); -}); - -describe("consumeAuthCompletion: single-use, scoped, expiring", () => { - it("a code redeems exactly once under concurrent redemption, and never for another app", async () => { - const { app } = await harness(); - const started = await start(app, { appSlug: "repixelizer", mode: "sign_in", returnTo: "https://repixelizer.gamecult.org/app/" }); - const callback = await completeAs(app, stateOf(started.json()), "victim"); - const code = callback.json().completion.code as string; - - const crossApp = await redeem(app, "bifrost", code); - expect(crossApp.statusCode).toBe(410); - - const results = await Promise.all([redeem(app, "repixelizer", code), redeem(app, "repixelizer", code), redeem(app, "repixelizer", code)]); - expect(results.map((r) => r.statusCode).sort()).toEqual([201, 410, 410]); - }); - - it("an expired completion is not consumable, by code or by attempt", async () => { - const store = new InMemoryStore(); - const completion = await store.createAuthCompletion({ - attemptId: "h1", - appSlug: "repixelizer", - provider: "discord", - mode: "sign_in", - accountId: "a", - sessionId: "s", - returnTo: "https://repixelizer.gamecult.org/app/", - createdAt: "2026-01-01T00:00:00.000Z", - expiresAt: "2026-01-01T00:05:00.000Z", - payloadJson: {}, - }); - expect(await store.consumeAuthCompletion("repixelizer", completion.code, "2026-01-01T00:05:00.000Z")).toBeNull(); - expect(await store.consumeAuthCompletionByAttempt("repixelizer", "h1", "2026-01-01T00:05:00.000Z")).toBeNull(); - expect(await store.consumeAuthCompletionByAttempt("bifrost", "h1", "2026-01-01T00:04:00.000Z")).toBeNull(); - expect(await store.consumeAuthCompletionByAttempt("repixelizer", "h1", "2026-01-01T00:04:00.000Z")).not.toBeNull(); - expect(await store.consumeAuthCompletionByAttempt("repixelizer", "h1", "2026-01-01T00:04:00.000Z")).toBeNull(); - }); -}); - -describe("attempt-handle binding: the public start route may attach a completion to any attempt", () => { - // Closed (R21.1). The private plane creates attempt H for its app and later - // redeems by handle (consumeAuthCompletionByAttempt). handoff.attemptId is - // no longer read from the request body at all (normalizeOAuthHandoff always - // returns a bare `{ kind: "browser_completion" }` for a public caller); the - // only path by which an attempt handle reaches the signed state token is - // `startOAuthFlow`'s `trustedBrowserAttemptId` option, which only - // `beginAuth` (private-command-plane.ts) can set, from the handle it just - // minted server-side. A value that never crosses the public boundary cannot - // be chosen by a stranger, so a public flow carrying H as body JSON now has - // no effect on H at all. - it("a public flow carrying the app's attempt handle must not complete that attempt", async () => { - const { app, store } = await harness(); - const attempt = await store.createAuthAttempt({ - appSlug: "ghostlight", - provider: "discord", - mode: "sign_in", - returnTo: "https://yggdrasil.gamecult.org/ghostlight/", - createdAt: new Date().toISOString(), - expiresAt: new Date(Date.now() + 600_000).toISOString(), - }); - - // Ghostlight's start is the app's own: without its secret there is no state to complete with. - const attackerStart = await start(app, { - appSlug: "ghostlight", - mode: "sign_in", - returnTo: "https://yggdrasil.gamecult.org/ghostlight/", - handoff: { kind: "browser_completion", attemptId: attempt.handle }, - }); - expect([attackerStart.statusCode, attackerStart.json().error]).toEqual([401, "app_auth_required"]); - - const after = await store.findAuthAttempt("ghostlight", attempt.handle); - expect(after?.status).toBe("pending"); - const bound = await store.consumeAuthCompletionByAttempt("ghostlight", attempt.handle, new Date().toISOString()); - expect(bound).toBeNull(); - }); -}); - -describe("isAllowedReturnOrigin: origin comparison, not string matching", () => { - const profile = builtInAppProfiles.repixelizer; - // Narrow rather than cast: the lookup is Partial-typed, and a missing - // built-in should fail this suite loudly instead of being asserted away. - if (!profile) { - throw new Error("built-in repixelizer profile is missing"); - } - const rejected = [ - "https://repixelizer.gamecult.org.evil.com/", - "https://evil.com/?x=https://repixelizer.gamecult.org", - "https://repixelizer.gamecult.org@evil.com/", - "https://evil.com#https://repixelizer.gamecult.org", - "//repixelizer.gamecult.org/app/", - "http://repixelizer.gamecult.org/app/", - "https://repixelizer.gamecult.org:8443/app/", - "https://repixelizer.gamecult.org./app/", - "https://xn--repixelizer-gamecult.org/", - "javascript:alert(1)", - "data:text/html,hi", - "not a url", - "", - "https://repixelizer.gamecult.org.", - "https://repixelizer.gamecult.orgx/", - "https://sub.repixelizer.gamecult.org/", - ]; - it.each(rejected)("rejects %s", (returnTo) => { - expect(isAllowedReturnOrigin(profile, returnTo)).toBe(false); - }); - - // Accepted variants are all the same origin after WHATWG normalisation; - // they are listed so a future "fix" that switches to string comparison - // shows up as a behaviour change here rather than silently in production. - const acceptedSameOrigin = [ - "https://repixelizer.gamecult.org", - "https://repixelizer.gamecult.org/app/", - "https://REPIXELIZER.GameCult.org/app/", - "https://repixelizer.gamecult.org:443/app/", - "https:/\\repixelizer.gamecult.org/app/", - "https://user:pw@repixelizer.gamecult.org/app/", - "https://repixelizer.gamecult.org/app/?returnTo=https://evil.com", - ]; - it.each(acceptedSameOrigin)("accepts %s (same origin after URL parsing)", (returnTo) => { - expect(new URL(returnTo).origin).toBe("https://repixelizer.gamecult.org"); - expect(isAllowedReturnOrigin(profile, returnTo)).toBe(true); - }); - - it("an empty allowlist denies everything rather than passing vacuously", () => { - expect(isAllowedReturnOrigin({ ...profile, allowedReturnOrigins: [] }, "https://repixelizer.gamecult.org/")).toBe(false); - }); - - // The registered-app path this test covered (seedRegisteredApp, - // resolveAppProfile's non-built-in branch) was deleted in R21.3: every HTTP - // route already enumerates the four built-in slugs in its own JSON schema, - // so a registered row could never be reached over HTTP in the first place. - // An unknown slug is now refused by that schema directly. - it("an unknown appSlug cannot start a flow through HTTP at all (slug enum)", async () => { - const { app } = await harness(); - const started = await start(app, { appSlug: "newapp", mode: "sign_in", returnTo: "https://anything.example/" }); - expect(started.statusCode).toBe(400); - }); -}); - -describe("AppCaller brand: enforced by a module-private WeakSet (R21.2)", () => { - // Closed. brandCaller (app-caller.ts) registers every AppCaller it mints in - // a WeakSet that never leaves the module; isAppCaller is the only way a - // consumer may trust one, and startOAuthFlow / refreshAppSession now call - // it instead of trusting the AppCaller | null type alone. A forged literal - // — even one carrying the callerBrand symbol key by hand — was never added - // to the set and is rejected regardless of shape or cast. - it("a forged caller literal is refused at runtime", async () => { - const { app } = await harness(); - const context = (app as unknown as { heimdallContext: Parameters[0] }).heimdallContext; - const forged = { appSlug: "repixelizer" } as unknown as AppCaller; - const result = await refreshAppSession(context, "repixelizer", forged, { - refreshToken: "not-a-token", - entitlementPolicies: [{ kind: "discord_role_access", guildId: "g", allowedRoleIds: ["r"] }], - } as never); - // With a forged caller the request gets past the caller gate and fails - // later on the bogus refresh token (401 invalid_refresh_token / similar); - // a runtime brand check would return app_auth_required here. - expect(result.body).toMatchObject({ error: "app_auth_required" }); - }); -}); diff --git a/tests/caller-identity-soul.test.ts b/tests/caller-identity-soul.test.ts deleted file mode 100644 index d66f652..0000000 --- a/tests/caller-identity-soul.test.ts +++ /dev/null @@ -1,295 +0,0 @@ -// Soul falsification probes for the caller-identity cut (epiphany/heimdall-caller-identity). -// -// Two kinds of test live here: -// - plain `it(...)`: an invariant the cut claims and that currently holds. -// - `it.fails(...)`: an invariant the cut does NOT yet enforce. vitest passes -// the case while the body fails; when someone closes the hole the case -// flips to a real failure and must be promoted to a plain `it`. -import { readFileSync, readdirSync } from "node:fs"; -import { join } from "node:path"; -import { encode } from "@msgpack/msgpack"; -import { invokeCultNetOperation } from "cultnet-ts"; -import { afterEach, describe, expect, it } from "vitest"; -import { buildApp, refreshAppSession, startOAuthFlow } from "../src/app.js"; -import { callerFromOpenedEnvelope, secretMatches } from "../src/app-caller.js"; -import { type HeimdallConfig } from "../src/config.js"; -import { entitlementFacts } from "../src/facts.js"; -import { type OAuthProviderRuntime } from "../src/oauth.js"; -import { startHeimdallPrivateCommandPlane } from "../src/private-command-plane.js"; -import { sealPrivateEnvelope, type HeimdallPrivateEnvelope } from "../src/private-command-security.js"; -import { InMemoryStore } from "../src/store/index.js"; -import { launchFlow } from "./oauth-flow.js"; - -const ghostlightSecret = "ghostlight-private-command-secret"; -const resources: Array<{ close(): Promise }> = []; - -afterEach(async () => { - await Promise.all(resources.splice(0).reverse().map((resource) => resource.close())); -}); - -function testConfig(): HeimdallConfig { - return { - serviceName: "heimdall", - host: "127.0.0.1", - port: 4100, - privateCommandHost: "127.0.0.1", - privateCommandPort: 0, - workspaceRoot: "F:/Projects/Heimdall", - dataRoot: "F:/Projects/Heimdall/.heimdall-data", - cultCachePath: "F:/Projects/Heimdall/.heimdall-data/cultcache/test.cc", - publicBaseUrl: "https://heimdall.gamecult.org", - issuer: "https://heimdall.gamecult.org", - daemonId: "yggdrasil-heimdall", - idunnRudpHealth: undefined, - idunnHealthContract: "heimdall.cultnet-rudp-provider-health", - providerHealthIdentityPath: "F:/Projects/Heimdall/.heimdall-data/provider-health-test.cc", - sessionTtlSeconds: 3600, - refreshTtlSeconds: 3600, - stateTtlSeconds: 600, - completionTtlSeconds: 300, - bootstrapSigningPrivateKeyOnMissing: false, - tokenEncryptionKeyBase64: Buffer.alloc(32, 7).toString("base64"), - appSharedSecrets: { repixelizer: "repixelizer-secret", ghostlight: ghostlightSecret }, - appRuntimeIds: { ghostlight: ["yggdrasil-ghostlight"] }, - appBackendCallbacks: {}, - storage: { backend: "memory", applySchemaOnStartup: true }, - providers: { - discord: { clientId: "discord-client", clientSecret: "discord-secret" }, - patreon: {}, - github: {}, - twitch: {}, - youtube: {}, - spotify: {}, - joystick: {}, - google: {}, - }, - }; -} - -function mockDiscordRuntime(): OAuthProviderRuntime { - return { - async exchangeAuthorizationCode() { - return { accessToken: "provider-access", tokenType: "Bearer", scope: ["identify"], raw: {} }; - }, - async resolveIdentity() { - return { provider: "discord", providerUserId: "discord-victim", displayName: "Victim", profile: {} }; - }, - async evaluateEntitlements() { - return { facts: [entitlementFacts.appAccess], snapshots: [] }; - }, - }; -} - -describe("caller identity: unauthenticated mint paths", () => { - // Item 1 (closed). The completion code used to be chosen by whoever started - // the flow (handoff.attemptId became the completion code verbatim, - // src/app.ts createAuthCompletion `code: handoff.attemptId`), and - // auth-completions/redeem takes no app secret. An unauthenticated party - // could therefore fix the code, get a victim to finish provider login on - // the authorization URL, and redeem the victim's signed access + refresh - // tokens. The store now always mints the code itself; attemptId is kept - // only as a separate correlation field the browser may carry. - it("a client-chosen attemptId must not be redeemable for signed tokens without app auth", async () => { - const app = await buildApp({ config: testConfig(), oauthRuntimes: { discord: mockDiscordRuntime() } }); - resources.push(app); - - const start = await app.inject({ - method: "POST", - url: "/v1/oauth/discord/start", - payload: { - appSlug: "repixelizer", - mode: "sign_in", - returnTo: "https://repixelizer.gamecult.org/app/", - handoff: { kind: "browser_completion", attemptId: "attacker-fixed-code" }, - }, - // no x-heimdall-app-secret - }); - expect(start.statusCode).toBe(201); - - const flow = await launchFlow(app, start.json()); - const callback = await app.inject({ - method: "GET", - url: `/v1/oauth/discord/callback?code=victim-code&state=${encodeURIComponent(flow.state)}`, - headers: { accept: "text/html", cookie: flow.cookie }, - }); - expect(callback.statusCode).toBe(200); - - const redeem = await app.inject({ - method: "POST", - url: "/v1/apps/repixelizer/auth-completions/redeem", - payload: { completionCode: "attacker-fixed-code" }, - // still no x-heimdall-app-secret - }); - - // The invariant the cut claims: the caller-chosen code is never minted, - // so it can never be redeemed. - expect(redeem.statusCode).not.toBe(201); - expect(redeem.json().accessToken).toBeUndefined(); - }); - - // Item 2 (closed). returnTo used to be validated only as `format: uri`. The - // success page postMessages the completion payload to - // new URL(returnTo).origin and links to returnTo with the code in the - // fragment (src/browser-handoff.ts), so an unlisted origin was an - // exfiltration primitive. startOAuthFlow now refuses any returnTo whose - // origin is not in the app profile's allowedReturnOrigins. - it("an unauthenticated start must not accept an arbitrary returnTo origin", async () => { - const app = await buildApp({ config: testConfig(), oauthRuntimes: { discord: mockDiscordRuntime() } }); - resources.push(app); - - const start = await app.inject({ - method: "POST", - url: "/v1/oauth/discord/start", - payload: { appSlug: "repixelizer", mode: "sign_in", returnTo: "https://attacker.example/collect" }, - }); - - expect(start.statusCode).not.toBe(201); - }); - - it("refuses to mint on refresh when the caller supplies policy without app auth", async () => { - const app = await buildApp({ config: testConfig(), oauthRuntimes: { discord: mockDiscordRuntime() } }); - resources.push(app); - const context = (app as unknown as { heimdallContext: Parameters[0] }).heimdallContext; - const policy = { kind: "discord_role_access", guildId: "g", allowedRoleIds: ["r"] }; - - const nullCaller = await refreshAppSession(context, "repixelizer", null, { - refreshToken: "irrelevant", - entitlementPolicy: policy, - } as Parameters[3]); - expect(nullCaller).toEqual({ statusCode: 401, body: { error: "app_auth_required" } }); - - const wrongApp = await refreshAppSession(context, "repixelizer", callerFromOpenedEnvelope("ghostlight"), { - refreshToken: "irrelevant", - entitlementPolicy: policy, - } as Parameters[3]); - expect(wrongApp).toEqual({ statusCode: 401, body: { error: "app_auth_required" } }); - - const nullStart = await startOAuthFlow(context, "discord", null, { - appSlug: "repixelizer", - mode: "sign_in", - returnTo: "https://repixelizer.gamecult.org/app/", - entitlementPolicy: policy, - } as Parameters[3]); - expect(nullStart).toEqual({ statusCode: 401, body: { error: "app_auth_required" } }); - }); -}); - -describe("caller identity: single authority", () => { - // Item 2. Source tripwire: the header may be read in exactly one module, - // and the per-app secret table may be read only by the two envelope - // openers (HTTP header comparator, private-plane HMAC/AES-GCM opener). - const srcRoot = join(__dirname, "..", "src"); - const sources = readdirSync(srcRoot) - .filter((name) => name.endsWith(".ts")) - .map((name) => [name, readFileSync(join(srcRoot, name), "utf8")] as const); - - it("x-heimdall-app-secret is read only in app-caller.ts", () => { - const readers = sources - .filter(([, text]) => /headers\[\s*["']x-heimdall-app-secret["']\s*\]/.test(text)) - .map(([name]) => name); - expect(readers).toEqual(["app-caller.ts"]); - }); - - it("appSharedSecrets is read only by the HTTP comparator and the private-plane envelope opener", () => { - const readers = sources - .filter(([, text]) => /appSharedSecrets\s*[\[.]/.test(text)) - .map(([name]) => name) - .sort(); - expect(readers).toEqual(["app-caller.ts", "private-command-plane.ts"]); - }); - - it("no source file compares a shared secret with ===", () => { - const offenders = sources - .filter(([, text]) => /[sS]ecret\w*\s*===|===\s*\w*[sS]ecret/.test(text)) - .map(([name]) => name); - expect(offenders).toEqual([]); - }); - - it("AppCaller literals are constructed nowhere; AppCaller is a branded type", () => { - // Item 3 (closed). `{ appSlug }` used to satisfy AppCaller structurally, - // so the private plane (after openPrivateEnvelope + sourceRuntimeId) - // constructed the literal directly — nothing but grep discipline stopped - // any other importer from doing the same. AppCaller is now branded with - // an unexported symbol, and the private plane gets its caller from - // app-caller.ts's callerFromOpenedEnvelope, the same way the HTTP path - // gets its caller from resolveAppCaller. No file may construct the - // literal at all anymore. - const forgers = sources - .filter(([name, text]) => name !== "app-caller.ts" && /(startOAuthFlow|refreshAppSession)\([^;]*\{\s*appSlug\s*\}/s.test(text)) - .map(([name]) => name); - expect(forgers).toEqual([]); - }); -}); - -describe("caller identity: timing-safe comparator", () => { - // Item 4. - it("secretMatches rejects mismatches of any length and both empty sides", () => { - expect(secretMatches("abc", "abd")).toBe(false); - expect(secretMatches("abc", "abcd")).toBe(false); - expect(secretMatches("abc", "")).toBe(false); - expect(secretMatches(undefined, "abc")).toBe(false); - expect(secretMatches("abc", undefined)).toBe(false); - expect(secretMatches("", "")).toBe(false); - expect(secretMatches("abc", "abc")).toBe(true); - }); - - it("app-caller.ts is the only HTTP-side importer of timingSafeEqual", () => { - const srcRoot = join(__dirname, "..", "src"); - const importers = readdirSync(srcRoot) - .filter((name) => name.endsWith(".ts")) - .filter((name) => /timingSafeEqual/.test(readFileSync(join(srcRoot, name), "utf8"))) - .sort(); - expect(importers).toEqual(["app-caller.ts", "private-command-security.ts"]); - }); -}); - -describe("caller identity: private plane envelope authority", () => { - // Item 3. A correctly sealed envelope from the wrong sourceRuntimeId must - // be refused before beginAuth constructs an AppCaller: no auth attempt may - // be created. - it("refuses a valid envelope from an unconfigured runtime before any attempt is created", async () => { - const config = testConfig(); - const store = new InMemoryStore(); - const app = await buildApp({ config, store, oauthRuntimes: { discord: mockDiscordRuntime() } }); - resources.push(app); - const plane = await startHeimdallPrivateCommandPlane(app, config); - resources.push(plane); - - const envelope = sealPrivateEnvelope({ - appSlug: "ghostlight", - operation: "heimdall.auth.begin", - contentSchema: "heimdall.auth_begin_command.v1", - idempotencyKey: "soul-begin-1", - secret: ghostlightSecret, - payload: { - provider: "discord", - mode: "sign_in", - returnTo: "https://yggdrasil.gamecult.org/ghostlight/", - entitlementPolicy: { kind: "discord_role_access", guildId: "g", allowedRoleIds: ["r"] }, - }, - }); - - const response = await invokeCultNetOperation( - plane.endpoint, - request("heimdall.auth.begin", "soul-wrong-runtime", envelope, "not-ghostlight"), - { runtimeId: "not-ghostlight" } - ); - expect(response.status).toBe("denied"); - - const internals = store as unknown as { authAttempts: Map }; - expect(internals.authAttempts.size).toBe(0); - }, 20_000); -}); - -function request(operation: string, messageId: string, envelope: HeimdallPrivateEnvelope, sourceRuntimeId: string) { - return { - schemaVersion: "cultnet.operation_request.v0" as const, - messageId, - serviceId: "heimdall.private.commands", - operation, - payloadSchema: "heimdall.private_command_envelope.v1", - payloadEncoding: "messagepack-base64" as const, - payload: Buffer.from(encode(envelope)).toString("base64"), - sourceRuntimeId, - }; -} diff --git a/tests/caller-identity.test.ts b/tests/caller-identity.test.ts new file mode 100644 index 0000000..12e24f8 --- /dev/null +++ b/tests/caller-identity.test.ts @@ -0,0 +1,266 @@ +import { encode, decode } from "@msgpack/msgpack"; +import { invokeCultNetOperation } from "cultnet-ts"; +import { afterEach, describe, expect, it } from "vitest"; +import { buildApp, getHeimdallRuntimeContext, refreshAppSession, startOAuthFlow } from "../src/app.js"; +import { callerFromOpenedEnvelope, resolveAppCaller, secretMatches } from "../src/app-caller.js"; +import { type HeimdallConfig } from "../src/config.js"; +import { entitlementFacts } from "../src/facts.js"; +import { type OAuthProviderRuntime } from "../src/oauth.js"; +import { startHeimdallPrivateCommandPlane } from "../src/private-command-plane.js"; +import { openPrivateEnvelope, sealPrivateEnvelope, type HeimdallPrivateEnvelope } from "../src/private-command-security.js"; +import { InMemoryStore } from "../src/store/index.js"; +import { createTestConfig, launchFlow, launchState } from "./oauth-flow.js"; + +const ghostlightSecret = "ghostlight-private-command-secret"; +const resources: Array<{ close(): Promise }> = []; + +afterEach(async () => { + await Promise.all(resources.splice(0).reverse().map((resource) => resource.close())); +}); + +function callerTestConfig(): HeimdallConfig { + const base = createTestConfig(); + return { + ...base, + privateCommandHost: "127.0.0.1", + privateCommandPort: 0, + appSharedSecrets: { + ...base.appSharedSecrets, + ghostlight: ghostlightSecret, + }, + appRuntimeIds: { + ghostlight: ["yggdrasil-ghostlight"], + }, + }; +} + +function identityByCodeRuntime(): OAuthProviderRuntime { + return { + async exchangeAuthorizationCode({ code }) { + return { accessToken: code, tokenType: "Bearer", scope: ["identify"], raw: {} }; + }, + async resolveIdentity({ accessToken }) { + return { provider: "discord", providerUserId: accessToken, displayName: accessToken, profile: {} }; + }, + async evaluateEntitlements() { + return { facts: [entitlementFacts.appAccess], snapshots: [] }; + }, + }; +} + +async function createHarness() { + const config = callerTestConfig(); + const store = new InMemoryStore(); + const app = await buildApp({ config, store, oauthRuntimes: { discord: identityByCodeRuntime() } }); + resources.push(app); + return { app, store, config }; +} + +function jwtPayload(token: string): Record { + const [, body] = token.split("."); + return JSON.parse(Buffer.from(body ?? "", "base64url").toString("utf8")) as Record; +} + +describe("caller identity and secret comparison", () => { + it("secretMatches rejects mismatches of any length and empty/missing inputs", () => { + expect(secretMatches("abc", "abd")).toBe(false); + expect(secretMatches("abc", "abcd")).toBe(false); + expect(secretMatches("abc", "")).toBe(false); + expect(secretMatches(undefined, "abc")).toBe(false); + expect(secretMatches("abc", undefined)).toBe(false); + expect(secretMatches("", "")).toBe(false); + expect(secretMatches("abc", "abc")).toBe(true); + }); + + it("refuses missing or wrong secrets on startRequiresAppCaller and policy routes", async () => { + const { app, config } = await createHarness(); + const ctx = getHeimdallRuntimeContext(app); + + for (const headers of [undefined, {}, { "x-heimdall-app-secret": "wrong-secret" }, { "x-heimdall-app-secret": "repixelizer-secret" }]) { + const response = await app.inject({ + method: "POST", + url: "/v1/oauth/discord/start", + ...(headers ? { headers } : {}), + payload: { + appSlug: "ghostlight", + mode: "sign_in", + returnTo: "https://yggdrasil.gamecult.org/ghostlight/", + }, + }); + expect([response.statusCode, response.json().error]).toEqual([401, "app_auth_required"]); + } + + const repixelizerCaller = resolveAppCaller(config, "repixelizer", { "x-heimdall-app-secret": "repixelizer-secret" }); + expect(repixelizerCaller?.appSlug).toBe("repixelizer"); + + const policy = { kind: "discord_role_access" as const, guildId: "g", allowedRoleIds: ["r"] }; + expect(await startOAuthFlow(ctx, "discord", null, { + appSlug: "repixelizer", + mode: "sign_in", + returnTo: "https://repixelizer.gamecult.org/app/", + entitlementPolicy: policy, + })).toEqual({ statusCode: 401, body: { error: "app_auth_required" } }); + + expect(await refreshAppSession(ctx, "repixelizer", callerFromOpenedEnvelope("ghostlight"), { + refreshToken: "irrelevant", + entitlementPolicies: [policy], + })).toEqual({ statusCode: 401, body: { error: "app_auth_required" } }); + }); + + it("drops caller-supplied attemptId on HTTP starts and rejects untrusted returnTo origins", async () => { + const { app } = await createHarness(); + + const untrustedReturn = await app.inject({ + method: "POST", + url: "/v1/oauth/discord/start", + payload: { appSlug: "repixelizer", mode: "sign_in", returnTo: "https://attacker.example/collect" }, + }); + expect(untrustedReturn.statusCode).toBe(400); + + const start = await app.inject({ + method: "POST", + url: "/v1/oauth/discord/start", + payload: { + appSlug: "repixelizer", + mode: "sign_in", + returnTo: "https://repixelizer.gamecult.org/app/", + handoff: { kind: "browser_completion", attemptId: "attacker-fixed-code" }, + }, + }); + expect(start.statusCode).toBe(201); + expect(start.json().handoff).toEqual({ kind: "browser_completion" }); + + const flow = await launchFlow(app, start.json()); + const callback = await app.inject({ + method: "GET", + url: `/v1/oauth/discord/callback?code=victim&state=${encodeURIComponent(flow.state)}`, + headers: { accept: "application/json", cookie: flow.cookie }, + }); + expect(callback.statusCode).toBe(201); + const mintedCode = callback.json().completion.code as string; + expect(mintedCode).not.toBe("attacker-fixed-code"); + + const byAttempt = await app.inject({ + method: "POST", + url: "/v1/apps/repixelizer/auth-completions/redeem", + payload: { completionCode: "attacker-fixed-code" }, + }); + expect(byAttempt.statusCode).toBe(410); + + const crossApp = await app.inject({ + method: "POST", + url: "/v1/apps/bifrost/auth-completions/redeem", + payload: { completionCode: mintedCode }, + }); + expect(crossApp.statusCode).toBe(410); + }); + + it("returns 404 for unknown and prototype keys on GET /v1/apps/:appSlug", async () => { + const { app } = await createHarness(); + for (const key of ["nope", "constructor", "toString", "__proto__", "hasOwnProperty"]) { + const response = await app.inject({ method: "GET", url: `/v1/apps/${key}` }); + expect(response.statusCode, key).toBe(404); + } + }); +}); + +describe("private command plane caller authentication", () => { + function envelopeRequest(operation: string, messageId: string, envelope: HeimdallPrivateEnvelope, sourceRuntimeId: string) { + return { + schemaVersion: "cultnet.operation_request.v0" as const, + messageId, + serviceId: "heimdall.private.commands", + operation, + payloadSchema: "heimdall.private_command_envelope.v1", + payloadEncoding: "messagepack-base64" as const, + payload: Buffer.from(encode(envelope)).toString("base64"), + sourceRuntimeId, + }; + } + + it("refuses an unconfigured sourceRuntimeId before creating an auth attempt", async () => { + const { app, store, config } = await createHarness(); + const plane = await startHeimdallPrivateCommandPlane(app, config); + resources.push(plane); + + const envelope = sealPrivateEnvelope({ + appSlug: "ghostlight", + operation: "heimdall.auth.begin", + contentSchema: "heimdall.auth_begin_command.v1", + idempotencyKey: "wrong-runtime-begin", + secret: ghostlightSecret, + payload: { + provider: "discord", + mode: "sign_in", + returnTo: "https://yggdrasil.gamecult.org/ghostlight/", + }, + }); + + const response = await invokeCultNetOperation( + plane.endpoint, + envelopeRequest("heimdall.auth.begin", "msg-wrong-runtime", envelope, "not-ghostlight"), + { runtimeId: "not-ghostlight" } + ); + expect(response.status).toBe("denied"); + expect((store as unknown as { authAttempts: Map }).authAttempts.size).toBe(0); + }, 20_000); + + it("binds server-minted attempt handle on begin, correlates callback, and redeems on complete", async () => { + const { app, store, config } = await createHarness(); + const plane = await startHeimdallPrivateCommandPlane(app, config); + resources.push(plane); + + const beginEnvelope = sealPrivateEnvelope({ + appSlug: "ghostlight", + operation: "heimdall.auth.begin", + contentSchema: "heimdall.auth_begin_command.v1", + idempotencyKey: "legit-begin", + secret: ghostlightSecret, + payload: { + provider: "discord", + mode: "sign_in", + returnTo: "https://yggdrasil.gamecult.org/ghostlight/", + }, + }); + const beginResponse = await invokeCultNetOperation( + plane.endpoint, + envelopeRequest("heimdall.auth.begin", "msg-begin", beginEnvelope, "yggdrasil-ghostlight"), + { runtimeId: "yggdrasil-ghostlight" } + ); + expect(beginResponse.status).toBe("accepted"); + const receipt = openPrivateEnvelope(decode(Buffer.from(beginResponse.payload, "base64")) as HeimdallPrivateEnvelope, ghostlightSecret); + expect(receipt.status).toBe("pending"); + + const handle = String(receipt.handle); + const state = new URL((receipt.navigation as { url: string }).url).searchParams.get("state") ?? ""; + expect(jwtPayload(state).handoff).toEqual({ kind: "browser_completion", attemptId: handle }); + + const { cookie } = await launchState(app, state); + const callback = await app.inject({ + method: "GET", + url: `/v1/oauth/discord/callback?code=victim&state=${encodeURIComponent(state)}`, + headers: { accept: "application/json", cookie }, + }); + expect(callback.statusCode).toBe(201); + expect((await store.findAuthAttempt("ghostlight", handle))?.status).toBe("completed"); + + const completeEnvelope = sealPrivateEnvelope({ + appSlug: "ghostlight", + operation: "heimdall.auth.complete", + contentSchema: "heimdall.auth_complete_command.v1", + idempotencyKey: "legit-complete", + secret: ghostlightSecret, + payload: { handle }, + }); + const completeResponse = await invokeCultNetOperation( + plane.endpoint, + envelopeRequest("heimdall.auth.complete", "msg-complete", completeEnvelope, "yggdrasil-ghostlight"), + { runtimeId: "yggdrasil-ghostlight" } + ); + expect(completeResponse.status).toBe("accepted"); + const completed = openPrivateEnvelope(decode(Buffer.from(completeResponse.payload, "base64")) as HeimdallPrivateEnvelope, ghostlightSecret); + expect(completed.status).toBe("authenticated"); + expect(completed.accessToken).toEqual(expect.any(String)); + expect((await store.findAuthAttempt("ghostlight", handle))?.status).toBe("consumed"); + }, 20_000); +});