feat(authz): reach the merged catalog from boot via a process-wide singleton
Fix round 1 for Task 14 — closes the gap flagged in the last report:
loadAppAuthzCatalog existed but nothing called it.
- packages/authz/src/client.ts (new): setAuthzCatalog/getAuthzCatalog/
hasAuthzCatalog, mirroring @wrnexus/db's client.ts. App middleware runs
at module-eval time and needs the catalog then, so ctx cannot carry it;
getAuthzCatalog() throws a setup error naming the fix, like getDb() does.
Exported from packages/authz/src/index.ts.
- packages/dev-server/src/index.ts: startServer calls loadAppAuthzCatalog +
setAuthzCatalog before middleware is resolved (schemasJs precedent),
and populates the new RuntimeDeps.authz field.
- packages/dev-server/src/runtime.ts: RuntimeDeps gains authz?: AuthzCatalog.
- packages/cli/src/build.ts: emits static imports of each app/authz/*.ts
file into the generated entry (components/layouts precedent) and passes
{ source, module } pairs through ProdOptions.authz — the catalog holds
policy functions, so it cannot be JSON-baked like schemasJs.
- packages/dev-server/src/prod.ts: createProductionHandlers merges those
declarations and calls setAuthzCatalog before the server accepts
traffic, so a conflict fails the boot instead of surfacing on the first
request. Runs for every deployment adapter, not only Bun.serve.
The framework never installs authzMiddleware itself; the app still
registers it with its own store.
Verified end-to-end: added a temporary app/authz declaration to
examples/basic-app, ran `bun run build`, inspected the generated entry's
static import + authz array, and booted dist/server.js to confirm the
merge/setAuthzCatalog call succeeds against real bundled code (reverted
before commit).
This commit is contained in:
@@ -0,0 +1,44 @@
|
||||
/**
|
||||
* A process-wide authorization catalog registry, mirroring `@wrnexus/db`'s
|
||||
* `client.ts` (`setDb`/`getDb`/`hasDb`). It exists for the same reason: app
|
||||
* middleware runs at module-eval time — `app/middleware/*.ts` registers
|
||||
* `authzMiddleware({ catalog, store, ... })` itself, and it needs the merged
|
||||
* catalog *then*, before the first request. Passing it through `ctx` does not
|
||||
* work at that point, so the framework loads and merges every `app/authz/*.ts`
|
||||
* declaration at boot (dev: `loadAppAuthzCatalog` + `setAuthzCatalog`, before
|
||||
* middleware is resolved; prod: `mergeCatalogs` over the statically-imported
|
||||
* declarations + `setAuthzCatalog`, before the server starts listening) and
|
||||
* stashes it here. The framework never installs `authzMiddleware` itself — the
|
||||
* app always chooses its own store and registers the middleware; this registry
|
||||
* only makes the merged catalog reachable when it does.
|
||||
*/
|
||||
|
||||
import type { AuthzCatalog } from "./types.ts";
|
||||
|
||||
let catalog: AuthzCatalog | undefined;
|
||||
|
||||
/** Set the process-wide authorization catalog (called by the framework at boot). */
|
||||
export function setAuthzCatalog(next: AuthzCatalog): AuthzCatalog {
|
||||
catalog = next;
|
||||
return next;
|
||||
}
|
||||
|
||||
/** The process-wide authorization catalog. Throws if it hasn't been set. */
|
||||
export function getAuthzCatalog(): AuthzCatalog {
|
||||
if (!catalog) {
|
||||
throw new Error(
|
||||
"WRN-AUTHZ-SETUP: no authorization catalog is configured. The dev server and " +
|
||||
"production build call loadAppAuthzCatalog()/mergeCatalogs() and setAuthzCatalog() " +
|
||||
"automatically before your app's middleware runs. If you're seeing this, either " +
|
||||
"getAuthzCatalog() ran before that boot step (e.g. at import time) or you're " +
|
||||
"outside the normal boot path (a standalone script or test) and must call " +
|
||||
"setAuthzCatalog(catalog) yourself first.",
|
||||
);
|
||||
}
|
||||
return catalog;
|
||||
}
|
||||
|
||||
/** Whether the process-wide authorization catalog has been set. */
|
||||
export function hasAuthzCatalog(): boolean {
|
||||
return catalog !== undefined;
|
||||
}
|
||||
@@ -143,6 +143,7 @@ export type { AuthorizationDecision, DecisionPolicy } from "./advanced.ts";
|
||||
export { defineAuthz } from "./registry.ts";
|
||||
export { mergeCatalogs, emptyCatalog } from "./catalog.ts";
|
||||
export type { CatalogSource } from "./catalog.ts";
|
||||
export { setAuthzCatalog, getAuthzCatalog, hasAuthzCatalog } from "./client.ts";
|
||||
export { memoryPermissionStore, cachedPermissionStore, scopeKey } from "./store.ts";
|
||||
export type { PermissionStore, CachedPermissionStore, CacheOptions, GrantEffect } from "./store.ts";
|
||||
export { memoryAuditSink, consoleAuditSink, safeRecord } from "./audit.ts";
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { pathToFileURL } from "node:url";
|
||||
import { join } from "node:path";
|
||||
import { defineAuthz } from "../src/registry.ts";
|
||||
import { mergeCatalogs } from "../src/catalog.ts";
|
||||
import { getAuthzCatalog, hasAuthzCatalog, setAuthzCatalog } from "../src/client.ts";
|
||||
|
||||
const CLIENT_URL = pathToFileURL(join(import.meta.dir, "..", "src", "client.ts")).href;
|
||||
|
||||
describe("authz process-wide catalog singleton", () => {
|
||||
// `catalog` is module-level state, and bun test does NOT isolate module
|
||||
// instances between test files run in the same `bun test` invocation (a
|
||||
// single import in one file is visible to every other file in the run). So
|
||||
// "before any setAuthzCatalog call anywhere in the whole suite" cannot be
|
||||
// observed reliably in-process — a fresh subprocess is the only way to
|
||||
// guarantee the catalog genuinely has never been set.
|
||||
test("getAuthzCatalog throws a setup error before setAuthzCatalog is ever called, in a fresh process", async () => {
|
||||
const proc = Bun.spawn({
|
||||
cmd: [
|
||||
"bun",
|
||||
"-e",
|
||||
`const mod = await import(${JSON.stringify(CLIENT_URL)});
|
||||
if (mod.hasAuthzCatalog()) { console.log("UNEXPECTED_HAS_CATALOG"); process.exit(1); }
|
||||
try {
|
||||
mod.getAuthzCatalog();
|
||||
console.log("UNEXPECTED_NO_THROW");
|
||||
process.exit(1);
|
||||
} catch (e) {
|
||||
console.log("THREW:" + (e instanceof Error ? e.message : String(e)));
|
||||
}`,
|
||||
],
|
||||
stdout: "pipe",
|
||||
stderr: "pipe",
|
||||
cwd: join(import.meta.dir, ".."),
|
||||
});
|
||||
const [stdout, stderr, exitCode] = await Promise.all([
|
||||
new Response(proc.stdout).text(),
|
||||
new Response(proc.stderr).text(),
|
||||
proc.exited,
|
||||
]);
|
||||
expect(stderr).toBe("");
|
||||
expect(exitCode).toBe(0);
|
||||
expect(stdout).toContain("THREW:");
|
||||
// Names the fix, like getDb()'s "No database configured. Add `db: ...`" message.
|
||||
expect(stdout).toContain("WRN-AUTHZ-SETUP");
|
||||
expect(stdout).toContain("setAuthzCatalog");
|
||||
});
|
||||
|
||||
test("setAuthzCatalog/getAuthzCatalog round-trip, and hasAuthzCatalog reflects the set state", () => {
|
||||
const catalog = mergeCatalogs([
|
||||
{
|
||||
source: "client.test.ts",
|
||||
module: defineAuthz({ permissions: { "post:read": { title: "View posts" } } }),
|
||||
},
|
||||
]);
|
||||
|
||||
const returned = setAuthzCatalog(catalog);
|
||||
expect(returned).toBe(catalog);
|
||||
expect(hasAuthzCatalog()).toBe(true);
|
||||
expect(getAuthzCatalog()).toBe(catalog);
|
||||
expect(getAuthzCatalog().permissions.get("post:read")).toEqual({ title: "View posts" });
|
||||
});
|
||||
|
||||
test("setAuthzCatalog overwrites a previously set catalog", () => {
|
||||
const first = mergeCatalogs([
|
||||
{ source: "a.ts", module: defineAuthz({ permissions: { "a:read": {} } }) },
|
||||
]);
|
||||
const second = mergeCatalogs([
|
||||
{ source: "b.ts", module: defineAuthz({ permissions: { "b:read": {} } }) },
|
||||
]);
|
||||
setAuthzCatalog(first);
|
||||
expect(getAuthzCatalog()).toBe(first);
|
||||
setAuthzCatalog(second);
|
||||
expect(getAuthzCatalog()).toBe(second);
|
||||
expect(getAuthzCatalog().permissions.has("a:read")).toBe(false);
|
||||
expect(getAuthzCatalog().permissions.has("b:read")).toBe(true);
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user