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:
@@ -563,6 +563,46 @@ export async function runBuild(appRoot: string): Promise<void> {
|
||||
const imports: string[] = [];
|
||||
let counter = 0;
|
||||
|
||||
// Authorization: emit a small side-effecting module that statically imports
|
||||
// every app/authz/*.ts declaration and calls setAuthzCatalog EAGERLY, then
|
||||
// import THAT MODULE FIRST — before pages/api/realtime/middleware/
|
||||
// components/layouts — so it runs before any other static import's module
|
||||
// body, including app middleware that reads getAuthzCatalog() at module
|
||||
// scope (the same eager shape authzMiddleware({ catalog, ... }) itself
|
||||
// requires; app/middleware/logger.ts's `export default requestLogger({...})`
|
||||
// is the same pattern). ES modules evaluate every static import before the
|
||||
// importing module's own body runs, and evaluate sibling imports in
|
||||
// declaration order — so import POSITION is evaluation order, and this
|
||||
// must be imports[0], strictly before every other push into `imports`
|
||||
// below (in particular before any `mw*` import). This module is
|
||||
// deliberately silent about a missing default export (see
|
||||
// applyAuthzManifestEarly in @wrnexus/dev-server): createProductionHandlers
|
||||
// performs the identical merge again, with its warnings, as an idempotent
|
||||
// second pass — both for adapters that bypass this generated entry and to
|
||||
// avoid warning twice about the same declaration in the normal path.
|
||||
{
|
||||
let authzSetupCounter = 0;
|
||||
const authzSetupImports: string[] = [];
|
||||
const authzSetupEntries = router.authz
|
||||
.map((a) => {
|
||||
const v = `d${authzSetupCounter++}`;
|
||||
authzSetupImports.push(`import * as ${v} from ${JSON.stringify(fwd(a.file))};`);
|
||||
return `{ source: ${JSON.stringify(fwd(a.file))}, module: ${v}.default }`;
|
||||
})
|
||||
.join(", ");
|
||||
const authzSetupContent = `// AUTO-GENERATED authz catalog setup — do not edit.
|
||||
// Imported FIRST by the production entry (see the "Authorization" comment
|
||||
// there) so getAuthzCatalog() is populated before any other static import's
|
||||
// module body runs.
|
||||
import { applyAuthzManifestEarly } from "@wrnexus/dev-server";
|
||||
${authzSetupImports.join("\n")}
|
||||
|
||||
applyAuthzManifestEarly([${authzSetupEntries}]);
|
||||
`;
|
||||
writeFileSync(join(distDir, ".authz-setup.ts"), authzSetupContent, "utf8");
|
||||
imports.push(`import "./.authz-setup.ts";`);
|
||||
}
|
||||
|
||||
const manifestRoutes = (routes: Route[]): string => {
|
||||
const parts = routes.map((r) => {
|
||||
const v = `m${counter++}`;
|
||||
@@ -604,15 +644,18 @@ export async function runBuild(appRoot: string): Promise<void> {
|
||||
.join(", ");
|
||||
if (router.layouts.length) console.log(`✓ Layouts: ${router.layouts.length}`);
|
||||
|
||||
// Authorization declarations (app/authz/*.ts), statically imported like
|
||||
// components/layouts — NOT baked into JSON like schemasJs, because the
|
||||
// catalog contains policy FUNCTIONS, which JSON.stringify cannot carry.
|
||||
// Each module is passed through by reference in ProdOptions.authz and
|
||||
// merged into the process-wide catalog at prod startup (prod.ts), before
|
||||
// the server begins listening, so a conflicting pair of declarations fails
|
||||
// the boot instead of surfacing on the first request. A file with no
|
||||
// default export becomes `module: undefined` here; prod.ts warns and skips
|
||||
// it, matching the dev loader (authz-boot.ts).
|
||||
// Authorization declarations again, this time for ProdOptions.authz — a
|
||||
// SEPARATE set of static imports of the exact same files (harmless; ES
|
||||
// modules are evaluated once and shared across every importer), statically
|
||||
// imported like components/layouts — NOT baked into JSON like schemasJs,
|
||||
// because the catalog contains policy FUNCTIONS, which JSON.stringify
|
||||
// cannot carry. Each module is passed through by reference and merged
|
||||
// AGAIN into the process-wide catalog by createProductionHandlers's second
|
||||
// pass (prod.ts) — see the ".authz-setup.ts" block above for the EARLY,
|
||||
// eager pass that actually makes the catalog visible to app middleware. A
|
||||
// file with no default export becomes `module: undefined` here;
|
||||
// createProductionHandlers warns and skips it, matching the dev loader
|
||||
// (authz-boot.ts).
|
||||
const authzLit = router.authz
|
||||
.map((a) => {
|
||||
const v = `az${counter++}`;
|
||||
|
||||
@@ -0,0 +1,128 @@
|
||||
import { afterAll, expect, test } from "bun:test";
|
||||
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import { runBuild } from "../src/build.ts";
|
||||
|
||||
// This is the regression test for a CRITICAL boot-order bug (C1): in the
|
||||
// generated production entry, app middleware was emitted as a static import
|
||||
// AFTER the authz merge/set happened in the entry's own body. ES modules
|
||||
// evaluate every static import (including middleware) before the importing
|
||||
// module's body runs, so a middleware module reading getAuthzCatalog() at its
|
||||
// own module scope — the SAME eager shape authzMiddleware({ catalog, ... })
|
||||
// itself requires, and the same pattern examples/basic-app's
|
||||
// app/middleware/logger.ts uses for `export default requestLogger({...})` —
|
||||
// saw an unset catalog and threw, taking the app down at deploy while every
|
||||
// other gate (typecheck/lint/tests/a plain `bun run build`) stayed green.
|
||||
// A manual build+boot caught it once; this makes that check permanent.
|
||||
//
|
||||
// Fixtures live inside the repo tree, not os.tmpdir(): both the scaffolded
|
||||
// app files AND the code Bun.build bundles from them import "@wrnexus/authz"
|
||||
// by bare specifier, which resolves via the root tsconfig.json `paths` map
|
||||
// walked from the *importing file's* location — an out-of-tree path never
|
||||
// reaches it.
|
||||
const scratchRoot = join(import.meta.dir, ".tmp-authz-coldstart");
|
||||
mkdirSync(scratchRoot, { recursive: true });
|
||||
|
||||
afterAll(() => {
|
||||
rmSync(scratchRoot, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
test("a module-eval getAuthzCatalog() in app middleware survives a real production cold start", async () => {
|
||||
const root = mkdtempSync(join(scratchRoot, "app-"));
|
||||
const appDir = join(root, "app");
|
||||
mkdirSync(join(appDir, "api"), { recursive: true });
|
||||
mkdirSync(join(appDir, "authz"), { recursive: true });
|
||||
mkdirSync(join(appDir, "middleware"), { recursive: true });
|
||||
writeFileSync(
|
||||
join(root, "package.json"),
|
||||
JSON.stringify({ name: "authz-coldstart-fixture" }),
|
||||
"utf8",
|
||||
);
|
||||
writeFileSync(
|
||||
join(appDir, "api", "health.ts"),
|
||||
`export function GET() {
|
||||
return Response.json({ ok: true });
|
||||
}
|
||||
`,
|
||||
"utf8",
|
||||
);
|
||||
writeFileSync(
|
||||
join(appDir, "authz", "main.ts"),
|
||||
`import { defineAuthz } from "@wrnexus/authz";
|
||||
|
||||
export default defineAuthz({ permissions: { "post:read": {} } });
|
||||
`,
|
||||
"utf8",
|
||||
);
|
||||
writeFileSync(
|
||||
join(appDir, "middleware", "authz-probe.ts"),
|
||||
`import { authzMiddleware, getAuthzCatalog, memoryPermissionStore } from "@wrnexus/authz";
|
||||
|
||||
// Module-eval-time read, on purpose: this is exactly the pattern the
|
||||
// setAuthzCatalog() singleton exists for, and exactly what took the app down
|
||||
// under the pre-fix boot order. If getAuthzCatalog() throws here, this WHOLE
|
||||
// MODULE fails to evaluate and the entry crashes at import time, before
|
||||
// Bun.serve is ever reached.
|
||||
export default authzMiddleware({ catalog: getAuthzCatalog(), store: memoryPermissionStore() });
|
||||
`,
|
||||
"utf8",
|
||||
);
|
||||
|
||||
await runBuild(root);
|
||||
|
||||
const serverPath = join(root, "dist", "server.js");
|
||||
const proc = Bun.spawn({
|
||||
cmd: ["bun", serverPath],
|
||||
env: { ...process.env, PORT: "0" },
|
||||
stdout: "pipe",
|
||||
stderr: "pipe",
|
||||
cwd: root,
|
||||
});
|
||||
|
||||
let port: number | undefined;
|
||||
let stderrText = "";
|
||||
try {
|
||||
const reader = proc.stdout.getReader();
|
||||
const errReader = proc.stderr.getReader();
|
||||
const decoder = new TextDecoder();
|
||||
let buffered = "";
|
||||
const deadline = Date.now() + 20_000;
|
||||
const TIMED_OUT = Symbol("timed out");
|
||||
while (port === undefined && Date.now() < deadline) {
|
||||
const outcome = await Promise.race([
|
||||
reader.read(),
|
||||
new Promise<typeof TIMED_OUT>((resolve) => setTimeout(() => resolve(TIMED_OUT), 250)),
|
||||
]);
|
||||
if (outcome === TIMED_OUT) continue;
|
||||
const { value, done } = outcome;
|
||||
if (done) break;
|
||||
buffered += decoder.decode(value);
|
||||
const match = /listening on http:\/\/[^:]+:(\d+)/.exec(buffered);
|
||||
if (match) port = Number(match[1]);
|
||||
}
|
||||
reader.releaseLock();
|
||||
|
||||
if (port === undefined) {
|
||||
// Drain stderr for a useful failure message before giving up.
|
||||
const errOutcome = await Promise.race([
|
||||
errReader.read(),
|
||||
new Promise<typeof TIMED_OUT>((resolve) => setTimeout(() => resolve(TIMED_OUT), 500)),
|
||||
]);
|
||||
if (errOutcome !== TIMED_OUT && errOutcome.value) {
|
||||
stderrText += decoder.decode(errOutcome.value);
|
||||
}
|
||||
errReader.releaseLock();
|
||||
throw new Error(
|
||||
`production server never printed a "listening on" line within 20s. stderr:\n${stderrText}`,
|
||||
);
|
||||
}
|
||||
errReader.releaseLock();
|
||||
|
||||
const response = await fetch(`http://127.0.0.1:${port}/api/health`);
|
||||
expect(response.status).toBe(200);
|
||||
expect(await response.json()).toEqual({ ok: true });
|
||||
} finally {
|
||||
proc.kill();
|
||||
await proc.exited;
|
||||
}
|
||||
}, 30_000);
|
||||
Reference in New Issue
Block a user