ghostlight admits Google and honours the Dungeon's invite grant; public starts are refused
Profile: providers discord+google, no entitlement sources, startRequiresAppCaller, mayGrantFirstLogin, app_access on identity.authenticated. Private-plane begin threads firstLoginGrant 'invite' into startOAuthFlow and refuses any other value before an attempt exists. Schemas: google provider, optional policy and grant. Tests: public ghostlight starts 401, first Google login refused without a grant and minted under one, returning identity attaches nothing, discord without policy. Attempt-handle soul tests now send the app secret; the stranger case asserts 401. The refresh-diagnostics tests used ghostlight as a Discord-policy vehicle and now use bifrost, which still evaluates Discord. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
bd6e8d6d06
commit
a4532789e6
9 changed files with 228 additions and 33 deletions
|
|
@ -2,11 +2,12 @@
|
|||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||
"$id": "heimdall.auth_begin_command.v1",
|
||||
"type": "object",
|
||||
"required": ["provider", "mode", "returnTo", "entitlementPolicy"],
|
||||
"required": ["provider", "mode", "returnTo"],
|
||||
"properties": {
|
||||
"provider": { "enum": ["discord", "patreon", "github", "twitch", "youtube", "spotify", "joystick"] },
|
||||
"provider": { "enum": ["discord", "patreon", "github", "twitch", "youtube", "spotify", "joystick", "google"] },
|
||||
"mode": { "enum": ["sign_in", "link", "connect"] },
|
||||
"returnTo": { "type": "string", "format": "uri" },
|
||||
"firstLoginGrant": { "enum": ["invite"] },
|
||||
"entitlementPolicy": {
|
||||
"oneOf": [
|
||||
{
|
||||
|
|
|
|||
|
|
@ -2,7 +2,7 @@
|
|||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||
"$id": "heimdall.auth_refresh_command.v1",
|
||||
"type": "object",
|
||||
"required": ["schema", "refreshToken", "entitlementPolicy"],
|
||||
"required": ["schema", "refreshToken"],
|
||||
"properties": {
|
||||
"schema": { "const": "heimdall.auth_refresh_command.v1" },
|
||||
"refreshToken": { "type": "string", "minLength": 1 },
|
||||
|
|
|
|||
|
|
@ -188,23 +188,25 @@ const bifrostProfile: AppProfile = {
|
|||
const ghostlightProfile: AppProfile = {
|
||||
slug: "ghostlight",
|
||||
displayName: "Ghostlight Dungeon",
|
||||
profileVersion: "2026-08-22",
|
||||
identityProviders: ["discord"],
|
||||
entitlementSources: ["discord"],
|
||||
profileVersion: "2026-12-02",
|
||||
identityProviders: ["discord", "google"],
|
||||
entitlementSources: [],
|
||||
managedConnectionProviders: [],
|
||||
allowedReturnOrigins: ["https://yggdrasil.gamecult.org"],
|
||||
startRequiresAppCaller: true,
|
||||
mayGrantFirstLogin: true,
|
||||
capabilities: [
|
||||
{
|
||||
key: "app_access",
|
||||
mode: "shared",
|
||||
summary: "May enter Ghostlight Dungeon after Heimdall verifies the app-supplied GameCult Discord role policy.",
|
||||
anyOf: gameCultMembership,
|
||||
summary: "Heimdall authenticated this identity for Ghostlight; who may play is the Dungeon's account catalog.",
|
||||
anyOf: [identityFacts.authenticated],
|
||||
},
|
||||
{
|
||||
key: "campaign_play",
|
||||
mode: "hybrid",
|
||||
summary: "May play campaigns owned by the authenticated Ghostlight account.",
|
||||
localRequirement: "Ghostlight must combine app_access with local campaign ownership.",
|
||||
summary: "Ghostlight combines a Heimdall sign-in with its own account catalog and campaign ownership.",
|
||||
localRequirement: "Ghostlight combines a Heimdall sign-in with its own account catalog and campaign ownership.",
|
||||
},
|
||||
],
|
||||
};
|
||||
|
|
|
|||
|
|
@ -266,6 +266,9 @@ async function beginAuth(
|
|||
const returnTo = String(payload.returnTo ?? "");
|
||||
if (!providers.includes(provider) || !oauthModes.includes(mode) || !returnTo) throw new Error("Auth begin payload is incomplete.");
|
||||
const entitlementPolicy = parseEntitlementPolicy(payload.entitlementPolicy);
|
||||
// The app's word that it invited this person (the Dungeon holds the invite). Only the literal "invite" is a grant; startOAuthFlow's gate decides whether this app and mode may carry one.
|
||||
const grant = payload.firstLoginGrant;
|
||||
if (grant !== undefined && grant !== null && grant !== "invite") throw new Error("Auth begin payload is incomplete.");
|
||||
const store = getHeimdallRuntimeContext(app).store;
|
||||
const now = new Date();
|
||||
const attempt = await store.createAuthAttempt({
|
||||
|
|
@ -289,6 +292,7 @@ async function beginAuth(
|
|||
returnTo,
|
||||
handoff: { kind: "browser_completion" },
|
||||
...(entitlementPolicy ? { entitlementPolicy } : {}),
|
||||
...(grant === "invite" ? { firstLoginGrant: "invite" as const } : {}),
|
||||
},
|
||||
{ trustedBrowserAttemptId: attempt.handle }
|
||||
);
|
||||
|
|
|
|||
|
|
@ -318,10 +318,10 @@ describe("Heimdall service", () => {
|
|||
}
|
||||
});
|
||||
|
||||
it("flags only Bifrost's profile", () => {
|
||||
it("flags only Bifrost's and Ghostlight's profiles", () => {
|
||||
expect(
|
||||
Object.values(builtInAppProfiles).filter((profile) => profile.startRequiresAppCaller).map((profile) => profile.slug)
|
||||
).toEqual(["bifrost"]);
|
||||
Object.values(builtInAppProfiles).filter((profile) => profile.startRequiresAppCaller).map((profile) => profile.slug).sort()
|
||||
).toEqual(["bifrost", "ghostlight"]);
|
||||
});
|
||||
});
|
||||
|
||||
|
|
|
|||
|
|
@ -197,6 +197,8 @@ async function seedAccountAndSession(store: HeimdallStore, appSlug: AppSlug) {
|
|||
|
||||
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();
|
||||
|
|
@ -213,7 +215,7 @@ describe("R21.1: the attempt handle is unreachable from the public start route",
|
|||
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()));
|
||||
|
|
@ -236,7 +238,7 @@ describe("R21.1: the attempt handle is unreachable from the public start route",
|
|||
["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 });
|
||||
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" });
|
||||
|
|
@ -249,7 +251,7 @@ describe("R21.1: the attempt handle is unreachable from the public start route",
|
|||
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 });
|
||||
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" });
|
||||
|
|
@ -300,17 +302,16 @@ describe("R21.1: the attempt handle is unreachable from the public start route",
|
|||
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, then
|
||||
// completes as themselves before the victim does.
|
||||
// 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).toBe(201);
|
||||
const attackerCallback = await completeAs(app, stateOf(attackerStart.json()), "attacker");
|
||||
expect(attackerCallback.statusCode, attackerCallback.body).toBe(201);
|
||||
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.
|
||||
|
|
@ -339,7 +340,7 @@ describe("R21.1: the attempt handle is unreachable from the public start route",
|
|||
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.
|
||||
|
|
|
|||
|
|
@ -261,14 +261,14 @@ describe("attempt-handle binding: the public start route may attach a completion
|
|||
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).toBe(201);
|
||||
await completeAs(app, stateOf(attackerStart.json()), "attacker");
|
||||
expect([attackerStart.statusCode, attackerStart.json().error]).toEqual([401, "app_auth_required"]);
|
||||
|
||||
const after = await store.findAuthAttempt("ghostlight", attempt.handle);
|
||||
expect(after?.status).toBe("pending");
|
||||
|
|
|
|||
|
|
@ -1,18 +1,25 @@
|
|||
import { createHash, createSign, generateKeyPairSync } from "node:crypto";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { type FastifyInstance } from "fastify";
|
||||
import { decode, encode } from "@msgpack/msgpack";
|
||||
import { invokeCultNetOperation } from "cultnet-ts";
|
||||
import { buildApp } from "../src/app.js";
|
||||
import { loadConfig, type HeimdallConfig } from "../src/config.js";
|
||||
import { resetGoogleJwksCache } from "../src/google-oidc.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 { decodeJwt } from "../src/signing.js";
|
||||
import { IdentityHeldElsewhereError, InMemoryStore } from "../src/store/index.js";
|
||||
import { launchFlow, launchWithRedirect, stateOf, type LaunchedFlow } from "./oauth-flow.js";
|
||||
|
||||
const CLIENT_ID = "google-client";
|
||||
const GHOSTLIGHT_SECRET = "ghostlight-private-command-secret";
|
||||
const REDIRECT = "https://heimdall.gamecult.org/v1/oauth/google/callback";
|
||||
const rsa = generateKeyPairSync("rsa", { modulusLength: 2048 });
|
||||
const originalFetch = globalThis.fetch;
|
||||
const apps: FastifyInstance[] = [];
|
||||
const planes: Array<{ close(): Promise<unknown> }> = [];
|
||||
|
||||
function config(): HeimdallConfig {
|
||||
const base = loadConfig({
|
||||
|
|
@ -25,7 +32,10 @@ function config(): HeimdallConfig {
|
|||
storage: { backend: "memory", applySchemaOnStartup: true },
|
||||
tokenEncryptionKeyBase64: Buffer.alloc(32, 7).toString("base64"),
|
||||
bootstrapSigningPrivateKeyOnMissing: true,
|
||||
appSharedSecrets: { ...base.appSharedSecrets, bifrost: "bifrost-secret", repixelizer: "repixelizer-secret" },
|
||||
privateCommandHost: "127.0.0.1",
|
||||
privateCommandPort: 0,
|
||||
appSharedSecrets: { ...base.appSharedSecrets, bifrost: "bifrost-secret", repixelizer: "repixelizer-secret", ghostlight: GHOSTLIGHT_SECRET },
|
||||
appRuntimeIds: { ghostlight: ["yggdrasil-ghostlight"] },
|
||||
providers: {
|
||||
...base.providers,
|
||||
google: { clientId: CLIENT_ID, clientSecret: "google-secret" },
|
||||
|
|
@ -185,6 +195,7 @@ async function linkGoogle(app: FastifyInstance, token: string, claims?: Record<s
|
|||
afterEach(async () => {
|
||||
globalThis.fetch = originalFetch;
|
||||
resetGoogleJwksCache();
|
||||
while (planes.length) await planes.pop()?.close();
|
||||
while (apps.length) await apps.pop()?.close();
|
||||
});
|
||||
|
||||
|
|
@ -673,3 +684,179 @@ describe("an invite grant lets Bifrost's sign-in start mint the first Google acc
|
|||
expect(accountCount(store)).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe("ghostlight admits Google over the private command plane, and the Dungeon's invite is the only grant", () => {
|
||||
const RETURN = "https://yggdrasil.gamecult.org/ghostlight/";
|
||||
let seq = 0;
|
||||
|
||||
async function buildGhostlight() {
|
||||
const store = new InMemoryStore();
|
||||
const cfg = config();
|
||||
const app = await buildApp({ config: cfg, store, oauthRuntimes: { discord: discordRuntime("discord-1", "Person") } });
|
||||
apps.push(app);
|
||||
const plane = await startHeimdallPrivateCommandPlane(app, cfg);
|
||||
planes.push(plane);
|
||||
return { app, store, plane };
|
||||
}
|
||||
|
||||
/** One sealed command to the plane as Ghostlight's own runtime; the opened receipt, or the transport status when refused. */
|
||||
async function command(plane: { endpoint: string }, operation: string, contentSchema: string, payload: Record<string, unknown>) {
|
||||
const id = `gl-${++seq}`;
|
||||
const envelope = sealPrivateEnvelope({ appSlug: "ghostlight", operation, contentSchema, idempotencyKey: id, secret: GHOSTLIGHT_SECRET, payload });
|
||||
const response = await invokeCultNetOperation(
|
||||
plane.endpoint,
|
||||
{
|
||||
schemaVersion: "cultnet.operation_request.v0" as const,
|
||||
messageId: id,
|
||||
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",
|
||||
},
|
||||
{ runtimeId: "yggdrasil-ghostlight" }
|
||||
);
|
||||
if (response.status !== "accepted") return { status: response.status, receipt: undefined };
|
||||
const wire = decode(Buffer.from(response.payload, "base64")) as HeimdallPrivateEnvelope;
|
||||
return { status: response.status, receipt: openPrivateEnvelope(wire, GHOSTLIGHT_SECRET) as Record<string, unknown> };
|
||||
}
|
||||
|
||||
const begin = (plane: { endpoint: string }, payload: Record<string, unknown>) =>
|
||||
command(plane, "heimdall.auth.begin", "heimdall.auth_begin_command.v1", { mode: "sign_in", returnTo: RETURN, ...payload });
|
||||
const complete = (plane: { endpoint: string }, handle: unknown) =>
|
||||
command(plane, "heimdall.auth.complete", "heimdall.auth_complete_command.v1", { handle });
|
||||
|
||||
/** Begin google as Ghostlight, walk the browser to Google and back, and return the callback answer plus the attempt handle. */
|
||||
async function googleSignIn(app: FastifyInstance, plane: { endpoint: string }, payload: Record<string, unknown>, claims?: Record<string, unknown>) {
|
||||
const started = await begin(plane, { provider: "google", ...payload });
|
||||
expect(started.status).toBe("accepted");
|
||||
const receipt = started.receipt as { handle: string; navigation: { url: string } };
|
||||
const flow = await launchWithRedirect(app, { authorizationUrl: receipt.navigation.url });
|
||||
fakeGoogle({ nonceFrom: () => flow.url.searchParams.get("nonce") ?? undefined, ...(claims ? { claims } : {}) });
|
||||
return { handle: receipt.handle, done: await callbackGoogle(app, flow) };
|
||||
}
|
||||
|
||||
const auditEvents = (store: InMemoryStore) =>
|
||||
[...(store as unknown as { auditEvents: Map<string, { eventType: string; eventPayloadJson?: unknown }> }).auditEvents.values()];
|
||||
const attemptCount = (store: InMemoryStore) => (store as unknown as { authAttempts: Map<string, unknown> }).authAttempts.size;
|
||||
const capabilitiesOf = (receipt: Record<string, unknown> | undefined) =>
|
||||
decodeJwt(String(receipt?.accessToken)).payload.capabilities as string[];
|
||||
|
||||
it("a first Google sign-in under the Dungeon's invite grant mints one account, audits it, and the claim carries app_access", async () => {
|
||||
const { app, store, plane } = await buildGhostlight();
|
||||
const { handle, done } = await googleSignIn(app, plane, { firstLoginGrant: "invite" });
|
||||
expect(done.statusCode, done.body).toBe(201);
|
||||
expect(accountCount(store)).toBe(1);
|
||||
const minted = auditEvents(store).filter((e) => e.eventType === "account_minted_by_grant");
|
||||
expect(minted.map((e) => e.eventPayloadJson)).toEqual([{ provider: "google", appSlug: "ghostlight" }]);
|
||||
const completion = (await complete(plane, handle)).receipt;
|
||||
expect(completion).toMatchObject({ status: "authenticated", handle });
|
||||
expect(capabilitiesOf(completion)).toContain("app_access");
|
||||
});
|
||||
|
||||
it("a first Google sign-in with no live grant is refused identity_not_linked and mints nothing", async () => {
|
||||
const { app, store, plane } = await buildGhostlight();
|
||||
for (const extra of [{}, { firstLoginGrant: null }]) {
|
||||
const { handle, done } = await googleSignIn(app, plane, extra);
|
||||
expect([done.statusCode, done.json().error]).toEqual([403, "identity_not_linked"]);
|
||||
expect(auditEvents(store).some((e) => e.eventType === "account_minted_by_grant")).toBe(false);
|
||||
expect((await complete(plane, handle)).receipt?.status).toBe("denied");
|
||||
}
|
||||
expect(accountCount(store)).toBe(0);
|
||||
});
|
||||
|
||||
it("a returning Google identity signs in to its own account with or without the grant, and the grant attaches nothing", async () => {
|
||||
const { app, store, plane } = await buildGhostlight();
|
||||
const first = await googleSignIn(app, plane, { firstLoginGrant: "invite" });
|
||||
const accountId = first.done.json().account.id;
|
||||
for (const extra of [{}, { firstLoginGrant: "invite" }]) {
|
||||
const again = await googleSignIn(app, plane, extra);
|
||||
expect(again.done.statusCode, again.done.body).toBe(201);
|
||||
expect(again.done.json().account.id).toBe(accountId);
|
||||
}
|
||||
// A different Google subject under the grant is its own new account; the held one is never moved.
|
||||
const other = await googleSignIn(app, plane, { firstLoginGrant: "invite" }, { sub: "g-sub-2" });
|
||||
expect(other.done.json().account.id).not.toBe(accountId);
|
||||
expect((await store.findStoredLinkedIdentity("google", "g-sub-1"))?.accountId).toBe(accountId);
|
||||
expect(accountCount(store)).toBe(2);
|
||||
expect(auditEvents(store).filter((e) => e.eventType === "account_minted_by_grant")).toHaveLength(2);
|
||||
});
|
||||
|
||||
it("discord begins and refreshes with no entitlement policy, and the claim carries app_access", async () => {
|
||||
const { app, plane } = await buildGhostlight();
|
||||
const started = await begin(plane, { provider: "discord" });
|
||||
expect(started.status).toBe("accepted");
|
||||
const receipt = started.receipt as { handle: string; navigation: { url: string } };
|
||||
const flow = await launchFlow(app, { authorizationUrl: receipt.navigation.url });
|
||||
const callback = await app.inject({
|
||||
method: "GET",
|
||||
url: `/v1/oauth/discord/callback?code=c&state=${encodeURIComponent(flow.state)}`,
|
||||
headers: { cookie: flow.cookie },
|
||||
});
|
||||
expect(callback.statusCode, callback.body).toBe(201);
|
||||
const completion = (await complete(plane, receipt.handle)).receipt;
|
||||
expect(completion?.status).toBe("authenticated");
|
||||
expect(capabilitiesOf(completion)).toContain("app_access");
|
||||
const refreshed = await command(plane, "heimdall.auth.refresh", "heimdall.auth_refresh_command.v1", { refreshToken: completion?.refreshToken });
|
||||
expect(refreshed.receipt).toMatchObject({ schema: "heimdall.auth_refresh_receipt.v1", status: "authenticated" });
|
||||
expect(capabilitiesOf(refreshed.receipt)).toContain("app_access");
|
||||
});
|
||||
|
||||
it("a public ghostlight start, with no secret or the wrong one, is refused app_auth_required for every provider", async () => {
|
||||
const { app, store } = await buildGhostlight();
|
||||
for (const provider of ["google", "discord"]) {
|
||||
for (const headers of [{}, { "x-heimdall-app-secret": "wrong" }, { "x-heimdall-app-secret": "bifrost-secret" }]) {
|
||||
const res = await app.inject({
|
||||
method: "POST",
|
||||
url: `/v1/oauth/${provider}/start`,
|
||||
headers,
|
||||
payload: { appSlug: "ghostlight", mode: "sign_in", returnTo: RETURN },
|
||||
});
|
||||
expect([res.statusCode, res.json().error], `${provider} ${JSON.stringify(headers)}`).toEqual([401, "app_auth_required"]);
|
||||
expect(res.json().authorizationUrl).toBeUndefined();
|
||||
}
|
||||
}
|
||||
// The same start with a grant is no easier without the app's secret.
|
||||
const granted = await app.inject({
|
||||
method: "POST",
|
||||
url: "/v1/oauth/google/start",
|
||||
payload: { appSlug: "ghostlight", mode: "sign_in", returnTo: RETURN, firstLoginGrant: "invite" },
|
||||
});
|
||||
expect([granted.statusCode, granted.json().error]).toEqual([401, "app_auth_required"]);
|
||||
expect(accountCount(store)).toBe(0);
|
||||
expect(attemptCount(store)).toBe(0);
|
||||
});
|
||||
|
||||
it("a begin whose firstLoginGrant is anything but 'invite' is refused before any attempt or state is minted", async () => {
|
||||
const { plane, store } = await buildGhostlight();
|
||||
for (const bad of ["yes", "admin", true, 1, {}]) {
|
||||
const res = await begin(plane, { provider: "google", firstLoginGrant: bad });
|
||||
expect(res.status, JSON.stringify(bad)).not.toBe("accepted");
|
||||
}
|
||||
expect(attemptCount(store)).toBe(0);
|
||||
});
|
||||
|
||||
it("a grant on link mode is refused by startOAuthFlow's gate, not smuggled past it", async () => {
|
||||
const { plane } = await buildGhostlight();
|
||||
const res = await begin(plane, { provider: "google", mode: "link", firstLoginGrant: "invite" });
|
||||
expect(res.status).not.toBe("accepted");
|
||||
});
|
||||
|
||||
it("other apps are unchanged: repixelizer's public start still opens and its grant is still first_login_grant_refused", async () => {
|
||||
const { app } = await buildGhostlight();
|
||||
const open = await app.inject({
|
||||
method: "POST",
|
||||
url: "/v1/oauth/discord/start",
|
||||
payload: { appSlug: "repixelizer", mode: "sign_in", returnTo: "https://repixelizer.gamecult.org/app/" },
|
||||
});
|
||||
expect(open.statusCode).toBe(201);
|
||||
const granted = await app.inject({
|
||||
method: "POST",
|
||||
url: "/v1/oauth/discord/start",
|
||||
headers: { "x-heimdall-app-secret": "repixelizer-secret" },
|
||||
payload: { appSlug: "repixelizer", mode: "sign_in", returnTo: "https://repixelizer.gamecult.org/app/", firstLoginGrant: "invite" },
|
||||
});
|
||||
expect([granted.statusCode, granted.json().error]).toEqual([400, "first_login_grant_refused"]);
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -14,7 +14,7 @@ import { openPrivateEnvelope, sealPrivateEnvelope, type HeimdallPrivateEnvelope
|
|||
import { InMemoryStore } from "../src/store/index.js";
|
||||
import { launchState } from "./oauth-flow.js";
|
||||
|
||||
const secret = "ghostlight-private-command-secret";
|
||||
const secret = "bifrost-private-command-secret";
|
||||
const resources: Array<{ close(): Promise<unknown> }> = [];
|
||||
afterEach(async () => {
|
||||
vi.unstubAllGlobals();
|
||||
|
|
@ -29,24 +29,24 @@ function config(): HeimdallConfig {
|
|||
idunnRudpHealth: undefined, idunnHealthContract: "heimdall.cultnet-rudp-provider-health", providerHealthIdentityPath: "/tmp/.hd/p.cc",
|
||||
sessionTtlSeconds: 3600, refreshTtlSeconds: 3600, stateTtlSeconds: 600, completionTtlSeconds: 300,
|
||||
bootstrapSigningPrivateKeyOnMissing: false, tokenEncryptionKeyBase64: Buffer.alloc(32, 7).toString("base64"),
|
||||
appSharedSecrets: { ghostlight: secret }, appRuntimeIds: { ghostlight: ["yggdrasil-ghostlight"] }, appBackendCallbacks: {},
|
||||
appSharedSecrets: { bifrost: secret }, appRuntimeIds: { bifrost: ["bifrost-runtime"] }, appBackendCallbacks: {},
|
||||
storage: { backend: "memory", applySchemaOnStartup: true },
|
||||
providers: { discord: { clientId: "discord-client", clientSecret: "discord-secret" }, patreon: {}, github: {}, twitch: {}, youtube: {}, spotify: {}, joystick: {}, google: {} },
|
||||
} as HeimdallConfig;
|
||||
}
|
||||
|
||||
async function command(endpoint: unknown, operation: string, contentSchema: string, key: string, payload: Record<string, unknown>) {
|
||||
const envelope = sealPrivateEnvelope({ appSlug: "ghostlight", operation, contentSchema, idempotencyKey: key, secret, payload });
|
||||
const envelope = sealPrivateEnvelope({ appSlug: "bifrost", operation, contentSchema, idempotencyKey: key, secret, payload });
|
||||
return invokeCultNetOperation(endpoint as never, {
|
||||
schemaVersion: "cultnet.operation_request.v0", messageId: `m-${key}`, serviceId: "heimdall.private.commands", operation,
|
||||
payloadSchema: "heimdall.private_command_envelope.v1", payloadEncoding: "messagepack-base64",
|
||||
payload: Buffer.from(encode(envelope)).toString("base64"), sourceRuntimeId: "yggdrasil-ghostlight",
|
||||
} as never, { runtimeId: "yggdrasil-ghostlight" });
|
||||
payload: Buffer.from(encode(envelope)).toString("base64"), sourceRuntimeId: "bifrost-runtime",
|
||||
} as never, { runtimeId: "bifrost-runtime" });
|
||||
}
|
||||
const open = (reply: { payload: string }) =>
|
||||
openPrivateEnvelope(decode(Buffer.from(reply.payload, "base64")) as HeimdallPrivateEnvelope, secret);
|
||||
|
||||
/** A signed-in Ghostlight session, then a refresh whose provider answer is `refreshAnswer`. */
|
||||
/** A signed-in Bifrost session, then a refresh whose provider answer is `refreshAnswer`. */
|
||||
async function refreshAgainst(refreshAnswer: () => Response) {
|
||||
let refreshing = false;
|
||||
vi.stubGlobal("fetch", async (url: string | URL, init?: RequestInit) => {
|
||||
|
|
@ -72,7 +72,7 @@ async function refreshAgainst(refreshAnswer: () => Response) {
|
|||
resources.push(plane);
|
||||
const policy = { kind: "discord_role_access", guildId: "g", allowedRoleIds: ["r"] };
|
||||
const begin = open(await command(plane.endpoint, "heimdall.auth.begin", "heimdall.auth_begin_command.v1", "k1",
|
||||
{ provider: "discord", mode: "sign_in", returnTo: "https://yggdrasil.gamecult.org/ghostlight/", entitlementPolicy: policy }));
|
||||
{ provider: "discord", mode: "sign_in", returnTo: "https://bifrost.gamecult.org/auth/heimdall/complete", entitlementPolicy: policy }));
|
||||
const state = new URL(String((begin.navigation as { url: string }).url)).searchParams.get("state")!;
|
||||
const { cookie } = await launchState(app, state);
|
||||
const callback = await app.inject({
|
||||
|
|
@ -133,7 +133,7 @@ it("keeps the completion code out of the audit trail when the plane redeems by a
|
|||
resources.push(plane);
|
||||
const policy = { kind: "discord_role_access", guildId: "g", allowedRoleIds: ["r"] };
|
||||
const begin = open(await command(plane.endpoint, "heimdall.auth.begin", "heimdall.auth_begin_command.v1", "k1",
|
||||
{ provider: "discord", mode: "sign_in", returnTo: "https://yggdrasil.gamecult.org/ghostlight/", entitlementPolicy: policy }));
|
||||
{ provider: "discord", mode: "sign_in", returnTo: "https://bifrost.gamecult.org/auth/heimdall/complete", entitlementPolicy: policy }));
|
||||
const state = new URL(String((begin.navigation as { url: string }).url)).searchParams.get("state")!;
|
||||
const { cookie } = await launchState(app, state);
|
||||
const callback = await app.inject({
|
||||
|
|
|
|||
Loading…
Reference in a new issue