AI-powered virtual executive team — a single coherent executive persona backed by 8 specialist agents (FastAPI + Next.js).
fix: address adversarial review of the allowlist union
Rufus02154828c9bd
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex edc86393..fb22f5e6 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -8,6 +8,18 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0## [Unreleased]### Security+- **The sign-in allow-list is now the union of `ALLOWED_EMAILS` and the People+ roster, not the roster alone** (#132). The UI previously treated the roster+ as authoritative as soon as it held one email, so any Person row with an+ address silently disabled `ALLOWED_EMAILS` — a fixture load, which wipes+ `people` and inserts its own addresses, could lock the configured operator+ out of their own instance. **This widens access on upgrade:** every address+ still sitting in `ALLOWED_EMAILS` regains sign-in even if that person is not+ on the roster, so audit the env var before deploying. Removing someone now+ means removing them from *both* the roster and `ALLOWED_EMAILS`. The+ `authorized` callback's fail-open also narrows: it used to admit any valid+ session whenever the roster fetch failed, and now admits only a session that+ is not in `ALLOWED_EMAILS` and whose roster membership is unreadable.- `packages/ui`: force `lodash-es` to 4.18.1 via an npm `overrides` entry(GHSA-r5fr-rjxr-66jc code injection in `_.template`, GHSA-f23m-r3pf-42rhprototype pollution in `_.unset`/`_.omit`). The vulnerable 4.17.23 was pinneddiff --git a/docs/auth.md b/docs/auth.mdindex 9720933e..8908bf50 100644--- a/docs/auth.md+++ b/docs/auth.md@@ -213,7 +213,7 @@ If `AUTH_GOOGLE_SECRET` is leaked, regenerate in Google Cloud Console (Clients| `OAuth client was not found` / `invalid_client` | `AUTH_GOOGLE_ID` typo, swapped with `AUTH_GOOGLE_SECRET`, or the client lives in a different GCP project || `redirect_uri_mismatch` | The Authorized redirect URI in Google Console doesn't exactly match `<origin>/api/auth/callback/google`. Wait 5 min for Google to propagate after edits || Browser tries to load `0.0.0.0` after sign-in | `AUTH_URL` not set on the UI |-| `AccessDenied` page after Google login | Email is in neither `ALLOWED_EMAILS` nor the People roster (the two are unioned), or Google returned `email_verified !== true`. Check the `auth_login` audit row's `source`: `env_and_roster` = genuinely not listed; `env_only_roster_unavailable` = the roster fetch failed and the email isn't in the env list |+| `AccessDenied` page after Google login | Email is in neither `ALLOWED_EMAILS` nor the People roster (the two are unioned), or Google returned `email_verified !== true`. Check the `auth_login` audit row's `source`: `no_match` = checked against both lists and genuinely not on either; `env_only_roster_unavailable` = the roster fetch failed and the email isn't in the env list || A removed teammate can still sign in | Their email is still in `ALLOWED_EMAILS`. The roster is additive, so archiving the Person alone doesn't revoke access || API returns `401` for every request | UI and API have different `BACKEND_SHARED_SECRET` values (very common after rotating in two separate terminal sessions) || API refuses to start with `RuntimeError: BACKEND_SHARED_SECRET is required` | `OE_PUBLIC_DEPLOYMENT` is set and the secret is missing. Set it; the next restart will boot |diff --git a/packages/core/openexecutive/architecture/architecture-facts.yaml b/packages/core/openexecutive/architecture/architecture-facts.yamlindex ab3eb4c6..a4614ac4 100644--- a/packages/core/openexecutive/architecture/architecture-facts.yaml+++ b/packages/core/openexecutive/architecture/architecture-facts.yaml@@ -2629,9 +2629,13 @@ auth:2. Roster: GET /auth/allowed-emails returns every non-archivedPerson with a non-null email. Consulted only on an env miss,and purely additive.- Roster fetch is cached for 5 minutes per Next.js server instance;- a failed fetch returns null ("unknown") and is deliberately not- cached, and a stale success is not served past its TTL.+ Roster fetch is cached for 5 minutes per Next.js server instance+ (ROSTER_TTL_MS in auth.ts) and concurrent misses coalesce onto one+ in-flight request — `authorized` runs per gated request, so without+ that a page load would fan out into N backend calls. A failed fetch+ returns null ("unknown") and is deliberately not cached, so the next+ caller retries instead of being pinned out for a TTL; a stale success+ is not served past its TTL.The old rule made the roster authoritative as soon as it held oneemail, which was issue #132: anything that wrote a Person row —including a fixture load, which wipes `people` and inserts its own@@ -2641,8 +2645,10 @@ auth:createRosterLoader / describeDenial), unit-tested bypackages/ui/scripts/allowlist.test.mjs; auth.ts keeps only thewiring, the audit calls and the NextAuth config. The decision's- `source` — env | roster | env_and_roster | env_only_roster_unavailable- — is recorded in the audit-log `details`.+ `source` — env | roster | no_match | env_only_roster_unavailable —+ is recorded in the audit-log `details`, and `decideSessionAction`+ maps a decision to the `authorized` outcome (allow /+ allow_roster_unknown / revoke).backend_gate: |BACKEND_SHARED_SECRET via x-api-key header gates every API route(see api.main._shared_secret_gate). The Next.js proxy atdiff --git a/packages/ui/scripts/allowlist.test.mjs b/packages/ui/scripts/allowlist.test.mjsindex cddb8520..e6a9e393 100644--- a/packages/ui/scripts/allowlist.test.mjs+++ b/packages/ui/scripts/allowlist.test.mjs@@ -3,6 +3,7 @@ import test from "node:test";import {createRosterLoader,decideAllowed,+ decideSessionAction,describeDenial,normalizeEmail,parseAllowedEmails,@@ -55,7 +56,7 @@ test("an email in neither list is denied, with both lists readable", () => {const decision = decideAllowed("[email protected]", set("[email protected]"), set("[email protected]"));assert.deepEqual(decision, {allowed: false,- source: "env_and_roster",+ source: "no_match",rosterUnknown: false,});});@@ -64,7 +65,7 @@ test("an empty but readable roster revokes rather than failing open", () => {const decision = decideAllowed("[email protected]", NONE, NONE);assert.deepEqual(decision, {allowed: false,- source: "env_and_roster",+ source: "no_match",rosterUnknown: false,});});@@ -129,11 +130,73 @@ test("an ALLOWED_EMAILS miss fetches the roster exactly once", async () => {assert.equal(calls, 1);});-test("resolveAllowed normalizes before matching either list", async () => {+test("resolveAllowed normalizes before matching the env list", async () => {const decision = await resolveAllowed(" [email protected] ", set("[email protected]"), async () => NONE);assert.equal(decision.allowed, true);});+test("resolveAllowed normalizes before matching the roster too", async () => {+ const decision = await resolveAllowed(" [email protected] ", NONE, async () => set("[email protected]"));+ assert.deepEqual(decision, { allowed: true, source: "roster", rosterUnknown: false });+});++test("resolveAllowed surfaces an unreadable roster as unknown, not a denial", async () => {+ // The fail-open cell of the table, exercised through the real call path the+ // NextAuth callbacks use rather than only through decideAllowed.+ const decision = await resolveAllowed("[email protected]", set("[email protected]"), async () => null);+ assert.deepEqual(decision, {+ allowed: false,+ source: "env_only_roster_unavailable",+ rosterUnknown: true,+ });+});++// --- describeDenial ---------------------------------------------------------++test("denial clauses read as audit summaries and match docs/auth.md", () => {+ assert.equal(describeDenial("no_match"), "not in ALLOWED_EMAILS or the people roster");+ assert.equal(+ describeDenial("env_only_roster_unavailable"),+ "not in ALLOWED_EMAILS; people roster unavailable",+ );+});++// --- decideSessionAction: what `authorized` does with a decision -----------++test("a definite allow keeps the session, whichever list matched", () => {+ assert.equal(decideSessionAction({ allowed: true, source: "env", rosterUnknown: false }), "allow");+ assert.equal(decideSessionAction({ allowed: true, source: "roster", rosterUnknown: false }), "allow");+});++test("a definite miss revokes the session", () => {+ assert.equal(+ decideSessionAction({ allowed: false, source: "no_match", rosterUnknown: false }),+ "revoke",+ );+});++test("an unreadable roster keeps an already-vetted session", () => {+ assert.equal(+ decideSessionAction({+ allowed: false,+ source: "env_only_roster_unavailable",+ rosterUnknown: true,+ }),+ "allow_roster_unknown",+ );+});++test("allowed is honored before rosterUnknown, so a member never hits fail-open", () => {+ // Guards the ordering the old code got wrong: it returned true on any+ // roster-fetch error BEFORE consulting the decision, so an evicted user+ // could coast. `allowed` must win first, and an allow must never be+ // reported as a fail-open.+ assert.equal(+ decideSessionAction({ allowed: true, source: "env", rosterUnknown: true }),+ "allow",+ );+});+// --- createRosterLoader -----------------------------------------------------const okResponse = (rows) => ({ ok: true, status: 200, json: async () => rows });@@ -264,12 +327,73 @@ test("a body that fails to parse as JSON yields null", async () => {assert.equal(await load(), null);});-// --- describeDenial ---------------------------------------------------------+test("at most one fetch is ever in flight, across cache misses and expiries", async () => {+ // This is the invariant that makes an out-of-order resolve impossible: an+ // earlier-started but slower fetch can never land after a newer one and+ // clobber a fresher roster, because a second fetch never starts while the+ // first is pending. Without it, the cache write would need its own guard.+ let clock = 0;+ let open = 0;+ let peak = 0;+ let n = 0;+ const load = createRosterLoader({+ baseUrl: "http://api:8000",+ sharedSecret: "",+ ttlMs: 1000,+ now: () => clock,+ fetchImpl: async () => {+ open += 1;+ peak = Math.max(peak, open);+ await new Promise((r) => setTimeout(r, 5));+ open -= 1;+ n += 1;+ return { ok: true, status: 200, json: async () => [{ email: `p${n}@corp.com`, person_id: n }] };+ },+ });-test("denial clauses read as audit summaries and match docs/auth.md", () => {- assert.equal(describeDenial("env_and_roster"), "not in ALLOWED_EMAILS or the people roster");- assert.equal(- describeDenial("env_only_roster_unavailable"),- "not in ALLOWED_EMAILS; people roster unavailable",- );+ // A burst of misses, then a burst straddling the TTL expiry.+ await Promise.all([load(), load(), load()]);+ clock = 1000;+ await Promise.all([load(), load(), load()]);+ assert.equal(peak, 1, "never more than one concurrent backend fetch");+ assert.equal(n, 2, "one fetch per TTL window, not per caller");++ clock = 1500;+ assert.deepEqual([...(await load())], ["[email protected]"], "the newest roster is what is cached");+});++test("concurrent misses share one in-flight fetch", async () => {+ let fetches = 0;+ const load = createRosterLoader({+ baseUrl: "http://api:8000",+ sharedSecret: "",+ ttlMs: 1000,+ now: () => 0,+ fetchImpl: async () => {+ fetches += 1;+ await new Promise((r) => setTimeout(r, 5));+ return { ok: true, status: 200, json: async () => [{ email: "[email protected]", person_id: 1 }] };+ },+ });+ const results = await Promise.all([load(), load(), load(), load(), load()]);+ assert.equal(fetches, 1, "five concurrent callers, one backend call");+ for (const r of results) assert.deepEqual([...r], ["[email protected]"]);+});++test("a failed in-flight fetch is not retained, so the next caller retries", async () => {+ let n = 0;+ const load = createRosterLoader({+ baseUrl: "http://api:8000",+ sharedSecret: "",+ ttlMs: 60_000,+ now: () => 0,+ fetchImpl: async () => {+ n += 1;+ if (n === 1) throw new Error("ECONNREFUSED");+ return { ok: true, status: 200, json: async () => [{ email: "[email protected]", person_id: 1 }] };+ },+ });+ assert.equal(await load(), null);+ assert.deepEqual([...(await load())], ["[email protected]"]);+ assert.equal(n, 2);});diff --git a/packages/ui/src/auth.ts b/packages/ui/src/auth.tsindex caab94f3..a9c1d3a6 100644--- a/packages/ui/src/auth.ts+++ b/packages/ui/src/auth.ts@@ -2,6 +2,7 @@ import NextAuth from "next-auth";import Google from "next-auth/providers/google";import {createRosterLoader,+ decideSessionAction,describeDenial,parseAllowedEmails,resolveAllowed,@@ -16,14 +17,18 @@ const ENV_ALLOWED = parseAllowedEmails(process.env.ALLOWED_EMAILS);const BACKEND_BASE = process.env.BACKEND_BASE_URL ?? "http://localhost:8000";const BACKEND_SHARED_SECRET = process.env.BACKEND_SHARED_SECRET ?? "";-// 5-minute cache. Cheap insurance against hammering the backend on every-// sign-in attempt, and it keeps sign-in latency bounded if the backend is-// momentarily slow. Both NextAuth callbacks are server-side (Node runtime), so-// the loader's cache is per-server-instance.+// How long a fetched roster is trusted. `authorized` runs on nearly every+// gated request, so this is what keeps one page load from becoming N backend+// calls — and it bounds how long an archived Person stays admitted. Quoted as+// "5 minutes" in docs/auth.md; keep the two in step.+const ROSTER_TTL_MS = 5 * 60 * 1000;++// 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: 5 * 60 * 1000,+ ttlMs: ROSTER_TTL_MS,// Wrapped rather than passed bare: `fetch` must keep its own receiver.fetchImpl: (input, init) => fetch(input, init),onWarn: (message) => console.warn(message),@@ -134,28 +139,26 @@ export const { handlers, auth, signIn, signOut } = NextAuth({// until their JWT expires.//// Fails open ONLY for a session that is not in ALLOWED_EMAILS and whose- // roster membership is currently unreadable (`rosterUnknown`), so a brief- // backend hiccup doesn't sign out everyone with a valid session — the- // strict `signIn` gate already vetted them once. A *definite* miss (both- // lists readable, neither matched) still revokes. `allowed` is checked- // first so env and roster members never route through the fail-open- // branch at all.+ // roster membership is currently unreadable, so a brief backend hiccup+ // doesn't sign out everyone with a valid session — the strict `signIn`+ // gate already vetted them once. A *definite* miss (both lists readable,+ // neither matched) still revokes. `decideSessionAction` owns that+ // ordering so it can be tested without importing this module.authorized: async ({ auth }) => {if (!auth?.user?.email) return false;const email = auth.user.email.toLowerCase();- const { allowed, source, rosterUnknown } = await checkEmailAllowed(email);- if (allowed) return true;- if (rosterUnknown) return true;+ 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(source)})`,+ `Session revoked: ${email} (${describeDenial(decision.source)})`,email,{revoked: true,reason: "not_in_allowlist",- source,+ source: decision.source,roster_unavailable: false,},);diff --git a/packages/ui/src/lib/allowlist.ts b/packages/ui/src/lib/allowlist.tsindex 83a23dc3..cf7f1a8b 100644--- a/packages/ui/src/lib/allowlist.ts+++ b/packages/ui/src/lib/allowlist.ts@@ -9,9 +9,15 @@// access. Under the union that cannot happen: an env entry is revocable only// by editing the env.//-// No imports here (not React, not next-auth) so `npm test` can exercise this-// directly under `node --experimental-strip-types` — see-// scripts/allowlist.test.mjs. auth.ts keeps only the wiring and audit calls.+// 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./** Where an allow/deny decision came from. Recorded in audit-log `details`. */export type AllowSource =@@ -19,8 +25,8 @@ export type AllowSource =| "env"/** Missed ALLOWED_EMAILS, matched the People roster. */| "roster"- /** Definite miss: both lists were readable and neither had the email. */- | "env_and_roster"+ /** Definite miss: both lists were readable and neither held the email. */+ | "no_match"/** Missed ALLOWED_EMAILS; the roster was unreadable, so membership is unknown. */| "env_only_roster_unavailable";@@ -51,12 +57,25 @@ export function parseAllowedEmails();}+/**+ * The one env-match rule, shared by `decideAllowed` and `resolveAllowed` so the+ * two can never drift. The emptiness guard matters because this is exported+ * surface: a caller can hand in a set built by hand rather than by+ * `parseAllowedEmails`, and `""` must never match `""`.+ */+function matchesEnv(normalized: string, envAllowed: ReadonlySet<string>): boolean {+ return 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 union rule, as a pure function. `roster === null` means the roster could* not be read; an empty set means it was read and is genuinely empty.** Note that an env hit yields `rosterUnknown: false` even when the roster is- * unreadable — the decision never depended on the roster, so there is nothing+ * unreadable — the decision never consulted the roster, so there is nothing* unknown about it.*/export function decideAllowed(@@ -65,9 +84,7 @@ export function decideAllowed(roster: ReadonlySet<string> | null,): AllowDecision {const normalized = normalizeEmail(email);- if (normalized.length > 0 && envAllowed.has(normalized)) {- return { allowed: true, source: "env", rosterUnknown: false };- }+ if (matchesEnv(normalized, envAllowed)) return ENV_HIT;if (roster === null) {return {allowed: false,@@ -80,7 +97,7 @@ export function decideAllowed(}// Both lists readable and neither matched — a definite no. An empty roster// lands here too, so it revokes rather than failing open.- return { allowed: false, source: "env_and_roster", rosterUnknown: false };+ return { allowed: false, source: "no_match", rosterUnknown: false };}/**@@ -98,25 +115,49 @@ export async function resolveAllowed(loadRoster: () => Promise<ReadonlySet<string> | null>,): Promise<AllowDecision> {const normalized = normalizeEmail(email);- if (normalized.length > 0 && envAllowed.has(normalized)) {- return { allowed: true, source: "env", rosterUnknown: false };- }+ if (matchesEnv(normalized, envAllowed)) return ENV_HIT;return decideAllowed(normalized, envAllowed, await loadRoster());}+/**+ * What the `authorized` callback should do with a decision about an existing+ * session. Split out from auth.ts because auth.ts calls `NextAuth()` at module+ * scope and cannot be imported by the test harness — and this ordering is the+ * security-relevant part: `allowed` is consulted BEFORE `rosterUnknown`, so+ * env and roster members never route through the fail-open branch.+ */+export type SessionAction =+ /** On the allowlist right now. */+ | "allow"+ /** Not on it, but the roster is unreadable — keep the already-vetted session. */+ | "allow_roster_unknown"+ /** Definite miss. Bounce them on this request. */+ | "revoke";++export function decideSessionAction(decision: AllowDecision): SessionAction {+ if (decision.allowed) return "allow";+ if (decision.rosterUnknown) return "allow_roster_unknown";+ return "revoke";+}+/** Human clause for audit summaries. Mirrored in docs/auth.md's Debugging table. */export function describeDenial(source: AllowSource): string {switch (source) {- case "env_and_roster":+ case "no_match":return "not in ALLOWED_EMAILS or the people roster";case "env_only_roster_unavailable":return "not in ALLOWED_EMAILS; people roster unavailable";default:- // Unreachable: `env` and `roster` are allow outcomes.+ // Unreachable from either callback: `env` and `roster` are allow+ // outcomes. Kept so the switch is total over AllowSource.return "not allowed";}}+// --------------------------------------------------------------------------+// Roster fetching: the one impure part of this module.+// --------------------------------------------------------------------------+export type RosterLoaderOptions = {baseUrl: string;sharedSecret: string;@@ -127,15 +168,20 @@ export type RosterLoaderOptions = {};/**- * Build a cached loader for GET /auth/allowed-emails. The cache lives in the- * returned closure (one per Next.js server instance — both NextAuth callbacks- * run in the Node runtime), which keeps sign-in from hammering the backend and- * bounds sign-in latency when the backend is momentarily slow.+ * Build a cached loader for GET /auth/allowed-emails. The cache and the+ * in-flight promise live in the returned closure, so there is one per Next.js+ * server instance.+ *+ * This is called from the `authorized` callback, which the middleware runs on+ * essentially every non-asset request — not just at sign-in. So the cache is+ * what keeps a page load from becoming N backend calls, and concurrent callers+ * share a single in-flight fetch rather than each opening their own.** Returns `null` on any failure, which callers read as "roster unknown". A- * failure is deliberately NOT cached, so the next attempt retries; and a stale- * success is deliberately NOT served past its TTL, because "serve stale on- * refresh failure" is a different revocation contract than the one documented.+ * failure is deliberately NOT cached, so the next attempt retries rather than+ * pinning a roster-only user out for a TTL after a blip; and a stale success is+ * deliberately NOT served past its TTL, because "serve stale on refresh+ * failure" is a different revocation contract than the one docs/auth.md states.*/export function createRosterLoader(opts: RosterLoaderOptions,@@ -144,16 +190,15 @@ export function createRosterLoader(const now = opts.now ?? (() => Date.now());const warn = opts.onWarn ?? (() => {});let cache: { fetchedAt: number; emails: ReadonlySet<string> } | null = null;+ let inFlight: Promise<ReadonlySet<string> | null> | null = null;- return async function loadRoster(): Promise<ReadonlySet<string> | null> {- const at = now();- if (cache && at - cache.fetchedAt < ttlMs) return cache.emails;+ async function fetchRoster(at: number): Promise<ReadonlySet<string> | null> {try {const headers: Record<string, string> = {};if (sharedSecret) headers["x-api-key"] = sharedSecret;const res = await fetchImpl(`${baseUrl}/auth/allowed-emails`, {headers,- // Sign-in is rare; don't let stale Next.js fetch caches gate access.+ // Don't let a stale Next.js fetch cache gate access.cache: "no-store",});if (!res.ok) {@@ -167,7 +212,9 @@ export function createRosterLoader(// rather than throwing into NextAuth's callback.const body = (await res.json()) as unknown;if (!Array.isArray(body)) {- warn(`[auth] roster fetch returned a non-array body; treating the roster as unavailable`);+ warn(+ `[auth] roster fetch returned a non-array body; treating the roster as unavailable`,+ );return null;}const emails: ReadonlySet<string> = new Set(@@ -177,6 +224,13 @@ export function createRosterLoader(.map((r) => normalizeEmail(r.email)).filter((e) => e.length > 0),);+ // `at` is the PRE-fetch timestamp, so the effective TTL is shortened by+ // the fetch duration — conservative, and deliberate. Writing it+ // unconditionally is safe only because `loadRoster` keeps at most one+ // fetch in flight: without that, an earlier-started but slower fetch+ // could resolve last, clobber a fresher roster and stamp it with the+ // older `fetchedAt`, keeping an archived Person admitted for up to an+ // extra TTL window.cache = { fetchedAt: at, emails };return emails;} catch (err) {@@ -186,5 +240,21 @@ export function createRosterLoader();return null;}+ }++ return function loadRoster(): Promise<ReadonlySet<string> | null> {+ const at = now();+ if (cache && at - cache.fetchedAt < 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.+ // Cleared in `finally`, so a failure is not retained and the next caller+ // retries rather than being pinned out for a TTL.+ if (inFlight) return inFlight;+ const pending = fetchRoster(at).finally(() => {+ if (inFlight === pending) inFlight = null;+ });+ inFlight = pending;+ return pending;};}