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:
@@ -506,7 +506,9 @@
|
|||||||
"filterAuthorized",
|
"filterAuthorized",
|
||||||
"filterCan",
|
"filterCan",
|
||||||
"generatePermissionTypes",
|
"generatePermissionTypes",
|
||||||
|
"getAuthzCatalog",
|
||||||
"guardPermission",
|
"guardPermission",
|
||||||
|
"hasAuthzCatalog",
|
||||||
"hasRole",
|
"hasRole",
|
||||||
"memoryAuditSink",
|
"memoryAuditSink",
|
||||||
"memoryPermissionStore",
|
"memoryPermissionStore",
|
||||||
@@ -516,7 +518,8 @@
|
|||||||
"requirePermission",
|
"requirePermission",
|
||||||
"requireRole",
|
"requireRole",
|
||||||
"safeRecord",
|
"safeRecord",
|
||||||
"scopeKey"
|
"scopeKey",
|
||||||
|
"setAuthzCatalog"
|
||||||
],
|
],
|
||||||
"./db": [
|
"./db": [
|
||||||
"authzMigrationSql",
|
"authzMigrationSql",
|
||||||
|
|||||||
@@ -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 { defineAuthz } from "./registry.ts";
|
||||||
export { mergeCatalogs, emptyCatalog } from "./catalog.ts";
|
export { mergeCatalogs, emptyCatalog } from "./catalog.ts";
|
||||||
export type { CatalogSource } from "./catalog.ts";
|
export type { CatalogSource } from "./catalog.ts";
|
||||||
|
export { setAuthzCatalog, getAuthzCatalog, hasAuthzCatalog } from "./client.ts";
|
||||||
export { memoryPermissionStore, cachedPermissionStore, scopeKey } from "./store.ts";
|
export { memoryPermissionStore, cachedPermissionStore, scopeKey } from "./store.ts";
|
||||||
export type { PermissionStore, CachedPermissionStore, CacheOptions, GrantEffect } from "./store.ts";
|
export type { PermissionStore, CachedPermissionStore, CacheOptions, GrantEffect } from "./store.ts";
|
||||||
export { memoryAuditSink, consoleAuditSink, safeRecord } from "./audit.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);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -604,6 +604,24 @@ export async function runBuild(appRoot: string): Promise<void> {
|
|||||||
.join(", ");
|
.join(", ");
|
||||||
if (router.layouts.length) console.log(`✓ Layouts: ${router.layouts.length}`);
|
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).
|
||||||
|
const authzLit = router.authz
|
||||||
|
.map((a) => {
|
||||||
|
const v = `az${counter++}`;
|
||||||
|
imports.push(`import * as ${v} from ${JSON.stringify(fwd(a.file))};`);
|
||||||
|
return `{ source: ${JSON.stringify(fwd(a.file))}, module: ${v}.default }`;
|
||||||
|
})
|
||||||
|
.join(", ");
|
||||||
|
if (router.authz.length) console.log(`✓ Authz: ${router.authz.length} declaration(s)`);
|
||||||
|
|
||||||
const entry = `// AUTO-GENERATED production server entry — do not edit.
|
const entry = `// AUTO-GENERATED production server entry — do not edit.
|
||||||
import { join } from "node:path";
|
import { join } from "node:path";
|
||||||
import { createProductionServer } from ${JSON.stringify(PROD_MODULE)};
|
import { createProductionServer } from ${JSON.stringify(PROD_MODULE)};
|
||||||
@@ -627,6 +645,7 @@ await createProductionServer(
|
|||||||
uiCssPath: join(import.meta.dir, "ui.css"),
|
uiCssPath: join(import.meta.dir, "ui.css"),
|
||||||
frameworkCssPath: join(import.meta.dir, "framework.css"),
|
frameworkCssPath: join(import.meta.dir, "framework.css"),
|
||||||
schemasJs: ${JSON.stringify(schemasJs)},
|
schemasJs: ${JSON.stringify(schemasJs)},
|
||||||
|
authz: [${authzLit}],
|
||||||
i18n: ${i18n ? JSON.stringify(i18n) : "undefined"},
|
i18n: ${i18n ? JSON.stringify(i18n) : "undefined"},
|
||||||
db: ${config.db ? JSON.stringify(config.db) : "undefined"},
|
db: ${config.db ? JSON.stringify(config.db) : "undefined"},
|
||||||
databases: ${config.databases ? JSON.stringify(config.databases) : "undefined"},
|
databases: ${config.databases ? JSON.stringify(config.databases) : "undefined"},
|
||||||
|
|||||||
@@ -20,6 +20,10 @@ export async function loadAppAuthzCatalog(appDir: string): Promise<AuthzCatalog>
|
|||||||
const sources: CatalogSource[] = [];
|
const sources: CatalogSource[] = [];
|
||||||
for (const entry of router.authz) {
|
for (const entry of router.authz) {
|
||||||
// buildRouter already skips *.gen.ts, so only real declarations arrive here.
|
// buildRouter already skips *.gen.ts, so only real declarations arrive here.
|
||||||
|
// A file that throws on import is intentionally NOT caught here: it is the
|
||||||
|
// same failure class as a genuine conflict (a broken/misconfigured catalog),
|
||||||
|
// and letting it propagate fails the boot loudly instead of silently
|
||||||
|
// producing a partial catalog. Do not "helpfully" wrap this in a try/catch.
|
||||||
const imported = (await import(pathToFileURL(entry.file).href)) as { default?: AuthzModule };
|
const imported = (await import(pathToFileURL(entry.file).href)) as { default?: AuthzModule };
|
||||||
if (!imported.default) {
|
if (!imported.default) {
|
||||||
console.warn(`[wrnexus] authz declaration ${entry.file} has no default export; skipping.`);
|
console.warn(`[wrnexus] authz declaration ${entry.file} has no default export; skipping.`);
|
||||||
|
|||||||
@@ -32,6 +32,8 @@ import {
|
|||||||
} from "@wrnexus/db";
|
} from "@wrnexus/db";
|
||||||
import { connectFromConfig } from "@wrnexus/db/connect";
|
import { connectFromConfig } from "@wrnexus/db/connect";
|
||||||
import { configureStorage, type StorageConfig } from "@wrnexus/uploader";
|
import { configureStorage, type StorageConfig } from "@wrnexus/uploader";
|
||||||
|
import { setAuthzCatalog, type AuthzCatalog } from "@wrnexus/authz";
|
||||||
|
import { loadAppAuthzCatalog } from "./authz-boot.ts";
|
||||||
import { realtimeBusFromConfig } from "./realtime-bus.ts";
|
import { realtimeBusFromConfig } from "./realtime-bus.ts";
|
||||||
import {
|
import {
|
||||||
invalidateModule,
|
invalidateModule,
|
||||||
@@ -336,6 +338,16 @@ export async function startServer(opts: ServeOptions): Promise<RunningServer> {
|
|||||||
|
|
||||||
const schemasJs = await schemaRuntime(router);
|
const schemasJs = await schemaRuntime(router);
|
||||||
|
|
||||||
|
// Authorization: load and merge every app/authz/*.ts declaration, then stash
|
||||||
|
// it in the process-wide registry BEFORE middleware is resolved. App
|
||||||
|
// middleware (which registers authzMiddleware itself, with its own store —
|
||||||
|
// the framework never installs one) runs at request time and needs
|
||||||
|
// getAuthzCatalog() already populated by then. An app with no declarations
|
||||||
|
// gets an empty catalog; a genuine conflict between declarations throws and
|
||||||
|
// fails this boot loudly.
|
||||||
|
const authzCatalog: AuthzCatalog = await loadAppAuthzCatalog(appDir);
|
||||||
|
setAuthzCatalog(authzCatalog);
|
||||||
|
|
||||||
// i18n is opt-in by the presence of app/locales/*.json.
|
// i18n is opt-in by the presence of app/locales/*.json.
|
||||||
const localeMessages = loadLocales(join(appDir, "locales"), { strict: opts.i18n?.strict });
|
const localeMessages = loadLocales(join(appDir, "locales"), { strict: opts.i18n?.strict });
|
||||||
const i18n = Object.keys(localeMessages).length
|
const i18n = Object.keys(localeMessages).length
|
||||||
@@ -457,6 +469,7 @@ export async function startServer(opts: ServeOptions): Promise<RunningServer> {
|
|||||||
security: opts.security,
|
security: opts.security,
|
||||||
observability: opts.observability,
|
observability: opts.observability,
|
||||||
tenancy: opts.tenancy,
|
tenancy: opts.tenancy,
|
||||||
|
authz: authzCatalog,
|
||||||
navigation: opts.navigation,
|
navigation: opts.navigation,
|
||||||
clientRuntimes: pluginContributions.clientRuntimes,
|
clientRuntimes: pluginContributions.clientRuntimes,
|
||||||
hub,
|
hub,
|
||||||
|
|||||||
@@ -38,6 +38,7 @@ import { VALIDATE_RUNTIME } from "@wrnexus/validation";
|
|||||||
import { I18N_RUNTIME, type ResolvedI18n } from "@wrnexus/i18n";
|
import { I18N_RUNTIME, type ResolvedI18n } from "@wrnexus/i18n";
|
||||||
import { setDb, registerLazyDb, getDb, hasDb, migrate } from "@wrnexus/db";
|
import { setDb, registerLazyDb, getDb, hasDb, migrate } from "@wrnexus/db";
|
||||||
import { connectFromConfig } from "@wrnexus/db/connect";
|
import { connectFromConfig } from "@wrnexus/db/connect";
|
||||||
|
import { mergeCatalogs, setAuthzCatalog, type AuthzModule } from "@wrnexus/authz";
|
||||||
import {
|
import {
|
||||||
configureStorage,
|
configureStorage,
|
||||||
serveStoredFile,
|
serveStoredFile,
|
||||||
@@ -103,6 +104,15 @@ export interface ProdOptions {
|
|||||||
frameworkCssPath?: string;
|
frameworkCssPath?: string;
|
||||||
/** Pre-built `window.__wireSchemas = {...}` script for client validation. */
|
/** Pre-built `window.__wireSchemas = {...}` script for client validation. */
|
||||||
schemasJs?: string;
|
schemasJs?: string;
|
||||||
|
/**
|
||||||
|
* Authorization declarations discovered by `wrnexus build` from
|
||||||
|
* `app/authz/*.ts`, statically imported into the generated entry (the
|
||||||
|
* catalog holds policy FUNCTIONS, so — unlike `schemasJs` — it cannot be
|
||||||
|
* JSON-serialised). `module` is `undefined` for a file with no default
|
||||||
|
* export; `createProductionHandlers` warns and skips it, then merges the
|
||||||
|
* rest into the process-wide catalog before the server accepts traffic.
|
||||||
|
*/
|
||||||
|
authz?: { source: string; module?: AuthzModule }[];
|
||||||
/** Resolved i18n bundle (default lang + locale messages). */
|
/** Resolved i18n bundle (default lang + locale messages). */
|
||||||
i18n?: ResolvedI18n;
|
i18n?: ResolvedI18n;
|
||||||
/** Default database connection (driver + url); enables `getDb()`. */
|
/** Default database connection (driver + url); enables `getDb()`. */
|
||||||
@@ -353,6 +363,24 @@ export function createProductionHandlers(
|
|||||||
// (NOT dist/, which is rebuilt) so uploads persist across deploys.
|
// (NOT dist/, which is rebuilt) so uploads persist across deploys.
|
||||||
configureStorage(opts.storage, process.cwd());
|
configureStorage(opts.storage, process.cwd());
|
||||||
|
|
||||||
|
// Authorization: merge the build's statically-imported app/authz/*.ts
|
||||||
|
// declarations into the process-wide catalog BEFORE the handlers (and thus
|
||||||
|
// any request) exist, so a conflicting pair of declarations fails the boot
|
||||||
|
// loudly instead of surfacing on the first request. This runs for every
|
||||||
|
// deployment adapter that calls createProductionHandlers, not only the
|
||||||
|
// Bun.serve path in createProductionServer below. The app still registers
|
||||||
|
// authzMiddleware itself with its own store; this only makes the merged
|
||||||
|
// catalog reachable. No declarations -> an empty catalog, no error.
|
||||||
|
const authzSources = (opts.authz ?? []).flatMap((entry) => {
|
||||||
|
if (!entry.module) {
|
||||||
|
console.warn(`[wrnexus] authz declaration ${entry.source} has no default export; skipping.`);
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
return [{ source: entry.source, module: entry.module }];
|
||||||
|
});
|
||||||
|
const authzCatalog = mergeCatalogs(authzSources);
|
||||||
|
setAuthzCatalog(authzCatalog);
|
||||||
|
|
||||||
// Middleware is already an ordered array of functions.
|
// Middleware is already an ordered array of functions.
|
||||||
const getMiddleware = async (): Promise<Middleware[]> => manifest.middleware;
|
const getMiddleware = async (): Promise<Middleware[]> => manifest.middleware;
|
||||||
|
|
||||||
@@ -388,6 +416,7 @@ export function createProductionHandlers(
|
|||||||
security: opts.security,
|
security: opts.security,
|
||||||
observability: opts.observability,
|
observability: opts.observability,
|
||||||
tenancy: opts.tenancy,
|
tenancy: opts.tenancy,
|
||||||
|
authz: authzCatalog,
|
||||||
navigation: opts.navigation,
|
navigation: opts.navigation,
|
||||||
maxBodyBytes: opts.maxBodyBytes,
|
maxBodyBytes: opts.maxBodyBytes,
|
||||||
realtimeBus: realtimeBusFromConfig(opts.realtime),
|
realtimeBus: realtimeBusFromConfig(opts.realtime),
|
||||||
|
|||||||
@@ -63,6 +63,7 @@ import {
|
|||||||
requestStoreContainer,
|
requestStoreContainer,
|
||||||
} from "@wrnexus/ssr/store-context";
|
} from "@wrnexus/ssr/store-context";
|
||||||
import type { StoreDefinition } from "@wrnexus/store";
|
import type { StoreDefinition } from "@wrnexus/store";
|
||||||
|
import type { AuthzCatalog } from "@wrnexus/authz";
|
||||||
import type { ClientRuntimeDefinition } from "@wrnexus/plugin";
|
import type { ClientRuntimeDefinition } from "@wrnexus/plugin";
|
||||||
import { CacheCoordinator } from "@wrnexus/cache";
|
import { CacheCoordinator } from "@wrnexus/cache";
|
||||||
import { generateServiceWorker } from "@wrnexus/pwa";
|
import { generateServiceWorker } from "@wrnexus/pwa";
|
||||||
@@ -185,6 +186,17 @@ export interface RuntimeDeps {
|
|||||||
health?: HealthRegistry;
|
health?: HealthRegistry;
|
||||||
/** Built-in tenant identity resolution. */
|
/** Built-in tenant identity resolution. */
|
||||||
tenancy?: TenancyConfig;
|
tenancy?: TenancyConfig;
|
||||||
|
/**
|
||||||
|
* Process-wide authorization catalog, merged from `app/authz/*.ts` at boot
|
||||||
|
* (dev: `loadAppAuthzCatalog`; prod: `mergeCatalogs` over the build's static
|
||||||
|
* imports). Also reachable via `@wrnexus/authz`'s `getAuthzCatalog()`
|
||||||
|
* singleton, which is what the app's own `authzMiddleware` registration
|
||||||
|
* actually reads — this field exists so the request pipeline can see the
|
||||||
|
* catalog without importing that singleton directly. The framework never
|
||||||
|
* installs `authzMiddleware` itself; the app always registers it with its
|
||||||
|
* own store.
|
||||||
|
*/
|
||||||
|
authz?: AuthzCatalog;
|
||||||
/** Max request body size in bytes (413 above this). Default 10 MB. */
|
/** Max request body size in bytes (413 above this). Default 10 MB. */
|
||||||
maxBodyBytes?: number;
|
maxBodyBytes?: number;
|
||||||
/** HMR hub for browser live-update sockets (dev only). */
|
/** HMR hub for browser live-update sockets (dev only). */
|
||||||
|
|||||||
@@ -0,0 +1,103 @@
|
|||||||
|
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 });
|
||||||
|
});
|
||||||
|
|
||||||
|
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"));
|
||||||
|
});
|
||||||
|
});
|
||||||
Reference in New Issue
Block a user