Multiplayer agent harness for work.
Remember email sign-in browsers with revocable broker sessions (#1030)
Regan Belld2def2f4ad14
diff --git a/package.json b/package.jsonindex c12b42cc7..6a858b201 100644--- a/package.json+++ b/package.json@@ -36,7 +36,7 @@"sandbox:local:build": "bash scripts/local-sandbox-build.sh","sandbox:porter:build": "docker build --platform linux/amd64 -t \"${PORTER_SANDBOX_IMAGE:?Set PORTER_SANDBOX_IMAGE to the registry tag to publish}\" porter && docker push \"$PORTER_SANDBOX_IMAGE\"","deploy:porter-runner-image": "docker build --platform linux/amd64 -t \"${PORTER_DEPLOY_RUNNER_IMAGE:?Set PORTER_DEPLOY_RUNNER_IMAGE to the registry tag to publish}\" -f deploy/porter-runner/Dockerfile . && docker push \"$PORTER_DEPLOY_RUNNER_IMAGE\"",- "test:pg": "node --test --test-concurrency=1 test/postgres-store.test.ts test/postgres-grant-store.test.ts test/postgres-admin-grants.test.ts test/postgres-file-artifact-store.test.ts test/postgres-directory-store.test.ts test/postgres-map.test.ts test/deploy-store-pg.test.ts test/postgres-cron-fires.test.ts test/postgres-migration-adoption.test.ts test/cron-queue.test.ts test/postgres-metrics-sink.test.ts test/postgres-error-log.test.ts test/postgres-audit-log.test.ts test/postgres-budget.test.ts test/postgres-rate-limiter.test.ts test/postgres-credential-usage-sink.test.ts test/postgres-config-store.test.ts test/postgres-delivery-store.test.ts test/postgres-replay-dedupe.test.ts test/postgres-egress-audit-sink.test.ts test/postgres-memory-service.test.ts test/run-signal-store.test.ts test/postgres-run-activity-store.test.ts test/leader-lease.test.ts test/advisory-lock.test.ts test/persistence-init-retry.test.ts test/migrate-principals.test.ts test/postgres-surface-cache.test.ts test/postgres-instance-registry.test.ts",+ "test:pg": "node --test --test-concurrency=1 test/postgres-store.test.ts test/postgres-grant-store.test.ts test/postgres-admin-grants.test.ts test/postgres-file-artifact-store.test.ts test/postgres-directory-store.test.ts test/postgres-map.test.ts test/deploy-store-pg.test.ts test/postgres-cron-fires.test.ts test/postgres-migration-adoption.test.ts test/cron-queue.test.ts test/postgres-metrics-sink.test.ts test/postgres-error-log.test.ts test/postgres-audit-log.test.ts test/postgres-budget.test.ts test/postgres-rate-limiter.test.ts test/postgres-credential-usage-sink.test.ts test/postgres-config-store.test.ts test/postgres-delivery-store.test.ts test/postgres-replay-dedupe.test.ts test/postgres-broker-sessions.test.ts test/postgres-egress-audit-sink.test.ts test/postgres-memory-service.test.ts test/run-signal-store.test.ts test/postgres-run-activity-store.test.ts test/leader-lease.test.ts test/advisory-lock.test.ts test/persistence-init-retry.test.ts test/migrate-principals.test.ts test/postgres-surface-cache.test.ts test/postgres-instance-registry.test.ts","livetest": "node scripts/api-livetest.ts","bench:memory": "node --env-file-if-exists=.env scripts/memory-bench.ts","prepare": "node .husky/install.mjs",diff --git a/plugins/auth/README.md b/plugins/auth/README.mdindex 39960227a..32b5f2513 100644--- a/plugins/auth/README.md+++ b/plugins/auth/README.md@@ -107,3 +107,32 @@ the per-address budget is what bounds a single source. Both are durable claims,so they survive restarts, and both are keyed by an HMAC under`AUTH_TOKEN_SECRET` so another plugin holding the shared core signing secretcannot compute — and pre-claim — a chosen mailbox's slots.++## Remembered browsers++Verifying an email link creates a durable broker session in core's Postgres store.+The browser receives an HttpOnly, Secure, SameSite=Lax cookie scoped to the issuer+path (`/idp` behind the portal). Core stores only a hash of the random token; the+cookie also carries a broker-only MAC, so another plugin's core signing credential+cannot manufacture an email sign-in. Rotating `AUTH_TOKEN_SECRET` invalidates all+remembered cookies.++`AUTH_SESSION_IDLE_S` defaults to 30 days and `AUTH_SESSION_ABSOLUTE_S` defaults+to 90 days. Both are whole seconds; the idle limit must not exceed the absolute+limit, and the absolute limit cannot exceed 90 days. Reauthorization slides the+idle expiry without moving the original authentication time or absolute expiry.+The broker rechecks email eligibility before issuing and exchanging a code.++`prompt=login` and `max_age=0` always require a fresh email. A positive `max_age`+compares against the original email authentication time, also returned as+`auth_time` in the ID token. `prompt=none` returns `login_required` when silent+reauthentication is unavailable. Invalid prompt and max-age values fail closed.++The portal forwards only the broker cookie to `/idp` and preserves all broker+Set-Cookie headers. Ordinary `POST /auth/logout` clears both local cookies.+`POST /auth/logout?everywhere=1` additionally revokes all remembered browsers for+the authenticated email principal. The signed core endpoint+`POST /v1/auth/broker/sessions/revoke` accepts `{ "email": "[email protected]" }`+from that user's portal identity or an authorized administrator. These operations+prevent future silent reauthentication; already-issued stateless portal sessions+remain valid until their normal expiry.diff --git a/plugins/auth/src/config.ts b/plugins/auth/src/config.tsindex 2413bb035..40626696b 100644--- a/plugins/auth/src/config.ts+++ b/plugins/auth/src/config.ts@@ -25,6 +25,8 @@ export interface AuthConfig {transport: EmailTransportKind;resendApiKey: string;smtp: SmtpSettings;+ sessionIdleS: number;+ sessionAbsoluteS: number;linkTtlS: number;codeTtlS: number;accessTtlS: number;@@ -105,6 +107,8 @@ export function readConfig(env: NodeJS.ProcessEnv): AuthConfig {password: env.SMTP_PASSWORD ?? "",tls: smtpTlsFrom(env.SMTP_TLS, env.SMTP_PORT),},+ sessionIdleS: numberFrom(env.AUTH_SESSION_IDLE_S, 30 * 86400),+ sessionAbsoluteS: numberFrom(env.AUTH_SESSION_ABSOLUTE_S, 90 * 86400),linkTtlS: numberFrom(env.AUTH_LINK_TTL_S, 900),codeTtlS: numberFrom(env.AUTH_CODE_TTL_S, 120),accessTtlS: numberFrom(env.AUTH_ACCESS_TTL_S, 120),@@ -233,6 +237,15 @@ export function bootProblems(cfg: AuthConfig, isProd: boolean): string[] {);}}+ if (+ !Number.isInteger(cfg.sessionIdleS) ||+ !Number.isInteger(cfg.sessionAbsoluteS) ||+ cfg.sessionIdleS > cfg.sessionAbsoluteS ||+ cfg.sessionAbsoluteS > 90 * 86400+ )+ problems.push(+ "AUTH_SESSION_IDLE_S and AUTH_SESSION_ABSOLUTE_S must be whole seconds with idle <= absolute <= 90 days",+ );return problems;}diff --git a/plugins/auth/src/index.ts b/plugins/auth/src/index.tsindex ce34c6830..eb8695e50 100644--- a/plugins/auth/src/index.ts+++ b/plugins/auth/src/index.ts@@ -1,3 +1,4 @@+import { coreRememberedSessions } from "./sessions.ts";import { createServer } from "node:http";import { pathToFileURL } from "node:url";import { json } from "../../chassis/src/http.ts";@@ -40,6 +41,7 @@ export async function startServer(): Promise<void> {cfg: CFG,signingKey,signer: new TokenSigner(CFG.tokenSecret, CFG.issuer),+ sessions: coreRememberedSessions(CFG.coreApiUrl, CFG.coreSigningSecret),claims: coreClaimStore(CFG.coreApiUrl, CFG.coreSigningSecret, "auth"),mailer,brandName: () => {diff --git a/plugins/auth/src/server.ts b/plugins/auth/src/server.tsindex 8be75a92a..b0c8c6cc5 100644--- a/plugins/auth/src/server.ts+++ b/plugins/auth/src/server.ts@@ -1,3 +1,5 @@+import { createHmac } from "node:crypto";+import { coreRememberedSessions, type RememberedSessions, type RememberedSession } from "./sessions.ts";import type { IncomingMessage, ServerResponse } from "node:http";import { readBody, PayloadTooLargeError, sendBuffered, serveEmojiFavicon } from "../../chassis/src/http.ts";import { errMessage } from "../../chassis/src/errors.ts";@@ -19,6 +21,7 @@ export interface AuthDeps {signingKey: SigningKey;signer: TokenSigner;claims: ClaimStore;+ sessions?: RememberedSessions;mailer: Mailer | null;brandName?: () => string;emailAllowed?: (email: string) => Promise<boolean>;@@ -71,7 +74,7 @@ function basicCredentials(header: string | undefined): { id: string; secret: strfunction readAuthorizeRequest(cfg: AuthConfig,params: URLSearchParams,-): { request: AuthRequest } | { problem: string } {+): { request: AuthRequest; prompt: string; maxAge: number | undefined } | { problem: string } {const clientId = params.get("client_id") ?? "";const redirectUri = params.get("redirect_uri") ?? "";if (!clientId || !safeEqual(clientId, cfg.clientId))@@ -91,11 +94,23 @@ function readAuthorizeRequest(if (!nonce || nonce.length > 512) return { problem: "This sign-in request is missing its nonce." };const scope = params.get("scope") ?? "openid";if (!scope.split(/\s+/).includes("openid")) return { problem: "This sign-in request must ask for the openid scope." };- return { request: { clientId, redirectUri, state, nonce, codeChallenge, scope } };+ const prompt = params.get("prompt") ?? "";+ const prompts = prompt.split(/\s+/).filter(Boolean);+ if (prompts.some((value) => !["login", "none"].includes(value)) || (prompts.includes("none") && prompts.length > 1))+ return { problem: "Unsupported prompt." };+ const rawMaxAge = params.get("max_age");+ if (rawMaxAge !== null && (!/^\d+$/.test(rawMaxAge) || !Number.isSafeInteger(Number(rawMaxAge))))+ return { problem: "max_age must be a nonnegative whole number of seconds." };+ return {+ request: { clientId, redirectUri, state, nonce, codeChallenge, scope },+ prompt,+ maxAge: rawMaxAge === null ? undefined : Number(rawMaxAge),+ };}export function createAuthHandler(deps: AuthDeps): (req: IncomingMessage, res: ServerResponse) => Promise<void> {const { cfg, signer, claims, mailer, signingKey } = deps;+ const sessions = deps.sessions ?? coreRememberedSessions(cfg.coreApiUrl, cfg.coreSigningSecret);const brandName = deps.brandName ?? ((): string => cfg.brandName);const invited =deps.emailAllowed ??@@ -153,7 +168,56 @@ export function createAuthHandler(deps: AuthDeps): (req: IncomingMessage, res: S}),);- async function authorizeForm(res: ServerResponse, params: URLSearchParams): Promise<void> {+ const cookieSignature = (token: string): string =>+ createHmac("sha256", cfg.tokenSecret)+ .update(`qm-auth.browser.v1\n${cfg.issuer}\n${cfg.clientId}\n${token}`)+ .digest("base64url");++ const rememberedToken = (req: IncomingMessage): string | undefined => {+ const values = (req.headers.cookie ?? "")+ .split(";")+ .map((part) => part.trim())+ .filter((part) => part.startsWith("qm_idp_session="));+ const value = values.length === 1 ? values[0]!.slice("qm_idp_session=".length) : "";+ const [token, signature] = value.split(".");+ return /^[A-Za-z0-9_-]{43}\.[A-Za-z0-9_-]{43}$/.test(value) &&+ token &&+ signature &&+ safeEqual(signature, cookieSignature(token))+ ? token+ : undefined;+ };++ const sessionCookie = (token: string, session: RememberedSession): string =>+ `qm_idp_session=${token}.${cookieSignature(token)}; HttpOnly; Secure; SameSite=Lax; Path=${cfg.publicPath || "/"}; Max-Age=${Math.max(0, Math.floor((session.expiresAtMs - now()) / 1000))}`;++ async function issueCode(+ res: ServerResponse,+ request: AuthRequest,+ email: string,+ authTime: number,+ cookie: string,+ ): Promise<void> {+ const code = await signer.sealCode(+ {+ clientId: request.clientId,+ redirectUri: request.redirectUri,+ nonce: request.nonce,+ codeChallenge: request.codeChallenge,+ email,+ authTime,+ },+ cfg.codeTtlS,+ now(),+ );+ const destination = new URL(request.redirectUri);+ destination.searchParams.set("code", code.token);+ destination.searchParams.set("state", request.state);+ res.writeHead(302, noStore({ location: destination.toString(), "set-cookie": cookie }));+ res.end();+ }++ async function authorizeForm(req: IncomingMessage, res: ServerResponse, params: URLSearchParams): Promise<void> {const parsed = readAuthorizeRequest(cfg, params);if ("problem" in parsed)return problem(@@ -163,6 +227,33 @@ export function createAuthHandler(deps: AuthDeps): (req: IncomingMessage, res: S"Start again from the page you were trying to reach.",parsed.problem,);+ const token = rememberedToken(req);+ if (token && !parsed.prompt.split(/\s+/).includes("login") && parsed.maxAge !== 0) {+ let session: RememberedSession | null;+ try {+ session = await sessions.use(token);+ } catch {+ return problem(+ res,+ 503,+ "Sign-in is temporarily unavailable",+ "The sign-in service cannot reach its backend. Try again in a minute.",+ );+ }+ if (+ session &&+ (parsed.maxAge === undefined || Math.floor(now() / 1000) - session.authTime <= parsed.maxAge) &&+ (await emailAllowed(session.email))+ )+ return issueCode(res, parsed.request, session.email, session.authTime, sessionCookie(token, session));+ }+ if (parsed.prompt.split(/\s+/).includes("none")) {+ const destination = new URL(parsed.request.redirectUri);+ destination.searchParams.set("error", "login_required");+ destination.searchParams.set("state", parsed.request.state);+ res.writeHead(302, noStore({ location: destination.toString() }));+ return void res.end();+ }if (!mailer) return emailUnavailable(res);const sealed = await signer.sealRequest(parsed.request, cfg.requestTtlS, now());return sendHtml(@@ -290,22 +381,18 @@ export function createAuthHandler(deps: AuthDeps): (req: IncomingMessage, res: Sif (!(await emailAllowed(link.email))) {return problem(res, 403, "This address can't sign in", "Your administrator has not allowed this email address.");}- const code = await signer.sealCode(- {- clientId: link.clientId,- redirectUri: link.redirectUri,- nonce: link.nonce,- codeChallenge: link.codeChallenge,- email: link.email,- },- cfg.codeTtlS,- now(),- );- const destination = new URL(link.redirectUri);- destination.searchParams.set("code", code.token);- destination.searchParams.set("state", link.state);- res.writeHead(302, noStore({ location: destination.toString() }));- res.end();+ let session: RememberedSession & { token: string };+ try {+ session = await sessions.create(link.email, cfg.sessionIdleS, cfg.sessionAbsoluteS);+ } catch {+ return problem(+ res,+ 503,+ "Sign-in is temporarily unavailable",+ "The sign-in service cannot remember this browser. Request a fresh link in a minute.",+ );+ }+ return issueCode(res, link, link.email, session.authTime, sessionCookie(session.token, session));}async function token(req: IncomingMessage, res: ServerResponse): Promise<void> {@@ -356,6 +443,7 @@ export function createAuthHandler(deps: AuthDeps): (req: IncomingMessage, res: Semail: granted.email,nonce: granted.nonce,ttlS: ID_TOKEN_TTL_S,+ authTime: granted.authTime,nowMs,});const access = await signer.sealAccess({ sub, email: granted.email }, cfg.accessTtlS, nowMs);@@ -397,7 +485,7 @@ export function createAuthHandler(deps: AuthDeps): (req: IncomingMessage, res: Ssubject_types_supported: ["public"],id_token_signing_alg_values_supported: [ID_TOKEN_ALG],scopes_supported: ["openid", "email"],- claims_supported: ["sub", "iss", "aud", "exp", "iat", "nonce", "azp", "email", "email_verified"],+ claims_supported: ["sub", "iss", "aud", "exp", "iat", "nonce", "azp", "email", "email_verified", "auth_time"],token_endpoint_auth_methods_supported: ["client_secret_basic"],code_challenge_methods_supported: ["S256"],});@@ -426,7 +514,7 @@ export function createAuthHandler(deps: AuthDeps): (req: IncomingMessage, res: Sreturn void res.end(JSON.stringify({ keys: [signingKey.publicJwk] }));}if (method === "GET" && path === "/.well-known/openid-configuration") return discovery(res);- if (method === "GET" && path === "/authorize") return authorizeForm(res, url.searchParams);+ if (method === "GET" && path === "/authorize") return authorizeForm(req, res, url.searchParams);if (method === "POST" && path === "/authorize") return authorizeSubmit(req, res);if (method === "GET" && path === "/verify") return confirmVerify(res);if (method === "POST" && path === "/verify") return verify(req, res);diff --git a/plugins/auth/src/sessions.ts b/plugins/auth/src/sessions.tsnew file mode 100644index 000000000..26629dfa9--- /dev/null+++ b/plugins/auth/src/sessions.ts@@ -0,0 +1,35 @@+import { signedHeaders, withSourceAuthNonce } from "../../chassis/src/core-client.ts";++export interface RememberedSession {+ email: string;+ authTime: number;+ expiresAtMs: number;+}++export interface RememberedSessions {+ create(email: string, idleS: number, absoluteS: number): Promise<RememberedSession & { token: string }>;+ use(token: string): Promise<RememberedSession | null>;+}++export function coreRememberedSessions(baseUrl: string, secret: string | undefined): RememberedSessions {+ async function post(pathname: string, data: unknown): Promise<unknown> {+ const path = withSourceAuthNonce(`/v1/auth/broker/sessions${pathname}`, secret);+ const body = JSON.stringify(data);+ const response = await fetch(`${baseUrl}${path}`, {+ method: "POST",+ headers: signedHeaders(secret, "POST", path, body),+ body,+ signal: AbortSignal.timeout(4_000),+ });+ if (!response.ok) throw new Error(`broker sessions unavailable: HTTP ${response.status}`);+ return response.json();+ }+ return {+ async create(email, idleS, absoluteS) {+ return (await post("", { email, idleS, absoluteS })) as RememberedSession & { token: string };+ },+ async use(token) {+ return ((await post("/use", { token })) as { session: RememberedSession | null }).session;+ },+ };+}diff --git a/plugins/auth/src/tokens.ts b/plugins/auth/src/tokens.tsindex 1481cfc45..66a8287dc 100644--- a/plugins/auth/src/tokens.ts+++ b/plugins/auth/src/tokens.ts@@ -18,6 +18,7 @@ export interface LinkClaims extends AuthRequest {}export interface CodeClaims {+ authTime?: number;clientId: string;redirectUri: string;nonce: string;@@ -134,7 +135,14 @@ export class TokenSigner {async sealCode(claims: CodeClaims, ttlS: number, nowMs?: number): Promise<SealedToken> {return this.seal("code",- { cid: claims.clientId, ru: claims.redirectUri, no: claims.nonce, cc: claims.codeChallenge, em: claims.email },+ {+ cid: claims.clientId,+ ru: claims.redirectUri,+ no: claims.nonce,+ cc: claims.codeChallenge,+ em: claims.email,+ at: claims.authTime,+ },ttlS,nowMs,);@@ -155,6 +163,7 @@ export class TokenSigner {nonce: no as string,codeChallenge: cc as string,email: em as string,+ ...(typeof payload.at === "number" ? { authTime: payload.at } : {}),},jti: String(payload.jti),expiresAtMs: Number(payload.exp) * 1000,@@ -198,10 +207,25 @@ function readRequest(payload: JWTPayload): AuthRequest | null {export async function mintIdToken(key: SigningKey,- args: { issuer: string; clientId: string; sub: string; email: string; nonce: string; ttlS: number; nowMs?: number },+ args: {+ issuer: string;+ clientId: string;+ sub: string;+ email: string;+ nonce: string;+ ttlS: number;+ nowMs?: number;+ authTime?: number;+ },): Promise<string> {const issuedAt = Math.floor((args.nowMs ?? Date.now()) / 1000);- return new SignJWT({ nonce: args.nonce, azp: args.clientId, email: args.email, email_verified: true })+ return new SignJWT({+ nonce: args.nonce,+ azp: args.clientId,+ email: args.email,+ email_verified: true,+ ...(args.authTime !== undefined ? { auth_time: args.authTime } : {}),+ }).setProtectedHeader({ alg: ID_TOKEN_ALG, kid: key.kid, typ: "JWT" }).setIssuer(args.issuer).setSubject(args.sub)diff --git a/plugins/auth/test/flow.test.ts b/plugins/auth/test/flow.test.tsindex 3c73354d2..33ace44c7 100644--- a/plugins/auth/test/flow.test.ts+++ b/plugins/auth/test/flow.test.ts@@ -1,6 +1,6 @@import test from "node:test";import assert from "node:assert/strict";-import { createHash } from "node:crypto";+import { createHash, createHmac } from "node:crypto";import { ClaimStoreUnavailableError } from "../../chassis/src/claims.ts";import { createLocalJWKSet, decodeProtectedHeader, jwtVerify, type JWK } from "jose";import {@@ -639,3 +639,113 @@ test("a live brandName accessor overrides the env default on pages and emails",await requestLink(h);assert.match(h.mailer.sent[0]!.subject, /straylight/);});++test("remembered browsers silently reauthorize with fresh PKCE and the original auth_time", async (t) => {+ const h = await startHarness();+ t.after(() => h.close());+ await requestLink(h);+ const verified = await openLink(h, linkFrom(h.mailer));+ assert.equal(verified.status, 302);+ const cookie = verified.headers.get("set-cookie")!;+ assert.match(cookie, /HttpOnly; Secure; SameSite=Lax; Path=\/idp; Max-Age=/);+ const authTime = Math.floor(h.now.ms / 1000);+ h.now.ms += 60000;+ const { verifier, challenge } = pkcePair();+ const response = await fetch(+ `${h.base}/authorize?${authorizeQuery({ code_challenge: challenge, nonce: "fresh-nonce", state: "fresh-state" })}`,+ { headers: { cookie: cookie.split(";")[0]! }, redirect: "manual" },+ );+ assert.equal(response.status, 302);+ assert.equal(h.mailer.sent.length, 1);+ const location = new URL(response.headers.get("location")!);+ assert.equal(location.searchParams.get("state"), "fresh-state");+ const exchanged = await exchange(h, location.searchParams.get("code")!, verifier);+ assert.equal(exchanged.status, 200);+ const body = (await exchanged.json()) as { id_token: string };+ const payload = JSON.parse(Buffer.from(body.id_token.split(".")[1]!, "base64url").toString());+ assert.equal(payload.nonce, "fresh-nonce");+ assert.equal(payload.auth_time, authTime);+ assert.equal((await exchange(h, location.searchParams.get("code")!, verifier)).status, 400);+});++test("fresh-auth requests, expired sessions, revocation and invalid requests cannot silently sign in", async (t) => {+ const h = await startHarness({ env: { AUTH_SESSION_IDLE_S: "60", AUTH_SESSION_ABSOLUTE_S: "180" } });+ t.after(() => h.close());+ await requestLink(h);+ const verified = await openLink(h, linkFrom(h.mailer));+ const cookie = verified.headers.get("set-cookie")!.split(";")[0]!;+ const authorize = (params: Record<string, string> = {}) =>+ fetch(`${h.base}/authorize?${authorizeQuery(params)}`, { headers: { cookie }, redirect: "manual" });+ assert.equal((await authorize({ prompt: "login" })).status, 200);+ assert.equal((await authorize({ max_age: "0" })).status, 200);+ assert.equal((await authorize({ max_age: "-1" })).status, 400);+ assert.equal((await authorize({ prompt: "none login" })).status, 400);+ assert.equal((await authorize({ redirect_uri: "https://evil.example" })).status, 400);+ h.now.ms += 2000;+ assert.equal((await authorize({ max_age: "1" })).status, 200);+ for (let i = 0; i < 3; i++) {+ h.now.ms += 50000;+ assert.equal((await authorize()).status, 302);+ }+ h.now.ms += 30000;+ assert.equal((await authorize()).status, 200);+ const silent = await authorize({ prompt: " none " });+ assert.equal(new URL(silent.headers.get("location")!).searchParams.get("error"), "login_required");+ h.now.ms -= 100000;+ h.remembered.clear();+ assert.equal((await authorize()).status, 200);+ assert.equal(h.mailer.sent.length, 1);+});++test("remembered-session backend failures fail closed", async (t) => {+ const h = await startHarness({+ sessions: {+ async create() {+ throw new Error("offline");+ },+ async use() {+ throw new Error("offline");+ },+ },+ });+ t.after(() => h.close());+ const response = await fetch(`${h.base}/authorize?${authorizeQuery()}`, {+ headers: {+ cookie: `qm_idp_session=${"a".repeat(43)}.${createHmac("sha256", h.cfg.tokenSecret)+ .update(`qm-auth.browser.v1\n${h.cfg.issuer}\n${h.cfg.clientId}\n${"a".repeat(43)}`)+ .digest("base64url")}`,+ },+ redirect: "manual",+ });+ assert.equal(response.status, 503);+ await requestLink(h);+ assert.equal((await openLink(h, linkFrom(h.mailer))).status, 503);+});++test("core source credentials cannot mint broker cookies", async (t) => {+ const h = await startHarness();+ t.after(() => h.close());+ const forged = await h.sessions.create("[email protected]", 3600, 7200);+ for (const value of [forged.token, `${forged.token}.${"x".repeat(43)}`]) {+ const response = await fetch(`${h.base}/authorize?${authorizeQuery()}`, {+ headers: { cookie: `qm_idp_session=${value}` },+ redirect: "manual",+ });+ assert.equal(response.status, 200);+ }+});++test("a remembered browser loses access when email eligibility is withdrawn", async (t) => {+ let allowed = true;+ const h = await startHarness({ env: { AUTH_ALLOWED_EMAILS: "" }, emailAllowed: async () => allowed });+ t.after(() => h.close());+ await requestLink(h);+ const verified = await openLink(h, linkFrom(h.mailer));+ const cookie = verified.headers.get("set-cookie")!.split(";")[0]!;+ allowed = false;+ const response = await fetch(`${h.base}/authorize?${authorizeQuery({ prompt: "none" })}`, {+ headers: { cookie },+ redirect: "manual",+ });+ assert.equal(new URL(response.headers.get("location")!).searchParams.get("error"), "login_required");+});diff --git a/plugins/auth/test/helpers.ts b/plugins/auth/test/helpers.tsindex 2e68f8ba1..28fc1a2b7 100644--- a/plugins/auth/test/helpers.ts+++ b/plugins/auth/test/helpers.ts@@ -1,3 +1,4 @@+import type { RememberedSessions, RememberedSession } from "../src/sessions.ts";import { createServer, type Server } from "node:http";import { createHash, generateKeyPairSync, randomBytes } from "node:crypto";import { emailConfigured, readConfig, type AuthConfig } from "../src/config.ts";@@ -88,6 +89,8 @@ export interface Harness {settle(): Promise<void>;close(): Promise<void>;now: { ms: number };+ sessions: RememberedSessions;+ remembered: Map<string, RememberedSession & { absoluteMs: number; idleS: number }>;}export async function startHarness(@@ -96,18 +99,41 @@ export async function startHarness(claims?: ClaimStore & { calls: string[][] };brandName?: () => string;emailAllowed?: (email: string) => Promise<boolean>;+ sessions?: RememberedSessions;} = {},): Promise<Harness> {const cfg = readConfig(testEnv(options.env));const claims = options.claims ?? memoryClaimStore();const mailer = captureMailer();const now = { ms: Date.now() };+ const remembered = new Map<string, RememberedSession & { absoluteMs: number; idleS: number }>();+ const sessions: RememberedSessions = options.sessions ?? {+ async create(email, idleS, absoluteS) {+ const token = randomBytes(32).toString("base64url");+ const session = {+ email,+ authTime: Math.floor(now.ms / 1000),+ expiresAtMs: now.ms + idleS * 1000,+ absoluteMs: now.ms + absoluteS * 1000,+ idleS,+ };+ remembered.set(token, session);+ return { ...session, token };+ },+ async use(token) {+ const session = remembered.get(token);+ if (!session || session.expiresAtMs <= now.ms || session.absoluteMs <= now.ms) return null;+ session.expiresAtMs = Math.min(session.absoluteMs, now.ms + session.idleS * 1000);+ return session;+ },+ };const pending: Array<Promise<void>> = [];const handle = createAuthHandler({cfg,signingKey: await loadSigningKey(cfg.signingJwk!),signer: new TokenSigner(cfg.tokenSecret, cfg.issuer),claims,+ sessions,mailer: emailConfigured(cfg) ? mailer : null,...(options.brandName ? { brandName: options.brandName } : {}),emailAllowed: options.emailAllowed ?? (async () => false),@@ -126,6 +152,8 @@ export async function startHarness(return {cfg,claims,+ sessions,+ remembered,mailer,now,base: `http://127.0.0.1:${port}`,diff --git a/plugins/portal/src/index.ts b/plugins/portal/src/index.tsindex 667bc4063..697826c34 100644--- a/plugins/portal/src/index.ts+++ b/plugins/portal/src/index.ts@@ -897,10 +897,35 @@ async function handle(req: IncomingMessage, res: ServerResponse): Promise<void>if (pathname === "/auth/admin-login") return adminLogin(req, res);if (pathname === "/auth/logout" && method === "POST") {if (!sameOriginRequest(req)) return json(res, 403, { error: "forbidden" });+ if (AUTH_BROKER_UPSTREAM && url.searchParams.get("everywhere") === "1") {+ const session = currentSession(req);+ if (!session || session.anon) return json(res, 401, { error: "sign in" });+ if (!PORTAL_IDENTITY_SECRET) return json(res, 503, { error: "not_configured" });+ const path = withSourceAuthNonce("/v1/auth/broker/sessions/revoke", CORE_SIGNING_SECRET);+ const body = JSON.stringify({ email: session.sub });+ try {+ const response = await fetch(`${CORE}${path}`, {+ method: "POST",+ headers: {+ ...signedHeaders(CORE_SIGNING_SECRET, "POST", path, body),+ [PORTAL_IDENTITY_HEADER]: mintPortalIdentity(+ { p: session.sub, exp: Date.now() + 60_000 },+ PORTAL_IDENTITY_SECRET,+ ),+ },+ body,+ signal: AbortSignal.timeout(4_000),+ });+ if (!response.ok) return json(res, 503, { error: "revocation_failed" });+ } catch {+ return json(res, 503, { error: "revocation_failed" });+ }+ }setSession(res, [clearCookie("portal_session", "/", SECURE_COOKIES, COOKIE_DOMAIN),...(COOKIE_DOMAIN ? [clearCookie("portal_session", "/", SECURE_COOKIES)] : []),clearCookie("portal_oidc_tmp", "/auth", SECURE_COOKIES),+ ...(AUTH_BROKER_UPSTREAM ? [clearCookie("qm_idp_session", AUTH_BROKER_PREFIX, true)] : []),...(LOCAL_AUTH_BYPASS && isLoopbackAddress(req.socket.remoteAddress)? [setCookie(LOCAL_LOGOUT_COOKIE, "1", { path: "/", maxAge: SESSION_TTL_S, secure: SECURE_COOKIES })]: []),@@ -919,9 +944,16 @@ async function handle(req: IncomingMessage, res: ServerResponse): Promise<void>return proxyToUpstream(req,res,- { baseUrl: AUTH_BROKER_UPSTREAM, path: brokerPath, search: url.search },+ { baseUrl: AUTH_BROKER_UPSTREAM, path: brokerPath, search: url.search, forwardCookies: true },FORWARD_BROKER_HEADERS,- { "x-qm-client-ip": clientIpOf(req) },+ {+ "x-qm-client-ip": clientIpOf(req),+ cookie: (req.headers.cookie ?? "")+ .split(";")+ .map((part) => part.trim())+ .filter((part) => /^qm_idp_session=[A-Za-z0-9_-]{43}\.[A-Za-z0-9_-]{43}$/.test(part))+ .join("; "),+ },);}@@ -1234,6 +1266,7 @@ function authLogin(req: IncomingMessage, res: ServerResponse, url: URL): void {setSession(res, [...sessionCookieSet(seal(localSession, sessionKey)),clearCookie("portal_oidc_tmp", "/auth", SECURE_COOKIES),+ ...(AUTH_BROKER_UPSTREAM ? [clearCookie("qm_idp_session", AUTH_BROKER_PREFIX, true)] : []),clearCookie(LOCAL_LOGOUT_COOKIE, "/", SECURE_COOKIES),]);res.writeHead(302, { location: returnTo, "cache-control": "no-store" });diff --git a/plugins/portal/src/proxy.ts b/plugins/portal/src/proxy.tsindex 1d53dbed6..c7edf9e21 100644--- a/plugins/portal/src/proxy.ts+++ b/plugins/portal/src/proxy.ts@@ -55,6 +55,7 @@ function relay(path: string;headers: Record<string, string>;honorFramePolicy?: boolean;+ forwardCookies?: boolean;},): void {const up = httpRequest(@@ -70,7 +71,8 @@ function relay(const out: Record<string, string | string[]> = {};for (const [k, v] of Object.entries(upRes.headers)) {if (v === undefined) continue;- if (DROP_RESPONSE_HEADERS.has(k.toLowerCase())) continue;+ if (DROP_RESPONSE_HEADERS.has(k.toLowerCase()) && !(k.toLowerCase() === "set-cookie" && target.forwardCookies))+ continue;out[k] = v;}if (target.honorFramePolicy && declaresFrameAncestors(out)) res.removeHeader("x-frame-options");@@ -204,6 +206,7 @@ export function proxyToDeployment(req: IncomingMessage, res: ServerResponse, t:}export interface UpstreamTarget {+ forwardCookies?: boolean;baseUrl: string;path: string;search: string;@@ -228,6 +231,7 @@ export function proxyToUpstream(hostname: upstream.hostname,port: requestPort(upstream),path: `${t.path}${t.search}`,+ ...(t.forwardCookies ? { forwardCookies: true } : {}),headers,});}diff --git a/plugins/portal/test/broker-proxy.test.ts b/plugins/portal/test/broker-proxy.test.tsindex 495b934a4..c2c35028a 100644--- a/plugins/portal/test/broker-proxy.test.ts+++ b/plugins/portal/test/broker-proxy.test.ts@@ -1,3 +1,4 @@+import { deriveKey, seal } from "../src/session.ts";import test from "node:test";import assert from "node:assert/strict";import { createServer, type IncomingMessage } from "node:http";@@ -15,6 +16,10 @@ const broker = createServer((req: IncomingMessage, res) => {body: Buffer.concat(chunks).toString("utf8"),});if (req.url?.startsWith("/verify")) {+ res.setHeader("set-cookie", [+ "qm_idp_session=abc; Path=/idp; HttpOnly; Secure; SameSite=Lax",+ "extra=1; Path=/idp",+ ]);res.writeHead(302, { location: "https://portal.test/auth/callback?code=c&state=s" });return void res.end();}@@ -35,6 +40,7 @@ const surfaceUrl = `http://127.0.0.1:${(surface.address() as AddressInfo).port}`const PUBLIC = "http://portal.test";process.env.PORTAL_PUBLIC_URL = PUBLIC;process.env.PORTAL_SESSION_SECRET = "broker-proxy-test-portal-secret";+process.env.PORTAL_IDENTITY_SECRET = "broker-proxy-test-identity-secret";process.env.CORE_SIGNING_SECRET = "broker-proxy-test-core-secret";process.env.CORE_ORG_ID = "acme";process.env.WEB_UI_UPSTREAM = surfaceUrl;@@ -66,6 +72,8 @@ test("the broker's sign-in pages are reachable without a session", async () => {test("the verify redirect is relayed back to the browser", async () => {const redirect = await fetch(`${base}/idp/verify?token=abc`, { redirect: "manual" });assert.equal(redirect.status, 302);+ assert.equal(redirect.headers.getSetCookie().length, 2);+ assert.match(redirect.headers.getSetCookie()[0]!, /qm_idp_session=abc/);assert.equal(redirect.headers.get("location"), "https://portal.test/auth/callback?code=c&state=s");});@@ -207,3 +215,40 @@ test("isPrivateNetworkUrl admits only unroutable hosts", () => {assert.equal(isPrivateNetworkUrl(url), false, url);}});++test("only broker cookies reach the broker", async () => {+ const token = `${"a".repeat(43)}.${"b".repeat(43)}`;+ await fetch(`${base}/idp/authorize`, {+ headers: { cookie: `portal_session=secret; qm_idp_session=${token}; unrelated=secret` },+ });+ assert.equal(seen.at(-1)!.headers.cookie, `qm_idp_session=${token}`);+});++test("logout clears the remembered cookie and everywhere requires an authenticated caller", async () => {+ const response = await fetch(`${base}/auth/logout`, { method: "POST", headers: { origin: PUBLIC } });+ assert.equal(response.status, 200);+ assert.ok(+ response.headers+ .getSetCookie()+ .some(+ (value) => value.startsWith("qm_idp_session=") && value.includes("Path=/idp") && value.includes("Max-Age=0"),+ ),+ );+ const unsigned = await fetch(`${base}/auth/logout?everywhere=1`, { method: "POST", headers: { origin: PUBLIC } });+ assert.equal(unsigned.status, 401);+ const now = Date.now();+ const cookie = seal(+ { k: "session", sub: "[email protected]", org: "acme", iat: now, exp: now + 60000 },+ deriveKey(process.env.PORTAL_SESSION_SECRET!, "portal.session.v1"),+ );+ const signed = await fetch(`${base}/auth/logout?everywhere=1`, {+ method: "POST",+ headers: { origin: PUBLIC, cookie: `portal_session=${cookie}` },+ });+ assert.equal(signed.status, 200);+ const crossOrigin = await fetch(`${base}/auth/logout?everywhere=1`, {+ method: "POST",+ headers: { origin: "https://evil.test", cookie: `portal_session=${cookie}` },+ });+ assert.equal(crossOrigin.status, 403);+});diff --git a/src/api/deps.ts b/src/api/deps.tsindex 8e38d4f82..cef99eb3f 100644--- a/src/api/deps.ts+++ b/src/api/deps.ts@@ -1,3 +1,4 @@+import type { BrokerSessionStore } from "../auth/broker-sessions.ts";import type { ModelVerifier } from "../model/model-verification.ts";import type { DurableByteStore } from "../files/durable-byte-store.ts";import type { SessionShareStore } from "../sessions/session-share.ts";@@ -74,6 +75,7 @@ export interface ServerDeps {requireSignedPortalIdentity?: boolean;control: ControlService;replayDedupe?: ReplayDedupe;+ brokerSessions?: BrokerSessionStore;connectorTokens?: ConnectorTokenStore;slackInstallation?: SlackInstallationStore;slackInstallationFetch?: typeof fetch;diff --git a/src/api/routes/auth-broker.ts b/src/api/routes/auth-broker.tsindex d0d68ae9d..6e15cc988 100644--- a/src/api/routes/auth-broker.ts+++ b/src/api/routes/auth-broker.ts@@ -1,6 +1,6 @@import { sendJson } from "../http.ts";import { externalMemberActive } from "../../identity/external-members.ts";-import { isObj } from "./shared.ts";+import { isObj, authorizeAdmin, orgScope, audit } from "./shared.ts";import { type ApiCtx, type Route } from "./route.ts";const NAMESPACE = "authbroker:";@@ -60,7 +60,48 @@ async function emailAllowed(ctx: ApiCtx): Promise<void> {return sendJson(res, 200, { allowed, ...(allowed ? { expiresAt: member.expiresAt } : {}) });}+async function brokerSession(ctx: ApiCtx): Promise<void> {+ const { res, deps, body } = ctx;+ if (!deps.brokerSessions) return sendJson(res, 503, { error: "not_configured" });+ const b = isObj(body) ? body : {};+ if (ctx.pathname.endsWith("/use")) {+ if (typeof b.token !== "string" || !/^[A-Za-z0-9_-]{43}$/.test(b.token))+ return sendJson(res, 400, { error: "invalid_token" });+ return sendJson(res, 200, { session: await deps.brokerSessions.use(b.token) });+ }+ if (typeof b.email !== "string" || b.email.length > 254 || !/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(b.email))+ return sendJson(res, 400, { error: "invalid_email" });+ const email = b.email.trim().toLowerCase();+ if (ctx.pathname.endsWith("/revoke")) {+ if (ctx.actor?.p.toLowerCase() !== email && !(await authorizeAdmin(ctx, orgScope()))) return;+ await deps.brokerSessions.revoke(email);+ audit(deps, {+ principalId: ctx.actor?.p ?? "admin",+ action: "auth.broker.revoke",+ resource: email,+ scopeLabel: orgScope(),+ });+ return sendJson(res, 200, { ok: true });+ }+ const idleS = b.idleS;+ const absoluteS = b.absoluteS;+ if (+ typeof idleS !== "number" ||+ typeof absoluteS !== "number" ||+ !Number.isInteger(idleS) ||+ !Number.isInteger(absoluteS) ||+ idleS < 1 ||+ absoluteS < idleS ||+ absoluteS > 90 * 86400+ )+ return sendJson(res, 400, { error: "invalid_lifetime" });+ return sendJson(res, 200, await deps.brokerSessions.create(email, idleS, absoluteS));+}+export const authBrokerRoutes: ReadonlyArray<Route<ApiCtx>> = [+ { method: "POST", path: "/v1/auth/broker/sessions", auth: "source", handle: brokerSession },+ { method: "POST", path: "/v1/auth/broker/sessions/use", auth: "source", handle: brokerSession },+ { method: "POST", path: "/v1/auth/broker/sessions/revoke", auth: "source", handle: brokerSession },{ method: "POST", path: "/v1/auth/broker/claim", auth: "source", handle: claimBrokerNonce },{ method: "GET", path: "/v1/auth/broker/email-allowed", auth: "source", handle: emailAllowed },];diff --git a/src/api/user-scoped-routes.ts b/src/api/user-scoped-routes.tsindex bb257252e..f1294bc23 100644--- a/src/api/user-scoped-routes.ts+++ b/src/api/user-scoped-routes.ts@@ -9,6 +9,7 @@ function pat(method: string, template: string, field?: Field): Rule {}const USER_SCOPED: Rule[] = [+ pat("POST", "/v1/auth/broker/sessions/revoke"),pat("POST", "/v1/loops", { in: "query", name: "principalId" }),pat("GET", "/v1/loops", { in: "query", name: "principalId" }),pat("GET", "/v1/loops/:id", { in: "query", name: "principalId" }),@@ -122,6 +123,8 @@ const SYSTEM: Rule[] = [pat("POST", "/v1/blobs"),pat("POST", "/v1/egress-audit"),pat("POST", "/v1/auth/broker/claim"),+ pat("POST", "/v1/auth/broker/sessions"),+ pat("POST", "/v1/auth/broker/sessions/use"),pat("PUT", "/v1/deployment-layer"),pat("POST", "/v1/session-cap"),pat("POST", "/v1/keychain/drops/:id"),@@ -151,7 +154,7 @@ export function userScopedField(method: string, pathname: string): Field | undefexport function isUnclassifiedWrite(method: string, pathname: string): boolean {if (!WRITE.has(method)) return false;if (pathname.startsWith("/v1/admin/")) return false;- if (userScopedField(method, pathname)) return false;+ if (isUserScoped(method, pathname)) return false;return !SYSTEM.some((r) => r.method === method && r.re.test(pathname));}diff --git a/src/auth/broker-sessions.ts b/src/auth/broker-sessions.tsnew file mode 100644index 000000000..6e2e15e1a--- /dev/null+++ b/src/auth/broker-sessions.ts@@ -0,0 +1,63 @@+import { createHash, randomBytes } from "node:crypto";+import { createPgPool } from "../persistence/pg-pool.ts";++interface BrokerSession {+ email: string;+ authTime: number;+ expiresAtMs: number;+}++export interface BrokerSessionStore {+ create(email: string, idleS: number, absoluteS: number): Promise<BrokerSession & { token: string }>;+ use(token: string): Promise<BrokerSession | null>;+ revoke(email: string): Promise<void>;+}++const hash = (token: string): string => createHash("sha256").update(token).digest("hex");+const SCHEMA = [+ `CREATE TABLE IF NOT EXISTS auth_broker_sessions (+ token_hash TEXT PRIMARY KEY,+ email TEXT NOT NULL,+ authenticated_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ expires_at TIMESTAMPTZ NOT NULL,+ absolute_expires_at TIMESTAMPTZ NOT NULL,+ idle_seconds INTEGER NOT NULL+ )`,+ `CREATE INDEX IF NOT EXISTS auth_broker_sessions_email ON auth_broker_sessions (email)`,+ `CREATE INDEX IF NOT EXISTS auth_broker_sessions_expiry ON auth_broker_sessions (expires_at)`,+];++export function createPostgresBrokerSessions(connectionString: string): BrokerSessionStore {+ const pg = createPgPool(connectionString, "auth/broker-sessions/0001", SCHEMA);+ const session = (row: Record<string, unknown>): BrokerSession => ({+ email: String(row.email),+ authTime: Math.floor(new Date(String(row.authenticated_at)).getTime() / 1000),+ expiresAtMs: new Date(String(row.expires_at)).getTime(),+ });+ return {+ async create(email, idleS, absoluteS) {+ const token = randomBytes(32).toString("base64url");+ await pg.query("DELETE FROM auth_broker_sessions WHERE expires_at <= now()");+ const result = await pg.query(+ `INSERT INTO auth_broker_sessions (token_hash, email, expires_at, absolute_expires_at, idle_seconds)+ VALUES ($1, $2, now() + $3 * interval '1 second', now() + $4 * interval '1 second', $3)+ RETURNING email, authenticated_at, expires_at`,+ [hash(token), email, Math.min(idleS, absoluteS), absoluteS],+ );+ return { ...session(result.rows[0]!), token };+ },+ async use(token) {+ const result = await pg.query(+ `UPDATE auth_broker_sessions+ SET expires_at = LEAST(absolute_expires_at, now() + idle_seconds * interval '1 second')+ WHERE token_hash = $1 AND expires_at > now() AND absolute_expires_at > now()+ RETURNING email, authenticated_at, expires_at`,+ [hash(token)],+ );+ return result.rows[0] ? session(result.rows[0]) : null;+ },+ async revoke(email) {+ await pg.query("DELETE FROM auth_broker_sessions WHERE email = $1", [email]);+ },+ };+}diff --git a/src/wiring.ts b/src/wiring.tsindex 0a0608673..755396f7b 100644--- a/src/wiring.ts+++ b/src/wiring.ts@@ -1,3 +1,4 @@+import { createPostgresBrokerSessions, type BrokerSessionStore } from "./auth/broker-sessions.ts";import { createModelVerifier, type ModelVerifier } from "./model/model-verification.ts";import type { probeModel } from "./harness/pi-harness.ts";import { createAwsRoleBroker, type AwsRoleBroker } from "./auth/aws-role-broker.ts";@@ -447,6 +448,7 @@ export interface BuiltApp {deviceFlowCutover: DeviceFlowCutoverStore;featureFlags: FeatureFlagStore;replayDedupe?: ReplayDedupe;+ brokerSessions?: BrokerSessionStore;directory: DirectoryStore;projects: ProjectStore;environments: EnvironmentStore;@@ -1164,6 +1166,7 @@ export function buildApp(processes = config.databaseUrl ? createPostgresProcessRegistry(config.databaseUrl) : createMemoryProcessRegistry();}+ const brokerSessions = config.databaseUrl ? createPostgresBrokerSessions(config.databaseUrl) : undefined;const replayDedupe = config.databaseUrl ? createPostgresReplayDedupe(config.databaseUrl) : createMemoryReplayDedupe();const metrics = config.databaseUrl ? createPostgresMetricsSink(config.databaseUrl) : createMetricsSink();const credentialUsage = config.databaseUrl@@ -2019,6 +2022,7 @@ export function buildApp(deviceFlowCutover,featureFlags,...(replayDedupe ? { replayDedupe } : {}),+ ...(brokerSessions ? { brokerSessions } : {}),directory,projects,environments,@@ -2060,6 +2064,7 @@ export function serverDeps(...(config.portalIdentitySecret ? { portalIdentitySecret: config.portalIdentitySecret } : {}),...(config.requireSignedPortalIdentity ? { requireSignedPortalIdentity: true } : {}),...(built.replayDedupe ? { replayDedupe: built.replayDedupe } : {}),+ ...(built.brokerSessions ? { brokerSessions: built.brokerSessions } : {}),config: built.config,...(built.screenSecurity ? { screenSecurity: built.screenSecurity } : {}),...(configuredModel ? { baseModelDefault: configuredModel } : {}),diff --git a/test/auth-broker-claim.test.ts b/test/auth-broker-claim.test.tsindex ee0ff5f99..d5caaceb0 100644--- a/test/auth-broker-claim.test.ts+++ b/test/auth-broker-claim.test.ts@@ -1,3 +1,5 @@+import type { BrokerSessionStore } from "../src/auth/broker-sessions.ts";+import { mintPortalIdentity } from "../src/auth/portal-identity.ts";import "./support/auto-fake-sprites.ts";import { test } from "node:test";@@ -27,7 +29,10 @@ function durableStub(): ReplayDedupe {};}-function start(replayDedupe: ReplayDedupe = durableStub()): {+function start(+ replayDedupe: ReplayDedupe = durableStub(),+ brokerSessions?: BrokerSessionStore,+): {base: string;dedupe: ReplayDedupe;close: () => Promise<void>;@@ -35,7 +40,14 @@ function start(replayDedupe: ReplayDedupe = durableStub()): {const built: BuiltApp = buildApp(testConfig({ dataDir: mkdtempSync(join(tmpdir(), "auth-broker-claim-")), orgId: "acme" }),);- const server = createServer(built.app, { signingSecret: SECRET, replayDedupe });+ const server = createServer(built.app, {+ signingSecret: SECRET,+ replayDedupe,+ brokerSessions,+ requireSignedPortalIdentity: true,+ portalIdentitySecret: SECRET + "identity",+ capabilitySecret: SECRET + "capability",+ });server.listen(0);return {base: `http://localhost:${(server.address() as AddressInfo).port}`,@@ -49,14 +61,15 @@ async function claim(body: unknown,sign = true,): Promise<{ status: number; json: { claimed?: unknown; error?: unknown } }> {+ const path = `${CLAIM_PATH}?nonce=${crypto.randomUUID()}`;const raw = JSON.stringify(body);const ts = Math.floor(Date.now() / 1000);const headers: Record<string, string> = { "content-type": "application/json" };if (sign) {headers["x-timestamp"] = String(ts);- headers["x-signature"] = signRequest(SECRET, ts, `POST\n${CLAIM_PATH}\n${raw}`);+ headers["x-signature"] = signRequest(SECRET, ts, `POST\n${path}\n${raw}`);}- const res = await fetch(`${base}${CLAIM_PATH}`, { method: "POST", headers, body: raw });+ const res = await fetch(`${base}${path}`, { method: "POST", headers, body: raw });return { status: res.status, json: (await res.json()) as { claimed?: unknown; error?: unknown } };}@@ -131,3 +144,49 @@ test("the claim route validates its input", async (t) => {assert.equal(response.json.error, "bad_request");}});++test("broker sessions cross the production identity gate, but revocation requires the owner", async (t) => {+ const revoked: string[] = [];+ const token = "a".repeat(43);+ const sessions: BrokerSessionStore = {+ async create(email) {+ return { token, email, authTime: 1, expiresAtMs: Date.now() + 60000 };+ },+ async use(value) {+ return value === token ? { email: "[email protected]", authTime: 1, expiresAtMs: Date.now() + 60000 } : null;+ },+ async revoke(email) {+ revoked.push(email);+ },+ };+ const srv = start(durableStub(), sessions);+ t.after(() => srv.close());+ const post = async (suffix: string, data: unknown, actor?: string, signed = true): Promise<Response> => {+ const path = `/v1/auth/broker/sessions${suffix}?nonce=${crypto.randomUUID()}`;+ const body = JSON.stringify(data);+ const ts = Math.floor(Date.now() / 1000);+ return fetch(`${srv.base}${path}`, {+ method: "POST",+ body,+ headers: {+ "content-type": "application/json",+ ...(signed+ ? { "x-timestamp": String(ts), "x-signature": signRequest(SECRET, ts, `POST\n${path}\n${body}`) }+ : {}),+ ...(actor+ ? {+ "x-portal-identity": await mintPortalIdentity({ p: actor, exp: Date.now() + 60000 }, SECRET + "identity"),+ }+ : {}),+ },+ });+ };+ assert.equal((await post("", { email: "[email protected]", idleS: 30, absoluteS: 90 })).status, 200);+ assert.equal((await post("/use", { token })).status, 200);+ assert.equal((await post("", { email: "[email protected]", idleS: 30, absoluteS: 90 }, undefined, false)).status, 401);+ assert.equal((await post("", { email: "[email protected]", idleS: 91, absoluteS: 90 })).status, 400);+ assert.equal((await post("/revoke", { email: "[email protected]" })).status, 401);+ assert.notEqual((await post("/revoke", { email: "[email protected]" }, "[email protected]")).status, 200);+ assert.equal((await post("/revoke", { email: "[email protected]" }, "[email protected]")).status, 200);+ assert.deepEqual(revoked, ["[email protected]"]);+});diff --git a/test/postgres-broker-sessions.test.ts b/test/postgres-broker-sessions.test.tsnew file mode 100644index 000000000..a7469968e--- /dev/null+++ b/test/postgres-broker-sessions.test.ts@@ -0,0 +1,55 @@+import { test } from "node:test";+import assert from "node:assert/strict";+import { createHash, randomUUID } from "node:crypto";+import pg from "pg";+import { createPostgresBrokerSessions } from "../src/auth/broker-sessions.ts";++const url = process.env.DATABASE_URL;++test(+ "broker sessions persist across instances, expire strictly, and revoke every remembered browser",+ { skip: !url },+ async () => {+ const a = createPostgresBrokerSessions(url!);+ const b = createPostgresBrokerSessions(url!);+ const pool = new pg.Pool({ connectionString: url });+ const email = `${randomUUID()}@example.com`;+ try {+ const first = await a.create(email, 30 * 86400, 90 * 86400);+ const second = await b.create(email, 30 * 86400, 90 * 86400);+ assert.equal((await b.use(first.token))?.authTime, first.authTime);+ const hash = createHash("sha256").update(first.token).digest("hex");+ const rows = await pool.query("SELECT token_hash FROM auth_broker_sessions WHERE email = $1", [email]);+ assert.equal(rows.rows.length, 2);+ assert.ok(rows.rows.some((row) => row.token_hash === hash));+ assert.ok(rows.rows.every((row) => row.token_hash !== first.token));+ await pool.query("UPDATE auth_broker_sessions SET expires_at = now() + interval '1 day' WHERE token_hash = $1", [+ hash,+ ]);+ assert.ok((await b.use(first.token))!.expiresAtMs > Date.now() + 29 * 86400000);+ await pool.query(+ "UPDATE auth_broker_sessions SET absolute_expires_at = now() + interval '1 hour' WHERE token_hash = $1",+ [hash],+ );+ const capped = await b.use(first.token);+ assert.ok(capped!.expiresAtMs <= Date.now() + 3600000);+ await pool.query(+ "UPDATE auth_broker_sessions SET absolute_expires_at = now() - interval '1 second' WHERE token_hash = $1",+ [hash],+ );+ assert.equal(await a.use(first.token), null);+ await pool.query("UPDATE auth_broker_sessions SET expires_at = now() - interval '1 second' WHERE email = $1", [+ email,+ ]);+ assert.equal(await a.use(second.token), null);+ const third = await a.create(email, 30, 90);+ const fourth = await b.create(email, 30, 90);+ await a.revoke(email);+ assert.equal(await a.use(third.token), null);+ assert.equal(await b.use(fourth.token), null);+ } finally {+ await a.revoke(email);+ await pool.end();+ }+ },+);