refactor(auth): move the request guards out of api-handler into lib/auth/guards

api-handler.ts held two modules: the route wrapper and thirteen guards. The
guards now live in lib/auth/guards/, one module per family (the caller,
the acting-account carrier, the record modes, the cookie-only helpers, the
fresh-factor and recent-proof gates, the Bearer elevation, MFA management).
api-handler.ts keeps the wrapper and re-exports every guard, so it stays the
one public entry and no route changes its import.

The bodies move verbatim; only the version prefixes of moved comments are
dropped. The structural guards that read the auth layer now find the module
that declares a guard by name (helpers/auth-guards.ts) instead of a fixed
path, and a new guard holds the entry: nothing outside the folder but
api-handler.ts imports a guard module.
This commit is contained in:
Marc-André Bombeck committed 2026-10-23 10:54:23 +02:00
1 parent 9de64cae3e
commit ee1561496b
40 files changed
+2153 -1668

No files matched your search

@@ -16,6 +16,11 @@
import { describe, it, expect } from "vitest";
import { join } from "node:path";
import {
API_HANDLER,
authGuardModules,
guardSourceOf,
} from "./helpers/auth-guards";
import {
readSource,
readSourceText,
@@ -80,8 +85,16 @@ describe("the acting-account carrier is read in one place", () => {
// Reads it. The one statement of "what does this request say it is acting
// as", for both transports and for every caller that has to ask.
"lib/auth/acting-carrier.ts",
// The resolver. The only thing that acts on the value.
"lib/api-handler.ts",
// The resolver. The only thing that acts on the value: the guard module
// that reads the carrier off the auth context.
"lib/auth/guards/acting.ts",
// Declares the field on the auth context the resolvers pass around, and
// explains it in prose. Holds no logic that could read it.
"lib/auth/guards/context.ts",
// Names the column in prose only: the record resolver's note on why the
// fence and the carrier read one session row. It reads the carrier
// through `acting.ts`.
"lib/auth/guards/record.ts",
// v1.36.0 — the only thing that WRITES it: the switch endpoint sets it
// through here, ending a grant clears it through here. The routes
// themselves call these two functions and never name the column, which is
@@ -180,7 +193,7 @@ describe("the cookie-only helpers cannot see the acting account", () => {
const COOKIE_ONLY = ["requireAdmin", "requireCookieAuth", "requireFreshMfa"];
it.each(COOKIE_ONLY)("%s resolves the actor and nothing else", (name) => {
const body = functionBody(readSource("src/lib/api-handler.ts", name), name);
const body = functionBody(guardSourceOf(name), name);
// Non-zero proof, twice over: the slice found a function, and the slice is
// the function it claims to be. A renamed helper must fail here rather
@@ -194,7 +207,7 @@ describe("the cookie-only helpers cannot see the acting account", () => {
});
it("substitutes a data-scope user in exactly two functions", () => {
const src = readSource("src/lib/api-handler.ts", "requireRecordAuth");
const src = guardSourceOf("requireRecordAuth", ["requireGuardianAuth"]);
const record = functionBody(src, "requireRecordAuth");
expect(record).toContain("readActingCarrier");
@@ -210,8 +223,22 @@ describe("the cookie-only helpers cannot see the acting account", () => {
// `readActingCarrier` is what turns a request into "acting as somebody
// else". Three callers: the bare path, which refuses on it, and the two
// record paths, which act on it. A fourth would be a mode nobody declared.
const callers = (src.match(/await readActingCarrier\(/g) ?? []).length;
// Counted over the whole auth layer, the wrapper included, because the
// bare path lives in another guard module than the record paths.
const callers = (
[API_HANDLER, ...authGuardModules().map(([rel]) => rel)]
.map((rel) => read(rel))
.join("\n")
.match(/await readActingCarrier\(/g) ?? []
).length;
expect(callers).toBe(3);
expect(
(
functionBody(guardSourceOf("requireAuth"), "requireAuth").match(
/await readActingCarrier\(/g,
) ?? []
).length,
).toBe(1);
});
});
@@ -0,0 +1,80 @@
/**
* The request guards have one public entry.
*
* `requireAuth`, the record modes, the cookie-only helpers and the step-up
* gates live in `src/lib/auth/guards/`, one module per family, and
* `src/lib/api-handler.ts` re-exports them beside `apiHandler`. Routes, jobs
* and libraries import them from there. The guard modules import each other.
* Nothing else reaches into the folder.
*
* One entry keeps the structural guards that freeze the auth surface honest:
* they match an import of `@/lib/api-handler` and follow the local name to its
* calls (`step-up-elevation-guard`, `recent-proof-surface-guard`,
* `sharing-surface-guard`). A route that imported `requireMfaManagementAuth`
* from its guard module directly would be invisible to all of them.
*/
import { dirname, join, relative, sep } from "node:path";
import { describe, expect, it } from "vitest";
import { AUTH_GUARDS_DIR, authGuardModules } from "./helpers/auth-guards";
import {
productionSources,
readSrc,
testSources,
} from "./helpers/source-metrics";
const SRC = join(process.cwd(), "src");
const GUARDS = "lib/auth/guards/";
/** The first-party module a specifier names, relative to `src/`, or null. */
function target(specifier: string, from: string): string | null {
if (specifier.startsWith("@/")) return specifier.slice(2);
if (specifier.startsWith(".")) {
return relative(SRC, join(SRC, dirname(from), specifier))
.split(sep)
.join("/");
}
return null;
}
/**
* Every module specifier in a file: static imports and re-exports, type-only
* ones included (a type import is still a reach into the folder), and
* dynamic `import("…")` / `vi.mock("…")` with a literal.
*/
const SPECIFIER =
/\bfrom\s*["']([^"']+)["']|\b(?:import|mock|doMock)\(\s*["']([^"']+)["']/g;
/** Files that import, re-export or mock anything in the guard folder. */
function importersOfGuards(files: readonly string[]): string[] {
return files.filter((rel) => {
const text = readSrc(rel);
if (!text.includes("guards")) return false;
return [...text.matchAll(SPECIFIER)].some((m) =>
(target(m[1] ?? m[2], rel) ?? "").startsWith(GUARDS),
);
});
}
describe("the auth guards' public entry", () => {
it("is the only module outside the folder that imports a guard module", () => {
const outside = importersOfGuards(productionSources()).filter(
(rel) => !rel.startsWith(GUARDS),
);
// Non-zero proof: the entry itself must be found, or the matcher is blind.
expect(outside.length).toBeGreaterThan(0);
expect(outside).toEqual(["lib/api-handler.ts"]);
});
it("is not bypassed by tests either", () => {
// Tests import the guards the way routes do, so a mock of
// `@/lib/api-handler` stays the one seam they replace.
expect(importersOfGuards(testSources())).toEqual([]);
});
it("covers a folder that is still there", () => {
expect(authGuardModules().length).toBeGreaterThanOrEqual(10);
expect(AUTH_GUARDS_DIR).toBe(`src/${GUARDS.slice(0, -1)}`);
});
});
@@ -1,7 +1,7 @@
{
"$comment": "Production files over 800 lines and their length. Maintained by src/__tests__/source-size-ratchet.test.ts.",
"count": 121,
"total": 143770,
"count": 120,
"total": 141792,
"entries": {
"app/api/dashboard/summary/route.ts": 1032,
"app/api/documents/inbound/route.ts": 811,
@@ -55,7 +55,6 @@
"lib/analytics/score/reader.ts": 998,
"lib/analytics/sleep-night.ts": 1345,
"lib/analytics/summaries-slice.ts": 1248,
"lib/api-handler.ts": 1978,
"lib/auth/session.ts": 811,
"lib/cache/server-cache.ts": 851,
"lib/cycle/prediction.ts": 883,
@@ -1,7 +1,7 @@
{
"$comment": "Comment lines that open with a release version, per file under src/. Maintained by src/__tests__/version-stamp-ratchet.test.ts.",
"count": 2954,
"total": 10499,
"total": 10481,
"entries": {
"__tests__/account-payload-consumer-guard.test.ts": 2,
"__tests__/acting-account-boundary-guard.test.ts": 7,
@@ -1887,7 +1887,7 @@
"lib/analytics/window-confidence.ts": 1,
"lib/analytics/window-trend.ts": 1,
"lib/api-errors.ts": 2,
"lib/api-handler.ts": 22,
"lib/api-handler.ts": 5,
"lib/api-response.ts": 8,
"lib/api/__tests__/api-fetch.test.ts": 1,
"lib/api/__tests__/optimistic-token.test.ts": 1,
@@ -15,6 +15,7 @@
import { describe, it, expect } from "vitest";
import { join } from "node:path";
import { guardSourceOf } from "./helpers/auth-guards";
import {
readSource,
readSourceText,
@@ -226,8 +227,9 @@ describe("T1 — the Bearer resolution set is frozen", () => {
const RESOLUTION_ALLOWLIST = [
// The resolver. Owns the one authorisation arm.
"lib/auth/bearer.ts",
// The REST edge — maps `requireAuth`'s optional scope onto the union.
"lib/api-handler.ts",
// The REST edge — maps `requireAuth`'s optional scope onto the union. The
// guard module behind `requireAuth`, re-exported by `lib/api-handler.ts`.
"lib/auth/guards/caller.ts",
// The MCP edge — the one deliberate `any-valid-token` posture.
"lib/mcp/auth.ts",
// The `/mcp` transport, via `resolveMcpAuthContext`.
@@ -543,7 +545,7 @@ describe("T5 — a delegable route naming a Bearer scope is frozen", () => {
// it and every other leg in this file stays green while a single-purpose
// token gains delegated write — so the refusal is asserted where it lives,
// not only through the behaviour that depends on it.
const src = readSource("src/lib/api-handler.ts", "narrow_scope_selector");
const src = guardSourceOf("requireRecordAuth", ["narrow_scope_selector"]);
expect(src).toMatch(/narrow_scope_selector/);
expect(src).toMatch(/isScopedCredential\(auth\)/);
});
+83
View File
@@ -0,0 +1,83 @@
/**
* Where the request guards live, for the structural tests that read them.
*
* `apiHandler` and the guards it fronts (`requireAuth`, the record modes, the
* cookie-only helpers, the step-up gates) were one file. The guards now live
* in `src/lib/auth/guards/`, one module per family, and `src/lib/api-handler.ts`
* keeps the wrapper and re-exports them as the one public entry.
*
* A test that pins a guard reads the module that DECLARES it, found by name
* here, rather than a hard-coded path. Two properties follow: moving a guard
* between the modules does not need every test edited, and a guard that is
* renamed or deleted throws here instead of leaving a negative assertion green
* over a file that no longer holds it.
*/
import { readSource, readSourceFolder, requireFloor } from "./source-files";
/** The guard folder, relative to the repository root. */
export const AUTH_GUARDS_DIR = "src/lib/auth/guards";
/** The route wrapper and public entry, relative to `src/`. */
export const API_HANDLER = "lib/api-handler.ts";
/** How many guard modules there are at least; a smaller folder is a broken read. */
const GUARD_MODULE_FLOOR = 10;
/** Every guard module as `[path relative to src/, text]`, sorted. */
export function authGuardModules(): Array<[string, string]> {
const modules = readSourceFolder(AUTH_GUARDS_DIR, {
floor: GUARD_MODULE_FLOOR,
}).map(([rel, text]): [string, string] => [`lib/auth/guards/${rel}`, text]);
return requireFloor(
"auth guard modules",
modules,
GUARD_MODULE_FLOOR,
) as Array<[string, string]>;
}
/** Paths (relative to `src/`) of the guard modules plus the wrapper. */
export function authLayerFiles(): string[] {
return [API_HANDLER, ...authGuardModules().map(([rel]) => rel)].sort();
}
function declares(text: string, name: string): boolean {
return new RegExp(`(^|\\n)(export )?(async )?function ${name}\\s*[(<]`).test(
text,
);
}
/**
* The guard module (relative to `src/`) that declares `function name(`.
* Throws unless exactly one does.
*/
export function guardModuleOf(name: string): string {
const found = authGuardModules()
.filter(([, text]) => declares(text, name))
.map(([rel]) => rel);
if (found.length !== 1) {
throw new Error(
`guardModuleOf(${name}): expected exactly one module under ` +
`${AUTH_GUARDS_DIR} to declare it, found ${found.length} ` +
`(${found.join(", ") || "none"}).`,
);
}
return found[0];
}
/**
* The text of the module that declares `name`, read with `readSource` so the
* name and every extra anchor must be present in it.
*/
export function guardSourceOf(
name: string,
extraAnchors: readonly (string | RegExp)[] = [],
): string {
return readSource(`src/${guardModuleOf(name)}`, [name, ...extraAnchors]);
}
/** All guard modules joined, for counts that span the folder. */
export function authGuardsText(): string {
return authGuardModules()
.map(([, text]) => text)
.join("\n");
}
@@ -71,8 +71,9 @@ const RECORD_RESOLVER = "requireRecordAuth";
/**
* Rows the feed cannot show, and the reason each one cannot.
*
* `src/lib/api-handler.ts` is a direct import of every route, so the walk
* below reaches the three actions the auth kit files itself. None of them can
* `src/lib/api-handler.ts` is a direct import of every route, and it
* re-exports the guards in `src/lib/auth/guards/`, so the walk below reaches
* the three actions the auth kit files itself. None of them can
* appear in a record owner's activity view, and the reason is the same for all
* three: they are filed under `auth.user.id` — the CALLER — at a point where
* no record has been resolved. The feed selects rows where `userId` is the
@@ -148,6 +149,13 @@ interface ModuleFacts {
auditActions: string[];
/** First-party modules this one imports, resolved to files. */
imports: string[];
/**
* First-party modules this one re-exports with `export … from`, resolved to
* files. A re-export makes the named module's bindings this module's own,
* so its actions count as this module's (`lib/api-handler.ts` re-exports
* the guards in `lib/auth/guards/`).
*/
reexports: string[];
}
/**
@@ -173,7 +181,19 @@ export function moduleFacts(source: string, fileName: string): ModuleFacts {
const aliases = new Map<string, string>();
const namespaces = new Set<string>();
const importPaths: string[] = [];
const reexportPaths: string[] = [];
parsed.forEachChild((node) => {
if (
ts.isExportDeclaration(node) &&
node.moduleSpecifier &&
ts.isStringLiteral(node.moduleSpecifier)
) {
const resolved = resolveFirstParty(node.moduleSpecifier.text, fileName);
if (resolved !== null && !resolved.includes("__tests__")) {
reexportPaths.push(resolved);
}
return;
}
if (!ts.isImportDeclaration(node)) return;
if (ts.isStringLiteral(node.moduleSpecifier)) {
const resolved = resolveFirstParty(node.moduleSpecifier.text, fileName);
@@ -232,7 +252,13 @@ export function moduleFacts(source: string, fileName: string): ModuleFacts {
};
parsed.forEachChild(visit);
return { delegatesRecord, recordLevels, auditActions, imports: importPaths };
return {
delegatesRecord,
recordLevels,
auditActions,
imports: importPaths,
reexports: reexportPaths,
};
}
/**
@@ -267,7 +293,8 @@ export function resolveFirstParty(
* to this route can file; one level is where a route's own collaborators live
* — the import-admission module and the medication lifecycle module are both
* direct imports of the routes that use them, and both were invisible to a
* walk that read only `route.ts`.
* walk that read only `route.ts`. A module an import re-exports is part of
* that import, not a level below it, so its actions count at the same level.
*/
function actionsReachableFrom(
file: string,
@@ -276,7 +303,41 @@ function actionsReachableFrom(
const own = read(file);
const out = [...own.auditActions];
for (const imported of own.imports) {
out.push(...read(imported).auditActions);
const facts = read(imported);
out.push(...facts.auditActions);
for (const reexported of facts.reexports) {
out.push(...packageActions(reexported, read));
}
}
return out;
}
/**
* The actions of a re-exported module together with the sibling modules it
* imports from its own folder. The re-exported module is a package's public
* face; the siblings are its private parts, which run inside the same call
* (`lib/auth/guards/record.ts` files its refusals through `./acting.ts`).
* Bounded to the one folder, so this does not become the transitive closure
* the walk above deliberately avoids.
*/
function packageActions(
file: string,
read: (path: string) => ModuleFacts,
): string[] {
const folder = dirname(file);
const seen = new Set<string>([file]);
const queue = [file];
const out: string[] = [];
while (queue.length > 0) {
const current = queue.shift() as string;
const facts = read(current);
out.push(...facts.auditActions);
for (const next of [...facts.imports, ...facts.reexports]) {
if (dirname(next) === folder && !seen.has(next)) {
seen.add(next);
queue.push(next);
}
}
}
return out;
}
@@ -135,7 +135,7 @@ type HttpMethod = (typeof HTTP_METHODS)[number];
*/
const REASONS = {
/**
* `requireAdmin()` is cookie-only by construction (`src/lib/api-handler.ts`),
* `requireAdmin()` is cookie-only by construction (`src/lib/auth/guards/cookie.ts`),
* so a Bearer token cannot reach these however wide its scope. The only
* caller that can is the operator's own browser on the admin console, which
* ships with the server and does not read a spec to find out what it talks
@@ -4,8 +4,8 @@
* Exporting the whole record, making a clinician share link, minting a token,
* and the admin backup, restore, wipe and reset actions ask for a fresh proof,
* not only a live session (`requireRecentProof` / `assertRecentCookieProof` in
* `src/lib/api-handler.ts`). This file pins which routes those are, so a route
* cannot drop the gate, and a new one cannot quietly join the list of routes
* `src/lib/auth/guards/recent-proof.ts`, imported through `src/lib/api-handler.ts`).
* This file pins which routes those are, so a route cannot drop the gate, and a new one cannot quietly join the list of routes
* whose Bearer arm still takes the token alone.
*
* Matching is on the IMPORT and then on calls of the local name, the way
@@ -16,11 +16,8 @@
import { describe, it, expect } from "vitest";
import { join } from "node:path";
import {
readSource,
readSourceText,
walkSourceFiles,
} from "./helpers/source-files";
import { guardSourceOf } from "./helpers/auth-guards";
import { readSourceText, walkSourceFiles } from "./helpers/source-files";
const SRC = join(process.cwd(), "src");
@@ -185,10 +182,9 @@ describe("the recent-proof gate", () => {
});
it("the gate reads the session's own stamps, and only a second factor on an enrolled account", () => {
const src = readSource(
"src/lib/api-handler.ts",
const src = guardSourceOf("assertRecentCookieProof", [
"export async function assertRecentCookieProof(",
);
]);
const start = src.indexOf("export async function assertRecentCookieProof(");
expect(start).toBeGreaterThan(-1);
const body = src.slice(start, src.indexOf("\nexport ", start + 1));
@@ -41,6 +41,7 @@
import { describe, it, expect } from "vitest";
import { join } from "node:path";
import { authGuardsText, guardSourceOf } from "./helpers/auth-guards";
import {
readSource,
readSourceText,
@@ -84,10 +85,18 @@ function functionBody(src: string, name: string): string {
return "";
}
const API_HANDLER = readSource("src/lib/api-handler.ts", [
"requireRecordAuth",
"requireGuardianAuth",
]);
/**
* The auth layer: the route wrapper and every guard module it re-exports,
* joined, with the two record resolvers as anchors so a move that loses them
* throws instead of leaving the negative legs below green.
*/
const AUTH_LAYER = (() => {
guardSourceOf("requireRecordAuth", ["requireGuardianAuth"]);
return [
readSource("src/lib/api-handler.ts", "apiHandler"),
authGuardsText(),
].join("\n");
})();
/** The two helpers that resolve a record and therefore must consult the fence. */
const FENCED_RESOLVERS = ["requireRecordAuth", "requireGuardianAuth"] as const;
@@ -124,13 +133,18 @@ const UNFENCED_HELPERS = [
] as const;
describe("the fence runs in exactly two auth helpers", () => {
it("is called by both record resolvers and by nothing else in api-handler", () => {
const calls = [...API_HANDLER.matchAll(/assertRecordSessionFence\s*\(/g)];
it("is called by both record resolvers and by nothing else in the auth layer", () => {
const calls = [
...authGuardsText().matchAll(/assertRecordSessionFence\s*\(/g),
];
expect(readSource("src/lib/api-handler.ts", "apiHandler")).not.toMatch(
/assertRecordSessionFence\s*\(/,
);
// Non-zero proof: an emptied file would agree with an emptied expectation.
expect(calls.length).toBeGreaterThan(0);
const callers = FENCED_RESOLVERS.filter((name) =>
functionBody(API_HANDLER, name).includes("assertRecordSessionFence("),
functionBody(AUTH_LAYER, name).includes("assertRecordSessionFence("),
);
expect(callers).toEqual([...FENCED_RESOLVERS]);
// Two call sites, one import. Anything else means a third caller appeared.
@@ -140,7 +154,7 @@ describe("the fence runs in exactly two auth helpers", () => {
it.each(FENCED_RESOLVERS)(
"%s fences after authentication and before the carrier and the grant",
(name) => {
const body = functionBody(API_HANDLER, name);
const body = functionBody(AUTH_LAYER, name);
expect(body.length).toBeGreaterThan(100);
const fence = body.indexOf("assertRecordSessionFence(");
@@ -163,11 +177,11 @@ describe("the fence runs in exactly two auth helpers", () => {
it("fences before any grant lookup in the shared resolver path", () => {
// `findActiveGrant` lives in `resolveSwitchedRecord`, which both resolvers
// tail-call. Assert it appears nowhere ABOVE the fence in either body.
const grantCalls = [...API_HANDLER.matchAll(/findActiveGrant\s*\(/g)];
const grantCalls = [...authGuardsText().matchAll(/findActiveGrant\s*\(/g)];
expect(grantCalls.length).toBeGreaterThan(0);
for (const name of FENCED_RESOLVERS) {
const body = functionBody(API_HANDLER, name);
const body = functionBody(AUTH_LAYER, name);
const fence = body.indexOf("assertRecordSessionFence(");
const grant = body.indexOf("findActiveGrant(");
// Either the body never names it (it is in the shared tail) or it names
@@ -177,7 +191,7 @@ describe("the fence runs in exactly two auth helpers", () => {
});
it.each(UNFENCED_HELPERS)("%s deliberately does not fence", (name) => {
const body = functionBody(API_HANDLER, name);
const body = functionBody(AUTH_LAYER, name);
expect(body.length).toBeGreaterThan(50);
expect(body).not.toContain("assertRecordSessionFence");
});
@@ -226,7 +240,7 @@ describe("the epoch has one writer and a closed reader set", () => {
// Projects it off the session row it already loaded.
"lib/auth/session.ts",
// Carries it on the auth context the fence is handed.
"lib/api-handler.ts",
"lib/auth/guards/context.ts",
// Compares it. The one place that decides anything from it.
"lib/sharing/record-session-fence.ts",
// Reads it off the same session lookup the idempotency wrapper already
@@ -3,7 +3,7 @@
*
* Every authenticated request resolves its caller through the session lookup
* (`lib/auth/session.ts`), the Bearer resolver (`lib/auth/bearer.ts`) or, for a
* switched record, the owner load in `lib/api-handler.ts`. They used to
* switched record, the owner load in `lib/auth/guards/record.ts`. They used to
* `include: { user: true }` / `findUnique({ where })`, which copied the profile
* picture (megabytes), the cached briefing text and every stored credential
* into memory on each request. They now name `SESSION_USER_SELECT`.
@@ -19,6 +19,7 @@ import { describe, it, expect } from "vitest";
import { readFileSync } from "node:fs";
import { join } from "node:path";
import { guardModuleOf } from "./helpers/auth-guards";
import { walkSourceFiles } from "./helpers/source-files";
import { SESSION_USER_SELECT } from "@/lib/auth/session-user";
@@ -70,7 +71,10 @@ describe("caller lookups load the session projection", () => {
});
it("the Bearer resolver and the switched-owner load select SESSION_USER_SELECT", () => {
for (const rel of ["lib/auth/bearer.ts", "lib/api-handler.ts"]) {
for (const rel of [
"lib/auth/bearer.ts",
guardModuleOf("resolveSwitchedRecord"),
]) {
const calls = callObjects(read(rel), USER_LOOKUP);
expect(calls.length, rel).toBeGreaterThan(0);
for (const body of calls) {
+68 -25
View File
@@ -75,6 +75,7 @@ import { ENTIRE_RECORD, SHARE_DOMAINS } from "@/lib/sharing/scope";
import type { ShareScope } from "@/lib/sharing/scope";
import { ADMITTED_MUTATING_HANDLERS } from "../../tests/fixtures/v137/sharing-matrix";
import { API_HANDLER, guardModuleOf } from "./helpers/auth-guards";
import { readSourceText } from "./helpers/source-files";
const SRC = join(process.cwd(), "src");
@@ -115,7 +116,7 @@ const VALID_SCOPES: ReadonlySet<string> = new Set<string>([
* "is this caller an admin", "has this caller just re-proven a second factor",
* "is this caller here over a cookie". All three resolve through `getSession()`
* and see the actor, never the owner — that is what
* `acting-account-boundary-guard.test.ts` pins inside `api-handler.ts`.
* `acting-account-boundary-guard.test.ts` pins inside `lib/auth/guards/`.
*
* This file pins the other end. A handler that resolves a RECORD and then runs
* one of these has put a role check and a substituted data scope in the same
@@ -721,6 +722,25 @@ function functionSource(rel: string, name: string): string {
return found;
}
/** Names a module re-exports with `export { … } from "…"`. */
function reexportedNames(rel: string): string[] {
const parsed = ts.createSourceFile(
rel,
read(rel),
ts.ScriptTarget.Latest,
true,
ts.ScriptKind.TS,
);
const names: string[] = [];
parsed.forEachChild((node) => {
if (!ts.isExportDeclaration(node) || !node.moduleSpecifier) return;
const clause = node.exportClause;
if (!clause || !ts.isNamedExports(clause)) return;
for (const spec of clause.elements) names.push(spec.name.text);
});
return names;
}
/** Names of the top-level functions a module exports. */
function exportedFunctionNames(rel: string): string[] {
const parsed = ts.createSourceFile(
@@ -2571,11 +2591,17 @@ describe("the resolvers exist and live in one place", () => {
// between "no route administers a managed profile" and "the guard is
// looking for a function that does not exist": its frozen list is empty,
// so its leg's negative result proves nothing on its own.
const exported = exportedFunctionNames("lib/api-handler.ts");
const declaring = guardModuleOf(RECORD_RESOLVER);
const exported = exportedFunctionNames(declaring);
expect(exported.length).toBeGreaterThan(0);
expect(exported).toContain(RECORD_RESOLVER);
expect(exported).toContain(ACTOR_RESOLVER);
expect(exported).toContain(GUARDIAN_RESOLVER);
// And the public entry routes import them from re-exports all three.
const reexported = reexportedNames(API_HANDLER);
expect(reexported).toContain(RECORD_RESOLVER);
expect(reexported).toContain(ACTOR_RESOLVER);
expect(reexported).toContain(GUARDIAN_RESOLVER);
});
it("nothing outside the frozen route lists reaches any resolver", () => {
@@ -2596,7 +2622,9 @@ describe("the resolvers exist and live in one place", () => {
expect(naming).toEqual(
[
// Declares all three. Not a caller.
"lib/api-handler.ts",
guardModuleOf(RECORD_RESOLVER),
// Re-exports all three as the public entry. Not a caller.
API_HANDLER,
...Object.keys(DELEGABLE_ROUTES),
...Object.keys(GUARDIAN_ROUTES),
...Object.keys(ACTOR_ROUTES),
@@ -2631,10 +2659,11 @@ describe("(a) the delegable route set is frozen", () => {
// names nothing" were the same sentence; the list is populated now, so the
// assertion below would catch a neutered matcher on its own. Kept anyway,
// because a future removal could empty the list again and the day that
// happens is not the day to rediscover this. `lib/api-handler.ts` is the
// guaranteed positive — it declares the symbol.
expect(modulesNaming(["lib/api-handler.ts"], RECORD_RESOLVER)).toEqual([
"lib/api-handler.ts",
// happens is not the day to rediscover this. The guard module that
// declares the symbol is the guaranteed positive.
const recordModule = guardModuleOf(RECORD_RESOLVER);
expect(modulesNaming([recordModule], RECORD_RESOLVER)).toEqual([
recordModule,
]);
expect(modulesNaming(scanned, RECORD_RESOLVER)).toEqual(
@@ -2654,9 +2683,8 @@ describe("(b) the actor-surface route set is frozen", () => {
expect(scanned.length).toBeGreaterThan(ROUTE_MODULE_FLOOR);
// Positive control, same reason as leg (a).
expect(modulesNaming(["lib/api-handler.ts"], ACTOR_RESOLVER)).toEqual([
"lib/api-handler.ts",
]);
const actorModule = guardModuleOf(ACTOR_RESOLVER);
expect(modulesNaming([actorModule], ACTOR_RESOLVER)).toEqual([actorModule]);
expect(modulesNaming(scanned, ACTOR_RESOLVER)).toEqual(
Object.keys(ACTOR_ROUTES).sort(),
@@ -2747,14 +2775,22 @@ describe("(c) a record resolver never shares a module with a role or step-up che
});
it("the declaration site is out of scope by construction", () => {
// `lib/api-handler.ts` declares the record resolver AND all three cookie-
// only helpers, so a scan of every source file would need it exempted, and
// an exemption is a hole. Scoping the leg to handler modules removes the
// need for one. This asserts the scoping still holds.
const src = exportedFunctionNames("lib/api-handler.ts");
expect(src).toContain(RECORD_RESOLVER);
for (const helper of COOKIE_ONLY_HELPERS) expect(src).toContain(helper);
expect(routeModules()).not.toContain("lib/api-handler.ts");
// The auth layer declares the record resolver AND all three cookie-only
// helpers (in `lib/auth/guards/`, re-exported by `lib/api-handler.ts`), so
// a scan of every source file would need those modules exempted, and an
// exemption is a hole. Scoping the leg to handler modules removes the need
// for one. This asserts the scoping still holds.
const declaring = [RECORD_RESOLVER, ...COOKIE_ONLY_HELPERS].map((name) =>
guardModuleOf(name),
);
expect(exportedFunctionNames(declaring[0])).toContain(RECORD_RESOLVER);
COOKIE_ONLY_HELPERS.forEach((helper, i) =>
expect(exportedFunctionNames(declaring[i + 1])).toContain(helper),
);
const routes = routeModules();
for (const rel of [API_HANDLER, ...declaring]) {
expect(routes).not.toContain(rel);
}
});
});
@@ -3166,7 +3202,7 @@ describe("(g) the MANAGE route set is frozen", () => {
// …and the fact it reads has to be stamped. The resolver is where the
// owner row is in hand, so it is the only place that can decide it.
const resolver = functionSource(
"lib/api-handler.ts",
guardModuleOf("resolveSwitchedRecord"),
"resolveSwitchedRecord",
);
expect(resolver.length).toBeGreaterThan(0);
@@ -3357,10 +3393,11 @@ describe("(h) the guardian route set is frozen", () => {
// Positive control for this leg's own matcher, the same one leg (a) uses
// and for the same reason twice over: the literal is empty, so "no route
// names the resolver" and "the matcher names nothing" are one sentence
// until something the matcher CAN find is named. `lib/api-handler.ts`
// declares the symbol and is the guaranteed positive.
expect(modulesNaming(["lib/api-handler.ts"], GUARDIAN_RESOLVER)).toEqual([
"lib/api-handler.ts",
// until something the matcher CAN find is named. The guard module that
// declares the symbol is the guaranteed positive.
const guardianModule = guardModuleOf(GUARDIAN_RESOLVER);
expect(modulesNaming([guardianModule], GUARDIAN_RESOLVER)).toEqual([
guardianModule,
]);
expect(modulesNaming(scanned, GUARDIAN_RESOLVER)).toEqual(
@@ -3375,7 +3412,10 @@ describe("(h) the guardian route set is frozen", () => {
// marker. A resolver that stopped reading it would leave every leg here
// passing and the identity fence gone — an invited adult's MANAGE grant
// would reach the settings of a record its owner still runs.
const guardian = functionSource("lib/api-handler.ts", GUARDIAN_RESOLVER);
const guardian = functionSource(
guardModuleOf(GUARDIAN_RESOLVER),
GUARDIAN_RESOLVER,
);
// Non-zero proof, twice: the slice found a function, and it is the one it
// claims to be. A renamed resolver must fail here rather than assert
// against an empty string.
@@ -3386,7 +3426,10 @@ describe("(h) the guardian route set is frozen", () => {
// …and the record resolver must NOT read it. The two resolvers differ in
// exactly this fact, so a marker check that drifted into the delegable
// path would make the fence meaningless while every list still agreed.
const record = functionSource("lib/api-handler.ts", RECORD_RESOLVER);
const record = functionSource(
guardModuleOf(RECORD_RESOLVER),
RECORD_RESOLVER,
);
expect(record.length).toBeGreaterThan(0);
expect(record).not.toContain("managedProfileAt");
});
+33 -22
View File
@@ -25,6 +25,7 @@
import { describe, it, expect } from "vitest";
import { join } from "node:path";
import { guardModuleOf, guardSourceOf } from "./helpers/auth-guards";
import {
readSource,
readSourceText,
@@ -77,6 +78,28 @@ function importedAs(
const API_HANDLER = /api-handler$/;
const STEP_UP_MODULE = /auth\/step-up$/;
/**
* The guard module that reads the elevation header, validates and claims:
* the one redemption path. Found by the function that does it, so a move
* between guard modules repoints every leg below at once.
*/
const GATE_MODULE = guardModuleOf("resolveBearerElevation");
/**
* An exported declaration's source, from its signature to the next top-level
* export (or the end of its module), read from the guard module that declares
* `name`. Throws when the signature is gone, so a negative assertion on the
* slice cannot pass over an empty string.
*/
function exportedBlock(name: string, signature: string): string {
const src = guardSourceOf(name, [signature]);
const start = src.indexOf(signature);
const next = src.indexOf("\nexport ", start + 1);
const body = src.slice(start, next === -1 ? undefined : next);
expect(body.length).toBeGreaterThan(signature.length);
return body;
}
/** Files that import `exportName` from the module AND call it. */
function callers(exportName: string, moduleRe: RegExp): string[] {
return sourceFiles()
@@ -260,15 +283,10 @@ describe("S6 — the erasure routes accept a fresh-factor elevation", () => {
// A password-proved elevation must not erase an account, and the gate
// must not grow a second, inline factor check beside the elevation: one
// mint surface, one redemption path.
const src = readSource(
"src/lib/api-handler.ts",
const body = exportedBlock(
"requireFreshMfaOrElevationIfEnrolled",
"export async function requireFreshMfaOrElevationIfEnrolled(",
);
const start = src.indexOf(
"export async function requireFreshMfaOrElevationIfEnrolled(",
);
expect(start).toBeGreaterThan(-1);
const body = src.slice(start, src.indexOf("\nexport ", start + 1));
expect(body).toMatch(/freshFactor:\s*true/);
expect(body).not.toMatch(/verifyMfaFactor|verifyTotp|recoveryCode/);
});
@@ -279,14 +297,14 @@ describe("S2 — mint and redeem happen in exactly one place each", () => {
const found = callers("claimStepUpElevation", STEP_UP_MODULE).filter(
(rel) => rel !== "lib/auth/step-up.ts",
);
expect(found).toEqual(["lib/api-handler.ts"]);
expect(found).toEqual([GATE_MODULE]);
});
it("only the gate validates one", () => {
const found = callers("validateStepUpElevation", STEP_UP_MODULE).filter(
(rel) => rel !== "lib/auth/step-up.ts",
);
expect(found).toEqual(["lib/api-handler.ts"]);
expect(found).toEqual([GATE_MODULE]);
});
it("only the mint route mints one", () => {
@@ -300,7 +318,7 @@ describe("S2 — mint and redeem happen in exactly one place each", () => {
// Both spellings — the literal string AND the exported constant — across
// every source file, not only `route.ts`. A helper could read it too.
const offenders = sourceFiles()
.filter((rel) => rel !== "lib/api-handler.ts")
.filter((rel) => rel !== GATE_MODULE)
.filter((rel) => {
const src = read(rel);
if (/["']x-step-up["']/i.test(src)) return true;
@@ -314,13 +332,9 @@ describe("S2 — mint and redeem happen in exactly one place each", () => {
describe("S3 — requireAdmin stays cookie-only", () => {
it("resolves through getSession and nothing else", () => {
const src = readSource("src/lib/api-handler.ts", [
const body = exportedBlock(
"requireAdmin",
"export async function requireAdmin(",
"export async function requireCookieAuth(",
]);
const body = src.slice(
src.indexOf("export async function requireAdmin("),
src.indexOf("export async function requireCookieAuth("),
);
expect(body).toContain("await getSession()");
expect(body).not.toMatch(/authenticateBearer|resolveBearerToken/);
@@ -345,14 +359,11 @@ describe("S4 — the mint surface refuses a cookie", () => {
});
it("requireBearerAuth never consults the session cookie", () => {
const src = readSource("src/lib/api-handler.ts", [
const body = exportedBlock(
"requireBearerAuth",
"export async function requireBearerAuth(",
"export const STEP_UP_ELEVATION_HEADER",
]);
const body = src.slice(
src.indexOf("export async function requireBearerAuth("),
src.indexOf("export const STEP_UP_ELEVATION_HEADER"),
);
expect(body).toContain("authenticateBearer(");
expect(body).not.toContain("getSession(");
});
});
+17 -14
View File
@@ -26,11 +26,15 @@ import { readFileSync } from "node:fs";
import { join } from "node:path";
import { describe, expect, it } from "vitest";
import { guardSourceOf } from "./helpers/auth-guards";
import { walkSourceFiles } from "./helpers/source-files";
const SRC = join(process.cwd(), "src");
/** The resolvers in `api-handler.ts` that charge the shared write bucket. */
/**
* The resolvers that charge the shared write bucket: the guards in
* `lib/auth/guards/`, imported by routes through `lib/api-handler.ts`.
*/
const METERING_RESOLVERS = [
"requireAuth",
"requireRecordAuth",
@@ -194,7 +198,16 @@ describe("every mutating route meets a rate limit", () => {
});
it("charges the bucket in each metering resolver", () => {
const handler = read("lib/api-handler.ts");
/** The resolver's source, from its signature to the next export. */
const resolverBody = (name: string): string => {
const signature = new RegExp(
`export\\s+async\\s+function\\s+${name}\\s*\\(`,
);
const handler = guardSourceOf(name, [signature]);
const start = handler.search(signature);
const next = handler.indexOf("\nexport ", start + 1);
return handler.slice(start, next === -1 ? undefined : next);
};
for (const name of [
"requireAuth",
"requireActorAuth",
@@ -205,13 +218,7 @@ describe("every mutating route meets a rate limit", () => {
"requireFreshMfa",
"requireBearerAuth",
]) {
const start = handler.search(
new RegExp(`export\\s+async\\s+function\\s+${name}\\s*\\(`),
);
expect(start, name).toBeGreaterThanOrEqual(0);
const next = handler.indexOf("\nexport ", start + 1);
const body = handler.slice(start, next === -1 ? undefined : next);
expect(body, name).toMatch(/\bmeterAccountWrite\s*\(/);
expect(resolverBody(name), name).toMatch(/\bmeterAccountWrite\s*\(/);
}
// The three that only delegate reach the meter through `requireAuth`.
for (const name of [
@@ -219,11 +226,7 @@ describe("every mutating route meets a rate limit", () => {
"requireFreshMfaOrElevationIfEnrolled",
"requireRecentProof",
]) {
const start = handler.search(
new RegExp(`export\\s+async\\s+function\\s+${name}\\s*\\(`),
);
const next = handler.indexOf("\nexport ", start + 1);
expect(handler.slice(start, next), name).toMatch(/\brequireAuth\s*\(/);
expect(resolverBody(name), name).toMatch(/\brequireAuth\s*\(/);
}
});
});