fix(authz): fix prod boot-order (C1), dev HMR staleness (I2), add prod coverage (I4)

Fix round 2 for Task 14, addressing a critical review finding reproduced on
a real built server.

C1 (critical): the generated production entry set the authz catalog inside
createProductionServer's BODY, but ES modules evaluate every static import
(including app middleware, emitted as a static import) before the importing
module's body runs. Middleware reading getAuthzCatalog() at module scope —
the same eager shape authzMiddleware({ catalog, ... }) itself requires, and
the pattern app/middleware/logger.ts's `export default requestLogger({...})`
already uses — saw an unset catalog and crashed the whole process at import
time, after every other gate (typecheck/lint/tests/a plain `bun run build`)
stayed green.

Fix: packages/cli/src/build.ts now emits a small side-effecting
`.authz-setup.ts` module containing the static imports of every
app/authz/*.ts declaration plus a call to the new
applyAuthzManifestEarly(entries) (packages/dev-server/src/prod.ts), and
imports THAT MODULE FIRST in the generated entry — before pages, api,
realtime, middleware, components, and layouts. applyAuthzManifestEarly is
deliberately silent (no missing-default-export warnings, though a genuine
conflict still throws and fails the boot at import time); createProductionHandlers
keeps its own unconditional merge+set as an idempotent, always-warning second
pass, so an adapter that bypasses the generated entry and calls it directly
still gets a correctly merged, validated catalog, and so the function stays
independently testable.

I3: corrected packages/authz/src/client.ts's WRN-AUTHZ-SETUP message, which
claimed prod always sets the catalog before middleware runs — true again for
the generated entry after the C1 fix, but not for a custom entry that calls
createProductionHandlers directly.

I2: dev HMR editing app/authz/*.ts reloaded the page while the OLD catalog
stayed authoritative (watch.ts classifies any non-CSS change as "server";
hotUpdate had no authz/ branch) — a false security signal, since tightening
or removing a permission looked like it took effect but didn't until a
restart. Added the branch (packages/dev-server/src/index.ts), and gave
loadAppAuthzCatalog (authz-boot.ts) an injectable importer: a raw import()
would have silently no-op'd on the re-import (Bun caches local TS/JS modules
by filesystem path and ignores query strings), so the hot path routes through
loadModule (pipeline.ts) instead, which copies the edited file to a versioned
sibling specifically to defeat that cache.

I4: added direct createProductionHandlers/applyAuthzManifestEarly tests
(packages/dev-server/test/authz-prod.test.ts: conflict throws naming both
files, missing default export warns and skips, empty array yields an empty
catalog, a second call re-validates rather than trusting a stale singleton)
and the regression test that matters most
(packages/cli/test/authz-prod-coldstart.test.ts): a real `runBuild` + a real
`bun dist/server.js` boot, with a middleware module reading
getAuthzCatalog() at module scope, asserting it actually serves a request.

M5: startServer built its own router once, then loadAppAuthzCatalog built a
second one from scratch on every dev boot and every authz/ hot reload.
loadAppAuthzCatalog now accepts either an appDir (still used standalone, e.g.
by the test suite) or an already-built Router, and both call sites in
index.ts now pass the router they already have.

Every fix in this round was verified non-vacuous by sabotaging it and
confirming the corresponding test fails, then reverting.
This commit is contained in:
2026-08-04 23:16:41 +05:30
parent 226217ecbf
commit 57097c8204
9 changed files with 535 additions and 41 deletions
+145
View File
@@ -0,0 +1,145 @@
import { describe, expect, test } from "bun:test";
import { defineAuthz, getAuthzCatalog } from "@wrnexus/authz";
import {
applyAuthzManifestEarly,
createProductionHandlers,
type ProdManifest,
} from "../src/prod.ts";
const EMPTY_MANIFEST: ProdManifest = {
pages: [],
api: [],
realtime: [],
middleware: [],
components: [],
layouts: [],
};
describe("createProductionHandlers authorization wiring (the idempotent second pass)", () => {
test("an empty (or absent) authz array yields an empty catalog, no error", () => {
createProductionHandlers(EMPTY_MANIFEST, { authz: [] });
expect(getAuthzCatalog().permissions.size).toBe(0);
createProductionHandlers(EMPTY_MANIFEST, {});
expect(getAuthzCatalog().permissions.size).toBe(0);
});
test("a declaration with no default export warns and is skipped, not fatal", () => {
const originalWarn = console.warn;
const warnings: unknown[][] = [];
console.warn = (...args: unknown[]) => {
warnings.push(args);
};
try {
createProductionHandlers(EMPTY_MANIFEST, {
authz: [
{ source: "broken.ts", module: undefined },
{
source: "ok.ts",
module: defineAuthz({ permissions: { "post:read": {} } }),
},
],
});
} finally {
console.warn = originalWarn;
}
expect(getAuthzCatalog().permissions.has("post:read")).toBe(true);
expect(getAuthzCatalog().permissions.size).toBe(1);
expect(warnings.some((args) => args.some((arg) => String(arg).includes("broken.ts")))).toBe(
true,
);
});
test("a conflicting pair of declarations throws, naming both source files", () => {
expect(() =>
createProductionHandlers(EMPTY_MANIFEST, {
authz: [
{
source: "a.ts",
module: defineAuthz({ permissions: { "post:read": { risk: "low" } } }),
},
{
source: "b.ts",
module: defineAuthz({ permissions: { "post:read": { risk: "high" } } }),
},
],
}),
).toThrow(/WRN-AUTHZ-CONFLICT/);
let thrown: unknown;
try {
createProductionHandlers(EMPTY_MANIFEST, {
authz: [
{
source: "a.ts",
module: defineAuthz({ permissions: { "post:read": { risk: "low" } } }),
},
{
source: "b.ts",
module: defineAuthz({ permissions: { "post:read": { risk: "high" } } }),
},
],
});
} catch (error) {
thrown = error;
}
expect(thrown).toBeInstanceOf(Error);
const message = (thrown as Error).message;
expect(message).toContain("a.ts");
expect(message).toContain("b.ts");
});
test("calling createProductionHandlers a second time with different declarations re-validates, not skips", () => {
// Regression guard for the "skip merging if a catalog is already set"
// trap: since setAuthzCatalog is a process-wide singleton, an earlier
// test (or an earlier createProductionHandlers call in the same process)
// can leave hasAuthzCatalog() true. This call must still independently
// merge+validate its OWN opts.authz, not silently trust a stale catalog
// left over from something else.
createProductionHandlers(EMPTY_MANIFEST, {
authz: [{ source: "first.ts", module: defineAuthz({ permissions: { "a:read": {} } }) }],
});
expect(getAuthzCatalog().permissions.has("a:read")).toBe(true);
createProductionHandlers(EMPTY_MANIFEST, {
authz: [{ source: "second.ts", module: defineAuthz({ permissions: { "b:read": {} } }) }],
});
expect(getAuthzCatalog().permissions.has("a:read")).toBe(false);
expect(getAuthzCatalog().permissions.has("b:read")).toBe(true);
});
});
describe("applyAuthzManifestEarly (the eager, silent pass called only by the generated .authz-setup.ts)", () => {
test("sets the catalog from valid declarations", () => {
applyAuthzManifestEarly([
{ source: "early.ts", module: defineAuthz({ permissions: { "early:read": {} } }) },
]);
expect(getAuthzCatalog().permissions.has("early:read")).toBe(true);
});
test("silently skips a missing default export — no warning, no throw", () => {
const originalWarn = console.warn;
let warnCalls = 0;
console.warn = () => {
warnCalls++;
};
try {
expect(() =>
applyAuthzManifestEarly([{ source: "broken.ts", module: undefined }]),
).not.toThrow();
} finally {
console.warn = originalWarn;
}
expect(warnCalls).toBe(0);
expect(getAuthzCatalog().permissions.size).toBe(0);
});
test("still throws on a genuine conflict (fatal either way, just earlier)", () => {
expect(() =>
applyAuthzManifestEarly([
{ source: "a.ts", module: defineAuthz({ permissions: { "post:read": { risk: "low" } } }) },
{ source: "b.ts", module: defineAuthz({ permissions: { "post:read": { risk: "high" } } }) },
]),
).toThrow(/WRN-AUTHZ-CONFLICT/);
});
});
@@ -34,6 +34,19 @@ afterAll(() => {
rmSync(scratchRoot, { recursive: true, force: true });
});
async function waitFor(
condition: () => boolean,
timeoutMs: number,
intervalMs = 50,
): Promise<void> {
const deadline = Date.now() + timeoutMs;
while (Date.now() < deadline) {
if (condition()) return;
await new Promise((resolve) => setTimeout(resolve, intervalMs));
}
if (!condition()) throw new Error(`waitFor: condition was not met within ${timeoutMs}ms`);
}
describe("dev boot loads the authz catalog before middleware is resolved", () => {
test("an app with declarations makes getAuthzCatalog() return them after boot", async () => {
const appDir = scaffold("has-decls", {
@@ -100,4 +113,40 @@ export default defineAuthz({ permissions: { "post:read": { risk: "high" } } });`
expect(message).toContain(join(appDir, "authz", "a.ts"));
expect(message).toContain(join(appDir, "authz", "b.ts"));
});
test("editing a declaration in a RUNNING dev server updates the live catalog, via the real file watcher", async () => {
const appDir = scaffold("hmr-live", {
"main.ts": `import { defineAuthz } from "@wrnexus/authz";
export default defineAuthz({ permissions: { "post:read": {} } });`,
});
const server = await startServer({
appDir,
hostname: "127.0.0.1",
port: 0,
mode: "development",
hmr: true,
});
try {
expect(getAuthzCatalog().permissions.has("post:read")).toBe(true);
expect(getAuthzCatalog().permissions.has("post:write")).toBe(false);
// A real write to disk, picked up by the real fs watcher (watch.ts /
// startWatcher) — not a direct call into any internal hot-update
// function. This is the only way to prove the wiring actually works,
// as opposed to proving only that the code branch exists.
writeFileSync(
join(appDir, "authz", "main.ts"),
`import { defineAuthz } from "@wrnexus/authz";
export default defineAuthz({ permissions: { "post:write": {} } });`,
"utf8",
);
await waitFor(() => getAuthzCatalog().permissions.has("post:write"), 10_000);
expect(getAuthzCatalog().permissions.has("post:write")).toBe(true);
expect(getAuthzCatalog().permissions.has("post:read")).toBe(false);
} finally {
server.stop();
}
}, 15_000);
});