AI-powered virtual executive team — a single coherent executive persona backed by 8 specialist agents (FastAPI + Next.js).
fix: harden the roster loader and freeze the shared env decision
Rufus1730130e05b2
diff --git a/packages/ui/scripts/allowlist.test.mjs b/packages/ui/scripts/allowlist.test.mjsindex e6a9e393..1f215b3d 100644--- a/packages/ui/scripts/allowlist.test.mjs+++ b/packages/ui/scripts/allowlist.test.mjs@@ -218,6 +218,7 @@ test("the loader hits /auth/allowed-emails with the shared secret and no cachingbaseUrl: "http://api:8000",sharedSecret: "s3cret",ttlMs: 1000,+ timeoutMs: 1000,fetchImpl,});assert.deepEqual([...(await load())], ["[email protected]"]);@@ -232,6 +233,7 @@ test("the loader omits x-api-key when no shared secret is configured", async ()baseUrl: "http://api:8000",sharedSecret: "",ttlMs: 1000,+ timeoutMs: 1000,fetchImpl,});await load();@@ -245,6 +247,7 @@ test("a successful roster is cached for its TTL and refetched after it expires",baseUrl: "http://api:8000",sharedSecret: "",ttlMs: 1000,+ timeoutMs: 1000,fetchImpl,now: () => clock,});@@ -266,6 +269,7 @@ test("an HTTP error yields null, warns, and is not cached", async () => {baseUrl: "http://api:8000",sharedSecret: "",ttlMs: 60_000,+ timeoutMs: 1000,fetchImpl,now: () => 0,onWarn: (m) => warnings.push(m),@@ -282,6 +286,7 @@ test("a rejecting fetch yields null instead of throwing into NextAuth", async ()baseUrl: "http://api:8000",sharedSecret: "",ttlMs: 1000,+ timeoutMs: 1000,fetchImpl: async () => {throw new Error("ECONNREFUSED");},@@ -295,6 +300,7 @@ test("a non-array body yields null rather than an empty roster", async () => {baseUrl: "http://api:8000",sharedSecret: "",ttlMs: 1000,+ timeoutMs: 1000,fetchImpl: async () => ({ ok: true, status: 200, json: async () => ({ detail: "nope" }) }),});assert.equal(await load(), null);@@ -305,6 +311,7 @@ test("a row with a null email is skipped without nulling the whole roster", asynbaseUrl: "http://api:8000",sharedSecret: "",ttlMs: 1000,+ timeoutMs: 1000,fetchImpl: async () =>okResponse([{ email: null, person_id: 1 }, { email: "[email protected]", person_id: 2 }, {}]),});@@ -316,6 +323,7 @@ test("a body that fails to parse as JSON yields null", async () => {baseUrl: "http://api:8000",sharedSecret: "",ttlMs: 1000,+ timeoutMs: 1000,fetchImpl: async () => ({ok: true,status: 200,@@ -340,6 +348,7 @@ test("at most one fetch is ever in flight, across cache misses and expiries", asbaseUrl: "http://api:8000",sharedSecret: "",ttlMs: 1000,+ timeoutMs: 1000,now: () => clock,fetchImpl: async () => {open += 1;@@ -362,12 +371,16 @@ test("at most one fetch is ever in flight, across cache misses and expiries", asassert.deepEqual([...(await load())], ["[email protected]"], "the newest roster is what is cached");});+// Companion to the TTL-straddling test above: this is the simple baseline+// (one window, no expiry), that one is the TTL-boundary case. Neither+// subsumes the other — keep both.test("concurrent misses share one in-flight fetch", async () => {let fetches = 0;const load = createRosterLoader({baseUrl: "http://api:8000",sharedSecret: "",ttlMs: 1000,+ timeoutMs: 1000,now: () => 0,fetchImpl: async () => {fetches += 1;@@ -386,6 +399,7 @@ test("a failed in-flight fetch is not retained, so the next caller retries", asybaseUrl: "http://api:8000",sharedSecret: "",ttlMs: 60_000,+ timeoutMs: 1000,now: () => 0,fetchImpl: async () => {n += 1;@@ -397,3 +411,81 @@ test("a failed in-flight fetch is not retained, so the next caller retries", asyassert.deepEqual([...(await load())], ["[email protected]"]);assert.equal(n, 2);});++test("ENV_HIT cannot be mutated by a caller into a lockout", () => {+ // Both decision functions return one shared object for an env hit, so an+ // accidental write would poison every later env hit in the process — the+ // #132 lockout class. Frozen, the write throws under ESM strict mode.+ const env = set("[email protected]");+ const first = decideAllowed("[email protected]", env, NONE);+ assert.equal(Object.isFrozen(first), true);+ assert.throws(() => {+ first.allowed = false;+ }, TypeError);+ assert.equal(decideAllowed("[email protected]", env, NONE).allowed, true);+});++test("a hung fetch is abandoned at the timeout instead of pinning joiners", async () => {+ // Regression: callers share one in-flight request, so without a timeout a+ // hung backend blocked every joiner until undici's ~300s default and kept+ // denying roster-only sign-ins long after recovery.+ //+ // The signal is captured and asserted on in TEST scope, not inside the+ // mock: anything thrown inside `fetchImpl` is swallowed by the loader's+ // catch and degrades to `null`, so an in-mock assertion would let the+ // test pass even with no timeout wired up at all.+ let attempts = 0;+ let signal;+ const load = createRosterLoader({+ baseUrl: "http://api:8000",+ sharedSecret: "",+ ttlMs: 60_000,+ timeoutMs: 20,+ now: () => 0,+ fetchImpl: async (_url, init) => {+ attempts += 1;+ if (attempts === 1) {+ signal = init.signal;+ // Never resolves on its own — only the abort ends it. The ref'd+ // timer is required: AbortSignal.timeout's own timer is UNREF'd, so+ // without something holding the loop open the test would drain+ // before the abort fires.+ return new Promise((_resolve, reject) => {+ const keepAlive = setTimeout(() => reject(new Error("never aborted")), 5000);+ init.signal.addEventListener("abort", () => {+ clearTimeout(keepAlive);+ reject(init.signal.reason);+ });+ });+ }+ return { ok: true, status: 200, json: async () => [{ email: "[email protected]", person_id: 1 }] };+ },+ });++ assert.equal(await load(), null, "the hung attempt degrades to unknown");+ assert.ok(signal instanceof AbortSignal, "the loader must pass an abort signal");+ assert.equal(signal.aborted, true, "and it must have fired");+ assert.equal(signal.reason?.name, "TimeoutError", "aborted by the timeout, not something else");+ // The failure was not cached, so the recovered backend is reachable at once.+ assert.deepEqual([...(await load())], ["[email protected]"]);+ assert.equal(attempts, 2);+});++test("a backwards clock step does not make an expired roster look fresh", async () => {+ let clock = 10_000;+ let n = 0;+ const load = createRosterLoader({+ baseUrl: "http://api:8000",+ sharedSecret: "",+ ttlMs: 1000,+ timeoutMs: 1000,+ now: () => clock,+ fetchImpl: async () => {+ n += 1;+ return { ok: true, status: 200, json: async () => [{ email: `p${n}@corp.com`, person_id: n }] };+ },+ });+ assert.deepEqual([...(await load())], ["[email protected]"]);+ clock = 0; // NTP steps the clock backwards past the entry's fetchedAt+ assert.deepEqual([...(await load())], ["[email protected]"], "refetched rather than served stale");+});diff --git a/packages/ui/src/auth.ts b/packages/ui/src/auth.tsindex a9c1d3a6..af980e21 100644--- a/packages/ui/src/auth.ts+++ b/packages/ui/src/auth.ts@@ -23,12 +23,18 @@ const BACKEND_SHARED_SECRET = process.env.BACKEND_SHARED_SECRET ?? "";// "5 minutes" in docs/auth.md; keep the two in step.const ROSTER_TTL_MS = 5 * 60 * 1000;+// Give up on a roster fetch well before undici's ~300s default. Concurrent+// callers share one in-flight request, so an unbounded hang would pin them all+// and keep denying new roster-only sign-ins after the backend recovered.+const ROSTER_FETCH_TIMEOUT_MS = 3000;+// Both NextAuth callbacks are server-side (Node runtime), so the loader's// cache is per-server-instance.const loadRoster = createRosterLoader({baseUrl: BACKEND_BASE,sharedSecret: BACKEND_SHARED_SECRET,ttlMs: ROSTER_TTL_MS,+ timeoutMs: ROSTER_FETCH_TIMEOUT_MS,// Wrapped rather than passed bare: `fetch` must keep its own receiver.fetchImpl: (input, init) => fetch(input, init),onWarn: (message) => console.warn(message),@@ -148,21 +154,30 @@ export const { handlers, auth, signIn, signOut } = NextAuth({if (!auth?.user?.email) return false;const email = auth.user.email.toLowerCase();const decision = await checkEmailAllowed(email);- if (decideSessionAction(decision) !== "revoke") return true;- // Fire-and-forget audit so a mid-session eviction leaves a- // trail even if the user never re-attempts sign-in.- auditAuth(- "auth_logout",- `Session revoked: ${email} (${describeDenial(decision.source)})`,- email,- {- revoked: true,- reason: "not_in_allowlist",- source: decision.source,- roster_unavailable: false,- },- );- return false;+ // Exhaustive on purpose: a `!== "revoke"` test would admit any future+ // SessionAction, i.e. fail open. This way adding one is a build error.+ switch (decideSessionAction(decision)) {+ case "allow":+ case "allow_roster_unknown":+ return true;+ case "revoke":+ // Fire-and-forget audit so a mid-session eviction leaves a+ // trail even if the user never re-attempts sign-in.+ auditAuth(+ "auth_logout",+ `Session revoked: ${email} (${describeDenial(decision.source)})`,+ email,+ {+ revoked: true,+ reason: "not_in_allowlist",+ source: decision.source,+ // Always false on this branch; read off the decision anyway so+ // it cannot silently desync from decideSessionAction.+ roster_unavailable: decision.rosterUnknown,+ },+ );+ return false;+ }},},events: {diff --git a/packages/ui/src/lib/allowlist.ts b/packages/ui/src/lib/allowlist.tsindex cf7f1a8b..4cfac389 100644--- a/packages/ui/src/lib/allowlist.ts+++ b/packages/ui/src/lib/allowlist.ts@@ -11,13 +11,17 @@//// No imports — not React, not next-auth — so `npm test` can exercise this// directly under `node --experimental-strip-types` (see-// scripts/allowlist.test.mjs). That is also why the roster loader lives here-// rather than in its own module: Node's ESM loader needs an explicit `.ts` on-// a relative import, which TypeScript rejects without-// `allowImportingTsExtensions`, so a second module could only share-// `normalizeEmail` by duplicating it. The decision logic below is pure; the-// loader at the bottom is the one piece with a socket, a clock and mutable-// state. auth.ts keeps only the wiring and the audit calls.+// scripts/allowlist.test.mjs).+//+// The roster loader lives here rather than in its own module even though the+// decision logic below is pure and the loader is the one piece with a socket,+// a clock and mutable state. Splitting them would need the loader to import+// `normalizeEmail` at runtime, and Node's ESM loader requires an explicit+// `.ts` on that relative import while TypeScript rejects it without+// `allowImportingTsExtensions`. That flag does work (it is compatible with+// this project's `noEmit`), so this is a preference, not a hard block: one+// cohesive 260-line module beat adding a compiler option and the only+// `.ts`-suffixed import in the codebase. Revisit if this file grows again./** Where an allow/deny decision came from. Recorded in audit-log `details`. */export type AllowSource =@@ -30,11 +34,16 @@ export type AllowSource =/** Missed ALLOWED_EMAILS; the roster was unreadable, so membership is unknown. */| "env_only_roster_unavailable";+// `readonly` + the frozen ENV_HIT below are load-bearing, not decoration:+// both decision functions return that one shared object by reference, so an+// accidental `decision.allowed = false` in a caller would otherwise poison+// every later env hit in the process — the exact #132 lockout class this+// module exists to prevent. Frozen, the stray write throws instead.export type AllowDecision = {- allowed: boolean;- source: AllowSource;+ readonly allowed: boolean;+ readonly source: AllowSource;/** True only when the answer is "no" AND the roster could not be read. */- rosterUnknown: boolean;+ readonly rosterUnknown: boolean;};export function normalizeEmail(email: string | null | undefined): string {@@ -67,8 +76,12 @@ function matchesEnv(normalized: string, envAllowed: ReadonlySet<string>): booleareturn normalized.length > 0 && envAllowed.has(normalized);}-/** The allow decision for an env hit. One object literal, one place. */-const ENV_HIT: AllowDecision = { allowed: true, source: "env", rosterUnknown: false };+/** The allow decision for an env hit. One object literal, one place, frozen. */+const ENV_HIT: AllowDecision = Object.freeze({+ allowed: true,+ source: "env",+ rosterUnknown: false,+} as const);/*** The union rule, as a pure function. `roster === null` means the roster could@@ -147,10 +160,16 @@ export function describeDenial(source: AllowSource): string {return "not in ALLOWED_EMAILS or the people roster";case "env_only_roster_unavailable":return "not in ALLOWED_EMAILS; people roster unavailable";- default:- // Unreachable from either callback: `env` and `roster` are allow- // outcomes. Kept so the switch is total over AllowSource.+ case "env":+ case "roster":+ // Unreachable from either callback: these are allow outcomes. The+ // `never` assignment makes adding an AllowSource a build error here+ // rather than a silent fall-through to a generic clause.return "not allowed";+ default: {+ const unhandled: never = source;+ return unhandled;+ }}}@@ -162,6 +181,14 @@ export type RosterLoaderOptions = {baseUrl: string;sharedSecret: string;ttlMs: number;+ /**+ * Abandon a roster fetch after this long. Required because callers share one+ * in-flight request: without it, undici only gives up at its default+ * ~300s header timeout, so a hung backend would pin every joiner to the same+ * doomed attempt and keep denying new roster-only sign-ins long after the+ * backend recovered — the opposite of "a failure is not cached".+ */+ timeoutMs: number;fetchImpl: typeof fetch;now?: () => number;onWarn?: (message: string) => void;@@ -186,7 +213,7 @@ export type RosterLoaderOptions = {export function createRosterLoader(opts: RosterLoaderOptions,): () => Promise<ReadonlySet<string> | null> {- const { baseUrl, sharedSecret, ttlMs, fetchImpl } = opts;+ const { baseUrl, sharedSecret, ttlMs, timeoutMs, fetchImpl } = opts;const now = opts.now ?? (() => Date.now());const warn = opts.onWarn ?? (() => {});let cache: { fetchedAt: number; emails: ReadonlySet<string> } | null = null;@@ -200,6 +227,7 @@ export function createRosterLoader(headers,// Don't let a stale Next.js fetch cache gate access.cache: "no-store",+ signal: AbortSignal.timeout(timeoutMs),});if (!res.ok) {warn(@@ -244,7 +272,11 @@ export function createRosterLoader(return function loadRoster(): Promise<ReadonlySet<string> | null> {const at = now();- if (cache && at - cache.fetchedAt < ttlMs) return Promise.resolve(cache.emails);+ // `age >= 0` matters: a backwards clock step makes the delta negative,+ // which would otherwise read as "fresh" and serve an expired roster for+ // up to another TTL.+ const age = cache ? at - cache.fetchedAt : Infinity;+ if (cache && age >= 0 && age < ttlMs) return Promise.resolve(cache.emails);// Coalesce concurrent misses onto one request. This is what keeps a page// load — `authorized` runs per gated request — from fanning out into N// backend calls, and it is why at most one fetch is ever in flight.