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.
153 lines
5.3 KiB
TypeScript
153 lines
5.3 KiB
TypeScript
import { afterAll, describe, expect, test } from "bun:test";
|
|
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
|
|
import { join } from "node:path";
|
|
import { getAuthzCatalog, hasAuthzCatalog } from "@wrnexus/authz";
|
|
import { startServer } from "../src/index.ts";
|
|
|
|
// Fixtures live inside the repo tree, not os.tmpdir(): a scaffolded file under
|
|
// app/authz importing "@wrnexus/authz" by bare specifier resolves via the root
|
|
// tsconfig.json `paths` map, walked from the *imported file's* location — an
|
|
// out-of-tree path (os.tmpdir(), often a different drive on Windows) never
|
|
// reaches it.
|
|
const scratchRoot = join(import.meta.dir, ".tmp-authz-startserver");
|
|
mkdirSync(scratchRoot, { recursive: true });
|
|
|
|
function scaffold(name: string, authzFiles: Record<string, string>): string {
|
|
const root = mkdtempSync(join(scratchRoot, `${name}-`));
|
|
const appDir = join(root, "app");
|
|
mkdirSync(join(appDir, "pages"), { recursive: true });
|
|
writeFileSync(
|
|
join(root, "package.json"),
|
|
JSON.stringify({ name: `authz-startserver-${name}` }),
|
|
"utf8",
|
|
);
|
|
if (Object.keys(authzFiles).length) {
|
|
mkdirSync(join(appDir, "authz"), { recursive: true });
|
|
for (const [file, body] of Object.entries(authzFiles)) {
|
|
writeFileSync(join(appDir, "authz", file), body, "utf8");
|
|
}
|
|
}
|
|
return appDir;
|
|
}
|
|
|
|
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", {
|
|
"main.ts": `import { defineAuthz } from "@wrnexus/authz";
|
|
export default defineAuthz({ permissions: { "post:read": { title: "View posts" } } });`,
|
|
});
|
|
const server = await startServer({
|
|
appDir,
|
|
hostname: "127.0.0.1",
|
|
port: 0,
|
|
mode: "development",
|
|
hmr: false,
|
|
});
|
|
try {
|
|
expect(hasAuthzCatalog()).toBe(true);
|
|
expect(getAuthzCatalog().permissions.has("post:read")).toBe(true);
|
|
} finally {
|
|
server.stop();
|
|
}
|
|
});
|
|
|
|
test("an app with no app/authz declarations boots without throwing", async () => {
|
|
const appDir = scaffold("no-decls", {});
|
|
const server = await startServer({
|
|
appDir,
|
|
hostname: "127.0.0.1",
|
|
port: 0,
|
|
mode: "development",
|
|
hmr: false,
|
|
});
|
|
try {
|
|
expect(getAuthzCatalog().permissions.size).toBe(0);
|
|
} finally {
|
|
server.stop();
|
|
}
|
|
});
|
|
|
|
test("a conflicting pair of declarations fails the boot, naming both source files", async () => {
|
|
const appDir = scaffold("conflict", {
|
|
"a.ts": `import { defineAuthz } from "@wrnexus/authz";
|
|
export default defineAuthz({ permissions: { "post:read": { risk: "low" } } });`,
|
|
"b.ts": `import { defineAuthz } from "@wrnexus/authz";
|
|
export default defineAuthz({ permissions: { "post:read": { risk: "high" } } });`,
|
|
});
|
|
|
|
let thrown: unknown;
|
|
try {
|
|
const server = await startServer({
|
|
appDir,
|
|
hostname: "127.0.0.1",
|
|
port: 0,
|
|
mode: "development",
|
|
hmr: false,
|
|
});
|
|
// Should be unreachable; stop it anyway so a regression doesn't leak a port.
|
|
server.stop();
|
|
} catch (error) {
|
|
thrown = error;
|
|
}
|
|
|
|
expect(thrown).toBeInstanceOf(Error);
|
|
const message = (thrown as Error).message;
|
|
expect(message).toContain("WRN-AUTHZ-CONFLICT");
|
|
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);
|
|
});
|