feat: mount module HTTP routes

Phase 5B, pass 2: production API mounting, authorization enforcement,
and module-runtime lifecycle integration.

apps/api now discovers the installed module inventory exactly once
(prepareStartupModuleInventory), composes the platform permission
registry from it, starts the module runtime from that same discovered
list (startDiscoveredModuleRuntime, never rediscovering), and mounts
StartedModuleRuntime's published routes under
/api/v1/modules/<module-id> via a new apps/api-owned Hono adapter
(module-http-routes.ts). Every module route is protected by the
existing requirePermission middleware against the composed registry,
state-changing methods additionally require a trusted Origin, OPTIONS
remains entirely platform-owned, and a handler that throws, rejects,
or returns a non-Response becomes a fixed, sanitized
500 MODULE_HANDLER_FAILED. Module-supplied CORS headers are stripped
and every module response is forced to Cache-Control: no-store with
Vary: Origin, Cookie. RunningApi shutdown now stops the module runtime
between draining the HTTP server and closing the shared pool, and
every startup failure path stops the runtime and/or closes the pool
before propagating, without masking the original failure.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
This commit is contained in:
ekklesia
2026-07-24 19:16:20 -05:00
co-authored by Claude Sonnet 5
parent e296e083ec
commit dfaf324a65
12 changed files with 1930 additions and 123 deletions
+133 -8
View File
@@ -200,6 +200,7 @@ async function applyCoreMigrations(url: string): Promise<void> {
}
const trackedModulesDirectories: string[] = [];
const eventSymbols: symbol[] = [];
async function createFixtureModulesDirectory(): Promise<string> {
const directory = await mkdtemp(path.join(tmpdir(), "ekklesia-api-installed-modules-"));
@@ -207,13 +208,31 @@ async function createFixtureModulesDirectory(): Promise<string> {
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. */
/** A dynamically imported module fixture cannot close over this test file's local variables, so
* lifecycle markers cross that boundary through a `globalThis` symbol instead (same technique as
* `core/tests/module-runtime.test.ts`). */
function createEventRecorder(): { events: string[]; expression: string } {
const key = `ekklesia.api.integration.test.${eventSymbols.length}.${Date.now()}.${Math.random()}`;
const symbol = Symbol.for(key);
const events: string[] = [];
(globalThis as unknown as Record<PropertyKey, unknown>)[symbol] = events;
eventSymbols.push(symbol);
return { events, expression: `globalThis[Symbol.for(${JSON.stringify(key)})]` };
}
/** Writes a minimal, structurally valid module fixture straight to disk — real discovery,
* composition, and (where a scenario actually starts the API) real module runtime execution all
* run against it, nothing hand-built. Register/start/stop push markers onto `recorder.events`
* instead of throwing, so both "Doctor/composition never executed this" (an empty recorder) and
* "startApi actually imported, registered, and started this" (a populated recorder) can be proven
* against the exact same fixture. When declared with the `calendar.events.read` permission, the
* module also registers a restricted `GET /events/:eventId` route and a restricted, state-changing
* `POST /events` route against that same permission, so the full HTTP mounting/enforcement chain
* can be exercised live. */
async function createFixtureModule(
modulesDirectory: string,
id: string,
recorder: { expression: string },
manifestOverrides: Record<string, unknown> = {},
): Promise<void> {
const moduleDirectory = path.join(modulesDirectory, id);
@@ -227,6 +246,9 @@ async function createFixtureModule(
entrypoints: { server: "./dist/server/index.js" },
...manifestOverrides,
};
const declaresCalendarRead = (manifest.permissions as ReadonlyArray<{ id: string }>).some(
(declaration) => declaration.id === "calendar.events.read",
);
await mkdir(path.join(moduleDirectory, "dist/server"), { recursive: true });
await Promise.all([
writeFile(
@@ -241,7 +263,39 @@ async function createFixtureModule(
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");',
`export default {
id: ${JSON.stringify(id)},
version: "0.1.0",
register({ http }) {
${recorder.expression}.push(${JSON.stringify(`${id}:register`)});
${
declaresCalendarRead
? `http.route({
method: "GET",
path: "/events/:eventId",
permission: "calendar.events.read",
async handler(request, context) {
return Response.json({ eventId: context.params.eventId, principal: context.principal });
},
});
http.route({
method: "POST",
path: "/events",
permission: "calendar.events.read",
async handler(request, context) {
return Response.json({ created: true, principal: context.principal }, { status: 201 });
},
});`
: ""
}
},
start() {
${recorder.expression}.push(${JSON.stringify(`${id}:start`)});
},
stop() {
${recorder.expression}.push(${JSON.stringify(`${id}:stop`)});
},
};`,
),
]);
}
@@ -253,6 +307,10 @@ afterAll(async () => {
for (const directory of trackedModulesDirectories.splice(0)) {
await rm(directory, { recursive: true, force: true }).catch(() => undefined);
}
const globalValues = globalThis as unknown as Record<PropertyKey, unknown>;
for (const symbol of eventSymbols.splice(0)) {
delete globalValues[symbol];
}
});
const identityBaseUrl = "https://identity.example.test";
@@ -1222,10 +1280,11 @@ describe.sequential("live API — installed module permission end-to-end", () =>
const password = "correct horse battery staple";
const modulePermission = "calendar.events.read";
const absentPermission = "scheduler.jobs.read";
const recorder = createEventRecorder();
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", {
await createFixtureModule(modulesDirectory, "calendar", recorder, {
permissions: [
{
baseline: "restricted",
@@ -1257,14 +1316,21 @@ describe.sequential("live API — installed module permission end-to-end", () =>
details: ["2 permissions registered"],
status: "pass",
});
// Doctor and permission composition read only the manifest — the fixture's register/start
// markers must remain entirely unset.
expect(recorder.events).toEqual([]);
});
it("starts a freshly migrated API that discovers the fixture module and signs up its eventual owner", async () => {
it("starts a freshly migrated API that discovers the fixture module, imports and starts its runtime exactly once, and mounts its route", async () => {
database = await createDisposableDatabase("authz_module");
await applyCoreMigrations(database.url);
running = await startMigratedApi(database.url, modulesDirectory);
origin = apiOrigin(running);
// Unlike Doctor above, a successful production startup does deliberately import, register,
// and start the module's runtime — exactly once each.
expect(recorder.events).toEqual(["calendar:register", "calendar:start"]);
const ownerSignUp = await signUp(origin, ownerEmail, password);
ownerUserId = ownerSignUp.body.user.id;
const ownerSignIn = await signIn(origin, ownerEmail, password);
@@ -1316,6 +1382,56 @@ describe.sequential("live API — installed module permission end-to-end", () =>
}
});
it("denies the module's own mounted route to an anonymous caller, then serves it to the newly granted owner with the decoded path parameter and authenticated principal", async () => {
const anonymousResponse = await fetch(`${origin}/api/v1/modules/calendar/events/evt-42`);
expect(anonymousResponse.status).toBe(403);
expect(await anonymousResponse.json()).toEqual({ code: "AUTHORIZATION_DENIED" });
const grantedResponse = await fetch(`${origin}/api/v1/modules/calendar/events/evt-42`, {
headers: { cookie: ownerCookie },
});
expect(grantedResponse.status).toBe(200);
const body = (await grantedResponse.json()) as {
eventId: string;
principal: { kind: string; userId: string };
};
expect(body.eventId).toBe("evt-42");
expect(body.principal).toEqual({ kind: "authenticated", userId: ownerUserId });
});
it("requires a trusted Origin for the module's own state-changing route, exactly like the platform's own mutation routes", async () => {
const noOriginResponse = await fetch(`${origin}/api/v1/modules/calendar/events`, {
body: JSON.stringify({}),
headers: { "content-type": "application/json", cookie: ownerCookie },
method: "POST",
});
expect(noOriginResponse.status).toBe(403);
expect(await noOriginResponse.json()).toEqual({ code: "UNTRUSTED_ORIGIN" });
const untrustedResponse = await fetch(`${origin}/api/v1/modules/calendar/events`, {
body: JSON.stringify({}),
headers: {
"content-type": "application/json",
cookie: ownerCookie,
origin: untrustedOrigin,
},
method: "POST",
});
expect(untrustedResponse.status).toBe(403);
const trustedResponse = await fetch(`${origin}/api/v1/modules/calendar/events`, {
body: JSON.stringify({}),
headers: {
"content-type": "application/json",
cookie: ownerCookie,
origin: dashboardOrigin,
},
method: "POST",
});
expect(trustedResponse.status).toBe(201);
expect(await trustedResponse.json()).toMatchObject({ created: true });
});
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 {
@@ -1355,15 +1471,24 @@ describe.sequential("live API — installed module permission end-to-end", () =>
}
});
it("shuts down cleanly, then restarting with the module absent rejects new grants for its former permission while the historical grant remains listable", async () => {
it("shuts down cleanly, then restarting with the module absent rejects new grants for its former permission, returns NOT_FOUND for its former route, while the historical grant remains listable", async () => {
await running.shutdown();
const remainingConnections = await activeConnectionCount(database.name);
expect(remainingConnections).toBe(0);
// Exactly one stop, matching the exactly-one register/start already asserted above.
expect(recorder.events.filter((event) => event === "calendar:stop")).toHaveLength(1);
const emptyModulesDirectory = await createFixtureModulesDirectory();
running = await startMigratedApi(database.url, emptyModulesDirectory);
origin = apiOrigin(running);
// The module's own route is unmounted along with the module itself.
const removedRouteResponse = await fetch(`${origin}/api/v1/modules/calendar/events/evt-42`, {
headers: { cookie: ownerCookie },
});
expect(removedRouteResponse.status).toBe(404);
expect(await removedRouteResponse.json()).toEqual({ code: "NOT_FOUND" });
// 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}`, {