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:
@@ -8,12 +8,13 @@ import {
|
||||
createAuthorizationDrizzleDatabase,
|
||||
createAuthorizationStore,
|
||||
} from "@ekklesia/core/authorization";
|
||||
import { diagnoseEkklesia } from "@ekklesia/core/diagnostics";
|
||||
import {
|
||||
applyModuleMigrations,
|
||||
createPostgresMigrationDatabase,
|
||||
discoverAllMigrations,
|
||||
} from "@ekklesia/core/migrations";
|
||||
import { mkdtemp, rm } from "node:fs/promises";
|
||||
import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { Client, type QueryResultRow } from "pg";
|
||||
import { afterAll, describe, expect, it, vi } from "vitest";
|
||||
@@ -198,10 +199,60 @@ async function applyCoreMigrations(url: string): Promise<void> {
|
||||
}
|
||||
}
|
||||
|
||||
const trackedModulesDirectories: string[] = [];
|
||||
|
||||
async function createFixtureModulesDirectory(): Promise<string> {
|
||||
const directory = await mkdtemp(path.join(tmpdir(), "ekklesia-api-installed-modules-"));
|
||||
trackedModulesDirectories.push(directory);
|
||||
return directory;
|
||||
}
|
||||
|
||||
/** Writes a minimal, structurally valid module fixture straight to disk — real discovery and
|
||||
* composition run against it, nothing hand-built. The server entrypoint throws immediately if
|
||||
* ever imported/executed, so a scenario that completes without that throw firing is direct
|
||||
* evidence permission composition and Doctor never ran module lifecycle code. */
|
||||
async function createFixtureModule(
|
||||
modulesDirectory: string,
|
||||
id: string,
|
||||
manifestOverrides: Record<string, unknown> = {},
|
||||
): Promise<void> {
|
||||
const moduleDirectory = path.join(modulesDirectory, id);
|
||||
const manifest = {
|
||||
manifestVersion: 3,
|
||||
id,
|
||||
name: `${id} module`,
|
||||
version: "0.1.0",
|
||||
compatibility: { platform: "^0.1.0", moduleSdk: "^0.1.0" },
|
||||
permissions: [],
|
||||
entrypoints: { server: "./dist/server/index.js" },
|
||||
...manifestOverrides,
|
||||
};
|
||||
await mkdir(path.join(moduleDirectory, "dist/server"), { recursive: true });
|
||||
await Promise.all([
|
||||
writeFile(
|
||||
path.join(moduleDirectory, "package.json"),
|
||||
JSON.stringify({
|
||||
ekklesia: { layer: "module" },
|
||||
name: `@test/module-${id}`,
|
||||
type: "module",
|
||||
version: "0.1.0",
|
||||
}),
|
||||
),
|
||||
writeFile(path.join(moduleDirectory, "ekklesia.module.json"), JSON.stringify(manifest)),
|
||||
writeFile(
|
||||
path.join(moduleDirectory, "dist/server/index.js"),
|
||||
'throw new Error("permission composition and Doctor must never execute a module server entrypoint");',
|
||||
),
|
||||
]);
|
||||
}
|
||||
|
||||
afterAll(async () => {
|
||||
for (const databaseName of [...trackedDatabases]) {
|
||||
await dropDatabase(databaseName).catch(() => undefined);
|
||||
}
|
||||
for (const directory of trackedModulesDirectories.splice(0)) {
|
||||
await rm(directory, { recursive: true, force: true }).catch(() => undefined);
|
||||
}
|
||||
});
|
||||
|
||||
const identityBaseUrl = "https://identity.example.test";
|
||||
@@ -216,7 +267,10 @@ function apiOrigin(running: RunningApi): string {
|
||||
return `http://127.0.0.1:${address.port}`;
|
||||
}
|
||||
|
||||
async function startMigratedApi(url: string): Promise<RunningApi> {
|
||||
async function startMigratedApi(
|
||||
url: string,
|
||||
modulesDirectoryOverride?: string,
|
||||
): Promise<RunningApi> {
|
||||
const config = createApiRuntimeConfig(
|
||||
{
|
||||
databaseUrl: url,
|
||||
@@ -230,10 +284,15 @@ async function startMigratedApi(url: string): Promise<RunningApi> {
|
||||
},
|
||||
{ environment: "production" },
|
||||
);
|
||||
// A narrow, explicit test-only override: production composition (server.ts's `main`) never
|
||||
// sets this. Better Auth's built-in sign-in/sign-up rate limit (3 requests / 10s) would
|
||||
// otherwise reject this suite's many sequential requests.
|
||||
return startApi(config, { rateLimitOverride: { max: 1000, window: 1 } });
|
||||
// Narrow, explicit test-only overrides: production composition (server.ts's `main`) never sets
|
||||
// either. Better Auth's built-in sign-in/sign-up rate limit (3 requests / 10s) would otherwise
|
||||
// reject this suite's many sequential requests; `modulesDirectoryOverride` lets a scenario point
|
||||
// permission composition at a real, disposable module fixture instead of this repository's own
|
||||
// (empty) `modules/` directory.
|
||||
return startApi(config, {
|
||||
rateLimitOverride: { max: 1000, window: 1 },
|
||||
...(modulesDirectoryOverride === undefined ? {} : { modulesDirectoryOverride }),
|
||||
});
|
||||
}
|
||||
|
||||
function setCookieValue(response: Response): string | undefined {
|
||||
@@ -1147,3 +1206,198 @@ describe.sequential("live API — authorization infrastructure failure is never
|
||||
await running.shutdown().catch(() => undefined);
|
||||
});
|
||||
});
|
||||
|
||||
describe.sequential("live API — installed module permission end-to-end", () => {
|
||||
let database: { name: string; url: string };
|
||||
let modulesDirectory: string;
|
||||
let running: RunningApi;
|
||||
let origin: string;
|
||||
let ownerUserId: string;
|
||||
let ownerCookie: string;
|
||||
let createdGrantId: string;
|
||||
|
||||
const ownerEmail = "[email protected]";
|
||||
const password = "correct horse battery staple";
|
||||
const modulePermission = "calendar.events.read";
|
||||
const absentPermission = "scheduler.jobs.read";
|
||||
|
||||
it("recognizes a real installed module and passes permission composition in Doctor, without executing its server entrypoint", async () => {
|
||||
modulesDirectory = await createFixtureModulesDirectory();
|
||||
await createFixtureModule(modulesDirectory, "calendar", {
|
||||
permissions: [
|
||||
{
|
||||
baseline: "restricted",
|
||||
description: "Read calendar events.",
|
||||
id: modulePermission,
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
const report = await diagnoseEkklesia({
|
||||
moduleDiscovery: {
|
||||
moduleSdkVersion: "0.1.0",
|
||||
modulesDirectory,
|
||||
platformVersion: "0.1.0",
|
||||
},
|
||||
runtimeRange: ">=0.0.0",
|
||||
runtimeVersion: process.versions.node,
|
||||
});
|
||||
|
||||
// Only the module-discovery and permission-composition checks are asserted here — this
|
||||
// fixture's temporary directory has no `core/drizzle` sibling for migrations discovery to
|
||||
// find, which is unrelated to what this scenario proves and would otherwise make the check
|
||||
// fail for a reason that has nothing to do with permission composition.
|
||||
const moduleCheck = report.checks.find((entry) => entry.id === "modules.discovery");
|
||||
const permissionsCheck = report.checks.find((entry) => entry.id === "modules.permissions");
|
||||
expect(moduleCheck).toMatchObject({ status: "pass" });
|
||||
expect(moduleCheck?.details).toEqual(["calendar 0.1.0"]);
|
||||
expect(permissionsCheck).toMatchObject({
|
||||
details: ["2 permissions registered"],
|
||||
status: "pass",
|
||||
});
|
||||
});
|
||||
|
||||
it("starts a freshly migrated API that discovers the fixture module and signs up its eventual owner", async () => {
|
||||
database = await createDisposableDatabase("authz_module");
|
||||
await applyCoreMigrations(database.url);
|
||||
running = await startMigratedApi(database.url, modulesDirectory);
|
||||
origin = apiOrigin(running);
|
||||
|
||||
const ownerSignUp = await signUp(origin, ownerEmail, password);
|
||||
ownerUserId = ownerSignUp.body.user.id;
|
||||
const ownerSignIn = await signIn(origin, ownerEmail, password);
|
||||
expect(ownerSignIn.cookiePair).toBeDefined();
|
||||
ownerCookie = ownerSignIn.cookiePair as string;
|
||||
|
||||
// Existing identity HTTP behavior — sign-up, sign-in, principal resolution — is unaffected by
|
||||
// module permission composition running before it.
|
||||
const { body: principal } = await fetchPrincipal(origin, { cookie: ownerCookie });
|
||||
expect(principal).toEqual({ kind: "authenticated", userId: ownerUserId });
|
||||
});
|
||||
|
||||
it("lets an authorized platform owner create an explicit grant for the installed module's permission, with an atomic audit entry using its declared id", async () => {
|
||||
const { close, db } = createAuthorizationDrizzleDatabase(database.url);
|
||||
try {
|
||||
await bootstrapPlatformOwner(db, { userId: parseEkklesiaUserId(ownerUserId) });
|
||||
} finally {
|
||||
await close();
|
||||
}
|
||||
|
||||
const response = await fetch(`${origin}/api/v1/grants`, {
|
||||
body: JSON.stringify({ permission: modulePermission, subjectUserId: ownerUserId }),
|
||||
headers: {
|
||||
"content-type": "application/json",
|
||||
cookie: ownerCookie,
|
||||
origin: dashboardOrigin,
|
||||
},
|
||||
method: "POST",
|
||||
});
|
||||
const body = (await response.json()) as {
|
||||
grant: { id: string; permission: string; sourceKind: string };
|
||||
};
|
||||
|
||||
expect(response.status).toBe(201);
|
||||
expect(body.grant.permission).toBe(modulePermission);
|
||||
expect(body.grant.sourceKind).toBe("explicit");
|
||||
createdGrantId = body.grant.id;
|
||||
|
||||
const admin = await openAdministrativeClient(database.url);
|
||||
try {
|
||||
const rows = await safeQuery<{ action: string; permission_id: string }>(
|
||||
admin,
|
||||
`select action, permission_id from "ekklesia_core_authorization_audit" where grant_id = $1`,
|
||||
[createdGrantId],
|
||||
);
|
||||
expect(rows).toEqual([{ action: "grant.create", permission_id: modulePermission }]);
|
||||
} finally {
|
||||
await safeEnd(admin);
|
||||
}
|
||||
});
|
||||
|
||||
it("rejects a well-formed permission absent from the composed registry, writing no grant or audit row", async () => {
|
||||
const admin = await openAdministrativeClient(database.url);
|
||||
try {
|
||||
const before = await safeQuery<{ count: string }>(
|
||||
admin,
|
||||
`select count(*)::text as count from "ekklesia_core_grant" where permission_id = $1`,
|
||||
[absentPermission],
|
||||
);
|
||||
expect(before[0]?.count).toBe("0");
|
||||
|
||||
const response = await fetch(`${origin}/api/v1/grants`, {
|
||||
body: JSON.stringify({ permission: absentPermission, subjectUserId: ownerUserId }),
|
||||
headers: {
|
||||
"content-type": "application/json",
|
||||
cookie: ownerCookie,
|
||||
origin: dashboardOrigin,
|
||||
},
|
||||
method: "POST",
|
||||
});
|
||||
expect(response.status).toBe(403);
|
||||
expect(await response.json()).toEqual({ code: "AUTHORIZATION_DENIED" });
|
||||
|
||||
const after = await safeQuery<{ count: string }>(
|
||||
admin,
|
||||
`select count(*)::text as count from "ekklesia_core_grant" where permission_id = $1`,
|
||||
[absentPermission],
|
||||
);
|
||||
const audit = await safeQuery<{ count: string }>(
|
||||
admin,
|
||||
`select count(*)::text as count from "ekklesia_core_authorization_audit" where permission_id = $1`,
|
||||
[absentPermission],
|
||||
);
|
||||
expect(after[0]?.count).toBe("0");
|
||||
expect(audit[0]?.count).toBe("0");
|
||||
} finally {
|
||||
await safeEnd(admin);
|
||||
}
|
||||
});
|
||||
|
||||
it("shuts down cleanly, then restarting with the module absent rejects new grants for its former permission while the historical grant remains listable", async () => {
|
||||
await running.shutdown();
|
||||
const remainingConnections = await activeConnectionCount(database.name);
|
||||
expect(remainingConnections).toBe(0);
|
||||
|
||||
const emptyModulesDirectory = await createFixtureModulesDirectory();
|
||||
running = await startMigratedApi(database.url, emptyModulesDirectory);
|
||||
origin = apiOrigin(running);
|
||||
|
||||
// The owner's existing session survives the restart (sessions live in the database, not the
|
||||
// process), so the same cookie proves ordinary identity behavior is unaffected here too.
|
||||
const listResponse = await fetch(`${origin}/api/v1/grants?userId=${ownerUserId}`, {
|
||||
headers: { cookie: ownerCookie },
|
||||
});
|
||||
const listBody = (await listResponse.json()) as {
|
||||
grants: Array<{ id: string; permission: string }>;
|
||||
};
|
||||
expect(listResponse.status).toBe(200);
|
||||
expect(listBody.grants.some((grant) => grant.id === createdGrantId)).toBe(true);
|
||||
|
||||
const response = await fetch(`${origin}/api/v1/grants`, {
|
||||
body: JSON.stringify({ permission: modulePermission, subjectUserId: ownerUserId }),
|
||||
headers: {
|
||||
"content-type": "application/json",
|
||||
cookie: ownerCookie,
|
||||
origin: dashboardOrigin,
|
||||
},
|
||||
method: "POST",
|
||||
});
|
||||
expect(response.status).toBe(403);
|
||||
expect(await response.json()).toEqual({ code: "AUTHORIZATION_DENIED" });
|
||||
|
||||
const admin = await openAdministrativeClient(database.url);
|
||||
try {
|
||||
const rows = await safeQuery<{ id: string }>(
|
||||
admin,
|
||||
`select id from "ekklesia_core_grant" where id = $1 and revoked_at is null`,
|
||||
[createdGrantId],
|
||||
);
|
||||
expect(rows).toHaveLength(1);
|
||||
} finally {
|
||||
await safeEnd(admin);
|
||||
}
|
||||
|
||||
await running.shutdown();
|
||||
await dropDatabase(database.name);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,5 +1,10 @@
|
||||
import { ANONYMOUS_PRINCIPAL, createAuthenticatedPrincipal } from "@ekklesia/contracts";
|
||||
import type { AuthorizationEvaluator, AuthorizationStore } from "@ekklesia/core/authorization";
|
||||
import {
|
||||
type AuthorizationEvaluator,
|
||||
type AuthorizationStore,
|
||||
CORE_PERMISSION_REGISTRY,
|
||||
type PermissionRegistry,
|
||||
} from "@ekklesia/core/authorization";
|
||||
import type { EkklesiaIdentityRuntime } from "@ekklesia/core/identity";
|
||||
import { IdentityRuntimeError } from "@ekklesia/core/identity";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
@@ -17,9 +22,13 @@ function fakeRuntime(overrides: Partial<EkklesiaIdentityRuntime> = {}): Ekklesia
|
||||
}
|
||||
|
||||
/** A fully stubbed authorization dependency, denying everything by default — tests that need a
|
||||
* specific decision or store behavior override the relevant method explicitly. */
|
||||
* specific decision or store behavior override the relevant method explicitly. The registry
|
||||
* defaults to Core's own (containing `core.authorization.grants.manage`, exactly what the
|
||||
* mounted grants routes require) rather than an app-composed one — these tests exercise
|
||||
* `createApiApp`'s wiring, not permission composition itself. */
|
||||
function fakeAuthorization(overrides: {
|
||||
readonly evaluator?: Partial<AuthorizationEvaluator>;
|
||||
readonly registry?: PermissionRegistry;
|
||||
readonly store?: Partial<AuthorizationStore>;
|
||||
}): CreateApiAppAuthorizationOptions {
|
||||
const evaluator: AuthorizationEvaluator = {
|
||||
@@ -36,7 +45,7 @@ function fakeAuthorization(overrides: {
|
||||
revokePlatformOwner: vi.fn(),
|
||||
...overrides.store,
|
||||
};
|
||||
return { evaluator, store };
|
||||
return { evaluator, registry: overrides.registry ?? CORE_PERMISSION_REGISTRY, store };
|
||||
}
|
||||
|
||||
describe("Ekklesia API Hono application", () => {
|
||||
@@ -253,6 +262,32 @@ describe("Ekklesia API Hono application", () => {
|
||||
expect(evaluatorAuthorize).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("uses exactly the injected registry, never an internal Core-only fallback", async () => {
|
||||
// An evaluator that would allow anything, paired with a registry that does not register
|
||||
// core.authorization.grants.manage at all — if createApiApp silently fell back to some
|
||||
// internal registry containing it, this request would reach the evaluator and succeed
|
||||
// (empty grant list, 200). It must instead fail closed on the registry lookup itself.
|
||||
const evaluatorAuthorize = vi.fn().mockResolvedValue({ allowed: true });
|
||||
const emptyRegistry: PermissionRegistry = {
|
||||
declarations: [],
|
||||
get: () => undefined,
|
||||
has: () => false,
|
||||
};
|
||||
const app = createApiApp({
|
||||
authorization: fakeAuthorization({
|
||||
evaluator: { authorize: evaluatorAuthorize },
|
||||
registry: emptyRegistry,
|
||||
}),
|
||||
runtime: fakeRuntime(),
|
||||
trustedOrigins: [trustedOrigin],
|
||||
});
|
||||
|
||||
const response = await app.request("/api/v1/grants?userId=user_123");
|
||||
|
||||
expect(response.status).toBe(403);
|
||||
expect(evaluatorAuthorize).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("applies the same CORS policy to /api/v1/grants as the rest of /api/v1/*", async () => {
|
||||
const app = createApiApp({
|
||||
authorization: fakeAuthorization({}),
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const poolConstructor = vi.hoisted(() => vi.fn());
|
||||
const betterAuthMock = vi.hoisted(() => vi.fn());
|
||||
@@ -11,6 +14,13 @@ vi.mock("better-auth", () => ({ betterAuth: betterAuthMock }));
|
||||
vi.mock("better-auth/adapters/drizzle", () => ({ drizzleAdapter: drizzleAdapterMock }));
|
||||
vi.mock("@hono/node-server", () => ({ serve: serveMock }));
|
||||
|
||||
import { parseModuleManifest } from "@ekklesia/contracts";
|
||||
import {
|
||||
type DiscoveredModule,
|
||||
ModuleDiscoveryError,
|
||||
ModulePermissionCompositionError,
|
||||
} from "@ekklesia/core/modules";
|
||||
import { PermissionRegistryError } from "@ekklesia/core/authorization";
|
||||
import { createApiRuntimeConfig } from "../src/config.js";
|
||||
import { installShutdownSignalHandlers, startApi } from "../src/server.js";
|
||||
|
||||
@@ -30,6 +40,84 @@ function validConfig() {
|
||||
);
|
||||
}
|
||||
|
||||
const temporaryDirectories: string[] = [];
|
||||
|
||||
async function createTemporaryModulesDirectory(): Promise<string> {
|
||||
const directory = await mkdtemp(path.join(tmpdir(), "ekklesia-api-modules-"));
|
||||
temporaryDirectories.push(directory);
|
||||
return directory;
|
||||
}
|
||||
|
||||
/** Writes a minimal, structurally valid module fixture (package.json + ekklesia.module.json +
|
||||
* server entrypoint) directly to disk — real discovery, not a hand-built double. The server
|
||||
* entrypoint throws immediately if ever imported, so a test that reaches a successful assertion
|
||||
* without that throw firing is direct evidence permission composition never executed it. */
|
||||
async function createFixtureModule(
|
||||
modulesDirectory: string,
|
||||
id: string,
|
||||
manifestOverrides: Record<string, unknown> = {},
|
||||
): Promise<void> {
|
||||
const moduleDirectory = path.join(modulesDirectory, id);
|
||||
const manifest = {
|
||||
manifestVersion: 3,
|
||||
id,
|
||||
name: `${id} module`,
|
||||
version: "0.1.0",
|
||||
compatibility: { platform: "^0.1.0", moduleSdk: "^0.1.0" },
|
||||
permissions: [],
|
||||
entrypoints: { server: "./dist/server/index.js" },
|
||||
...manifestOverrides,
|
||||
};
|
||||
await mkdir(path.join(moduleDirectory, "dist/server"), { recursive: true });
|
||||
await Promise.all([
|
||||
writeFile(
|
||||
path.join(moduleDirectory, "package.json"),
|
||||
JSON.stringify({
|
||||
ekklesia: { layer: "module" },
|
||||
name: `@test/module-${id}`,
|
||||
type: "module",
|
||||
version: "0.1.0",
|
||||
}),
|
||||
),
|
||||
writeFile(path.join(moduleDirectory, "ekklesia.module.json"), JSON.stringify(manifest)),
|
||||
writeFile(
|
||||
path.join(moduleDirectory, "dist/server/index.js"),
|
||||
'throw new Error("permission composition must never execute a module server entrypoint");',
|
||||
),
|
||||
]);
|
||||
}
|
||||
|
||||
/** A minimal, in-memory `DiscoveredModule` double built from a real, validated manifest — used
|
||||
* only to reach `composePlatformPermissionRegistry`'s own duplicate-detection failure, which is
|
||||
* unreachable through real filesystem discovery (module ids are unique and every permission id is
|
||||
* namespaced by its own module's id, so no two genuinely discovered modules can ever collide). */
|
||||
function fakeDiscoveredModule(
|
||||
id: string,
|
||||
permissions: ReadonlyArray<{
|
||||
id: string;
|
||||
baseline: "public" | "authenticated" | "restricted";
|
||||
description: string;
|
||||
}>,
|
||||
): DiscoveredModule {
|
||||
const manifest = parseModuleManifest({
|
||||
capabilities: [],
|
||||
compatibility: { moduleSdk: "^0.1.0", platform: "^0.1.0" },
|
||||
entrypoints: { server: "./dist/does-not-exist/index.js" },
|
||||
id,
|
||||
manifestVersion: 3,
|
||||
name: `${id} module`,
|
||||
permissions,
|
||||
version: "0.1.0",
|
||||
});
|
||||
return {
|
||||
directory: `/modules/${id}`,
|
||||
entrypoints: { server: `/modules/${id}/dist/does-not-exist/index.js` },
|
||||
manifest,
|
||||
manifestPath: `/modules/${id}/ekklesia.module.json`,
|
||||
packageName: `@test/${id}`,
|
||||
};
|
||||
}
|
||||
|
||||
/** A minimal fake `ServerType`: enough of Node's `http.Server` shape for `bindServer`/`shutdown`
|
||||
* to drive without a real socket. `close` and `once` are spies so tests can assert call counts;
|
||||
* `triggerError` simulates the server's own `'error'` event (e.g. a bind failure). */
|
||||
@@ -285,3 +373,148 @@ describe("Ekklesia API shutdown lifecycle", () => {
|
||||
restore();
|
||||
});
|
||||
});
|
||||
|
||||
describe("Ekklesia API module permission composition at startup", () => {
|
||||
afterEach(async () => {
|
||||
await Promise.all(
|
||||
temporaryDirectories.splice(0).map((directory) => rm(directory, { recursive: true })),
|
||||
);
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
poolConstructor.mockReset();
|
||||
betterAuthMock.mockReset();
|
||||
drizzleAdapterMock.mockClear();
|
||||
serveMock.mockReset();
|
||||
});
|
||||
|
||||
it("discovers and composes permissions before constructing the database pool, Better Auth, or the HTTP server", async () => {
|
||||
const modulesDirectory = await createTemporaryModulesDirectory();
|
||||
// An incompatible platform version fails discovery itself (MODULE_PLATFORM_INCOMPATIBLE),
|
||||
// before permission composition — and, since composition runs before any pool exists, before
|
||||
// any pool, Better Auth instance, or HTTP server could ever be constructed.
|
||||
await createFixtureModule(modulesDirectory, "incompatible", {
|
||||
compatibility: { moduleSdk: "^0.1.0", platform: ">=99.0.0" },
|
||||
});
|
||||
|
||||
await expect(
|
||||
startApi(validConfig(), { modulesDirectoryOverride: modulesDirectory }),
|
||||
).rejects.toBeInstanceOf(ModuleDiscoveryError);
|
||||
|
||||
expect(poolConstructor).not.toHaveBeenCalled();
|
||||
expect(betterAuthMock).not.toHaveBeenCalled();
|
||||
expect(serveMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("fails startup when a module claims the reserved core.* permission namespace, creating no pool, Better Auth instance, or server", async () => {
|
||||
const modulesDirectory = await createTemporaryModulesDirectory();
|
||||
// Only a module whose own id is literally "core" can produce a "core."-prefixed permission
|
||||
// that still passes the manifest's own module-namespace check.
|
||||
await createFixtureModule(modulesDirectory, "core", {
|
||||
permissions: [
|
||||
{ baseline: "restricted", description: "Not really Core's.", id: "core.rogue.permission" },
|
||||
],
|
||||
});
|
||||
|
||||
let captured: unknown;
|
||||
try {
|
||||
await startApi(validConfig(), { modulesDirectoryOverride: modulesDirectory });
|
||||
} catch (error) {
|
||||
captured = error;
|
||||
}
|
||||
|
||||
expect(captured).toBeInstanceOf(ModulePermissionCompositionError);
|
||||
expect(captured).toMatchObject({ code: "MODULE_PERMISSION_RESERVED_NAMESPACE" });
|
||||
expect(poolConstructor).not.toHaveBeenCalled();
|
||||
expect(betterAuthMock).not.toHaveBeenCalled();
|
||||
expect(serveMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("fails startup on a duplicate permission declaration, creating no pool, Better Auth instance, or server", async () => {
|
||||
const first = fakeDiscoveredModule("calendar", [
|
||||
{ baseline: "restricted", description: "Read events.", id: "calendar.events.read" },
|
||||
]);
|
||||
const second = fakeDiscoveredModule("calendar", [
|
||||
{ baseline: "public", description: "Also read events.", id: "calendar.events.read" },
|
||||
]);
|
||||
|
||||
let captured: unknown;
|
||||
try {
|
||||
await startApi(validConfig(), { discoveredModulesOverride: [first, second] });
|
||||
} catch (error) {
|
||||
captured = error;
|
||||
}
|
||||
|
||||
expect(captured).toBeInstanceOf(PermissionRegistryError);
|
||||
expect(captured).toMatchObject({ code: "PERMISSION_REGISTRY_DUPLICATE_DECLARATION" });
|
||||
expect(poolConstructor).not.toHaveBeenCalled();
|
||||
expect(betterAuthMock).not.toHaveBeenCalled();
|
||||
expect(serveMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("keeps a reserved-namespace failure and a generic duplicate-declaration failure distinguishable", async () => {
|
||||
const modulesDirectory = await createTemporaryModulesDirectory();
|
||||
await createFixtureModule(modulesDirectory, "core", {
|
||||
permissions: [
|
||||
{
|
||||
baseline: "restricted",
|
||||
description: "Attempting to shadow Core's own permission.",
|
||||
id: "core.authorization.grants.manage",
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
let reservedNamespaceError: unknown;
|
||||
try {
|
||||
await startApi(validConfig(), { modulesDirectoryOverride: modulesDirectory });
|
||||
} catch (error) {
|
||||
reservedNamespaceError = error;
|
||||
}
|
||||
|
||||
const duplicateModule = fakeDiscoveredModule("calendar", [
|
||||
{ baseline: "restricted", description: "Read events.", id: "calendar.events.read" },
|
||||
]);
|
||||
const duplicateModuleAgain = fakeDiscoveredModule("calendar", [
|
||||
{ baseline: "restricted", description: "Read events, again.", id: "calendar.events.read" },
|
||||
]);
|
||||
let duplicateError: unknown;
|
||||
try {
|
||||
await startApi(validConfig(), {
|
||||
discoveredModulesOverride: [duplicateModule, duplicateModuleAgain],
|
||||
});
|
||||
} catch (error) {
|
||||
duplicateError = error;
|
||||
}
|
||||
|
||||
// Even though the first scenario's module attempted to exactly collide with an existing
|
||||
// Core-owned permission id, it is reported as a reserved-namespace violation, never as a
|
||||
// generic duplicate — the two failure families never overlap.
|
||||
expect(reservedNamespaceError).toBeInstanceOf(ModulePermissionCompositionError);
|
||||
expect(reservedNamespaceError).not.toBeInstanceOf(PermissionRegistryError);
|
||||
expect(duplicateError).toBeInstanceOf(PermissionRegistryError);
|
||||
expect(duplicateError).not.toBeInstanceOf(ModulePermissionCompositionError);
|
||||
});
|
||||
|
||||
it("still constructs exactly one pool and succeeds when zero modules are installed", async () => {
|
||||
const modulesDirectory = await createTemporaryModulesDirectory();
|
||||
const poolEnd = vi.fn().mockResolvedValue(undefined);
|
||||
poolConstructor.mockImplementation(function fakePool() {
|
||||
return { end: poolEnd, on: vi.fn() };
|
||||
});
|
||||
betterAuthMock.mockReturnValue({ api: { getSession: vi.fn() }, handler: vi.fn() });
|
||||
mockSuccessfulServe();
|
||||
|
||||
const running = await startApi(validConfig(), { modulesDirectoryOverride: modulesDirectory });
|
||||
|
||||
expect(poolConstructor).toHaveBeenCalledTimes(1);
|
||||
await running.shutdown();
|
||||
expect(poolEnd).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("does not perform module discovery merely by importing the platform-permissions module", async () => {
|
||||
const module = await import("../src/platform-permissions.js");
|
||||
|
||||
expect(typeof module.composeStartupPermissionRegistry).toBe("function");
|
||||
expect(poolConstructor).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user