feat: integrate module authorization

Wires composePlatformPermissionRegistry into apps/api's production
startup: startApi() discovers every installed module, composes the one
immutable platform permission registry (Core's own declarations plus
every module's), and only then constructs the shared PostgreSQL pool,
Better Auth, and the HTTP server. A discovery or composition failure —
an invalid manifest, a reserved core.* namespace claim, or a duplicate
declaration — propagates before anything exists to close; there is no
Core-only registry fallback. apps/api/src/platform-permissions.ts
resolves the repository root from its own file location, never
process.cwd(), so package-scoped test runs discover the right modules/
directory.

createApiApp/createGrantsRoutes now require the composed registry as
an injected authorization option, replacing the previous hard-coded
CORE_PERMISSION_REGISTRY; requirePermission continues to work
identically for Core-owned and module-owned permissions, since it has
no concept of the distinction.

Extends pnpm doctor with a modules.permissions check (reusing the
already-discovered module list, distinguishing reserved-namespace from
generic-duplicate failures, never re-discovering modules) and pnpm
modules:validate to compose the same registry before a module is
considered installable.

Adds focused coverage: startup-ordering and failure-isolation tests in
apps/api/tests/lifecycle.test.ts, module-owned-declaration enforcement
tests in apps/api/tests/authorization-middleware.test.ts, Doctor
composition tests in core/tests/doctor.test.ts, and a live PostgreSQL
end-to-end scenario proving a real installed module's permission is
discoverable, grantable, and deniable once the module is absent again
after a restart, without ever executing its server entrypoint.
This commit is contained in:
ekklesia
2026-07-24 14:24:50 -05:00
parent d9dd409aa3
commit edd7148aa8
17 changed files with 1205 additions and 46 deletions
@@ -151,6 +151,153 @@ describe("requirePermission", () => {
});
});
describe("requirePermission with module-owned declarations", () => {
// requirePermission has no concept of "Core" versus "module" — it only ever consults whatever
// registry it is given. These declarations are shaped exactly like what
// composePlatformPermissionRegistry would contribute from a real installed module (an id
// namespaced under a module, not `core.*`), proving the shared enforcement mechanism works
// identically for module-owned permissions without any module-specific code path.
const modulePublicPermission = parsePermissionId("calendar.events.list");
const moduleAuthenticatedPermission = parsePermissionId("calendar.events.subscribe");
const moduleRestrictedPermission = parsePermissionId("calendar.events.read");
const moduleRegistry = createPermissionRegistry([
{
baseline: "public",
description: "List public calendar events.",
id: modulePublicPermission,
},
{
baseline: "authenticated",
description: "Subscribe to calendar event updates.",
id: moduleAuthenticatedPermission,
},
{
baseline: "restricted",
description: "Read calendar events.",
id: moduleRestrictedPermission,
},
]);
function buildModuleApp(
permissionId: typeof modulePublicPermission,
options: Partial<AuthorizationMiddlewareOptions> = {},
) {
const runtime = options.runtime ?? fakeRuntime();
const evaluator = options.evaluator ?? fakeEvaluator();
const middlewareOptions: AuthorizationMiddlewareOptions = {
evaluator,
registry: moduleRegistry,
runtime,
};
const app = new Hono();
app.get("/module-protected", requirePermission(middlewareOptions, permissionId), (c) =>
c.json({ ok: true }),
);
return { app, evaluator, runtime };
}
it("resolves a module public permission's trusted baseline and passes it to the evaluator unchanged", async () => {
const evaluator = fakeEvaluator();
const { app } = buildModuleApp(modulePublicPermission, { evaluator });
const response = await app.request("/module-protected");
expect(response.status).toBe(200);
expect(evaluator.authorize).toHaveBeenCalledWith(
expect.objectContaining({ baseline: "public", permission: modulePublicPermission }),
);
});
it("resolves a module authenticated permission's trusted baseline and passes it to the evaluator unchanged", async () => {
const evaluator = fakeEvaluator();
const { app } = buildModuleApp(moduleAuthenticatedPermission, { evaluator });
await app.request("/module-protected");
expect(evaluator.authorize).toHaveBeenCalledWith(
expect.objectContaining({
baseline: "authenticated",
permission: moduleAuthenticatedPermission,
}),
);
});
it("resolves a module restricted permission's trusted baseline and passes it to the evaluator unchanged", async () => {
const evaluator = fakeEvaluator();
const { app } = buildModuleApp(moduleRestrictedPermission, { evaluator });
await app.request("/module-protected");
expect(evaluator.authorize).toHaveBeenCalledWith(
expect.objectContaining({
baseline: "restricted",
permission: moduleRestrictedPermission,
}),
);
});
it("allows an anonymous principal for a module permission the evaluator authorizes", async () => {
const runtime = fakeRuntime({
resolvePrincipal: vi.fn().mockResolvedValue(ANONYMOUS_PRINCIPAL),
});
const { app } = buildModuleApp(modulePublicPermission, { runtime });
const response = await app.request("/module-protected");
expect(response.status).toBe(200);
});
it("allows an authenticated principal for a module permission the evaluator authorizes", async () => {
const runtime = fakeRuntime({
resolvePrincipal: vi.fn().mockResolvedValue(createAuthenticatedPrincipal("user_1")),
});
const { app } = buildModuleApp(moduleRestrictedPermission, { runtime });
const response = await app.request("/module-protected");
expect(response.status).toBe(200);
});
it("denies a module permission the evaluator does not authorize", async () => {
const evaluator = fakeEvaluator({ authorize: vi.fn().mockResolvedValue({ allowed: false }) });
const { app } = buildModuleApp(moduleRestrictedPermission, { evaluator });
const response = await app.request("/module-protected");
expect(response.status).toBe(403);
expect(await response.json()).toEqual({ code: "AUTHORIZATION_DENIED" });
});
it("denies a module permission absent from the registry before ever resolving the principal or consulting the evaluator", async () => {
const runtime = fakeRuntime();
const evaluator = fakeEvaluator();
const absentModulePermission = parsePermissionId("scheduler.jobs.read");
const { app } = buildModuleApp(absentModulePermission, { evaluator, runtime });
const response = await app.request("/module-protected");
expect(response.status).toBe(403);
expect(await response.json()).toEqual({ code: "AUTHORIZATION_DENIED" });
expect(runtime.resolvePrincipal).not.toHaveBeenCalled();
expect(evaluator.authorize).not.toHaveBeenCalled();
});
it("never lets a client-supplied baseline influence the decision for a module permission", async () => {
const evaluator = fakeEvaluator();
const { app } = buildModuleApp(moduleRestrictedPermission, { evaluator });
// A hostile client cannot make a restricted module permission behave as public — there is no
// request field the middleware reads for a baseline override.
await app.request("/module-protected", {
headers: { "x-baseline": "public", "x-permission-baseline": "public" },
});
expect(evaluator.authorize).toHaveBeenCalledWith(
expect.objectContaining({ baseline: "restricted" }),
);
});
});
describe("getAuthorizedPrincipal", () => {
it("throws when called on a route requirePermission never protected", async () => {
const { app } = buildTestApp();