From dbc6916c64df47255eaacc401bbfe22c727890ff Mon Sep 17 00:00:00 2001 From: Nikhil Unni Date: Tue, 1 Dec 2026 11:59:40 -0800 Subject: [PATCH 1/3] fix(orchestrator): reject empty broker secrets, bound file uploads, and remove client casts --- .../src/__tests__/admin-guard.test.ts | 47 +++++++++++++++++++ .../src/__tests__/config-broker.test.ts | 36 ++++++++++++++ .../connection-credential-broker.test.ts | 14 ++++++ .../src/__tests__/session-files.route.test.ts | 36 ++++++++++++++ orchestrator/src/auth/types.ts | 4 ++ orchestrator/src/config.ts | 18 +++---- .../src/control-plane/artifact-fetch.ts | 2 +- orchestrator/src/integrations/slack-policy.ts | 2 +- orchestrator/src/routes/admin.ts | 25 ++-------- orchestrator/src/routes/artifacts.ts | 4 +- .../routes/connection-credential-broker.ts | 6 +-- orchestrator/src/routes/connector-logo.ts | 3 +- orchestrator/src/routes/events.ts | 4 +- orchestrator/src/routes/guard.ts | 20 ++++++-- orchestrator/src/routes/ide.ts | 8 +--- orchestrator/src/routes/integration-oauth.ts | 21 ++------- orchestrator/src/routes/integration-op.ts | 14 ++---- orchestrator/src/routes/me.ts | 2 +- orchestrator/src/routes/oidc-key-admin.ts | 26 ++-------- orchestrator/src/routes/preview-proxy.ts | 4 +- orchestrator/src/routes/preview-ws.ts | 4 +- orchestrator/src/routes/reviews-dispatch.ts | 5 +- orchestrator/src/routes/session-files.ts | 22 +++++++-- orchestrator/src/routes/shell.ts | 4 +- orchestrator/src/routes/spec-events.ts | 2 +- orchestrator/src/routes/vnc.ts | 4 +- orchestrator/src/rpc/api-key.ts | 7 +-- orchestrator/src/rpc/artifacts.ts | 7 +-- orchestrator/src/rpc/automations.ts | 7 ++- orchestrator/src/rpc/image-guard.ts | 2 +- orchestrator/src/rpc/integration.ts | 9 ++-- orchestrator/src/rpc/mint.ts | 7 ++- orchestrator/src/rpc/model-routers.ts | 2 +- orchestrator/src/rpc/mount-catalog.ts | 7 ++- orchestrator/src/rpc/org-secret.ts | 7 ++- orchestrator/src/rpc/papercuts.ts | 7 +-- orchestrator/src/rpc/passthrough.ts | 7 +-- orchestrator/src/rpc/pr-refs.ts | 7 +-- orchestrator/src/rpc/profiles.ts | 13 +++-- orchestrator/src/rpc/require.ts | 8 +--- orchestrator/src/rpc/reviews.ts | 7 +-- orchestrator/src/rpc/tasks.ts | 12 ++--- orchestrator/src/skills/catalog.ts | 2 +- orchestrator/src/tools/coordination.ts | 3 +- 44 files changed, 262 insertions(+), 196 deletions(-) create mode 100644 orchestrator/src/__tests__/admin-guard.test.ts create mode 100644 orchestrator/src/__tests__/config-broker.test.ts create mode 100644 orchestrator/src/auth/types.ts diff --git a/orchestrator/src/__tests__/admin-guard.test.ts b/orchestrator/src/__tests__/admin-guard.test.ts new file mode 100644 index 000000000..c2705ce76 --- /dev/null +++ b/orchestrator/src/__tests__/admin-guard.test.ts @@ -0,0 +1,47 @@ +import { describe, expect, test } from "bun:test"; +import { requireAdmin, type GetSession } from "../routes/guard.ts"; +import { makeAdminRoute } from "../routes/admin.ts"; +import { makeIntegrationOpRoute } from "../routes/integration-op.ts"; +import { makeIntegrationOauthRoute } from "../routes/integration-oauth.ts"; +import { makeOidcKeyAdminRoute } from "../routes/oidc-key-admin.ts"; + +describe("HTTP admin guard", () => { + test("returns the admin identity and forwards the headers", async () => { + const headers = new Headers({ authorization: "Bearer test" }); + expect(await requireAdmin(headers, async (actual) => { + expect(actual).toBe(headers); + return { user: { id: "admin-1", role: "admin" } }; + })).toEqual({ id: "admin-1", role: "admin" }); + }); + + test.each([undefined, null, "user", "Admin", "unknown"])( + "rejects role %p", + async (role) => { + await expect(requireAdmin(new Headers(), async () => ({ user: { id: "user-1", role } }))) + .rejects.toMatchObject({ status: 403, message: "admin required" }); + }, + ); + + const routes = [ + { make: makeAdminRoute, path: "/api/v1/admin/sessions/session-1/pause", method: "POST" }, + { make: makeAdminRoute, path: "/api/v1/admin/sessions/session-1/resume", method: "POST" }, + { make: makeIntegrationOpRoute, path: "/api/v1/integrations/example/run-op", method: "POST" }, + { make: makeIntegrationOauthRoute, path: "/api/v1/integrations/example/oauth/authorize", method: "GET" }, + { make: makeIntegrationOauthRoute, path: "/api/v1/integrations/example/oauth/grant", method: "POST" }, + { make: makeOidcKeyAdminRoute, path: "/api/v1/admin/integrations/oidc/rotate", method: "POST" }, + ]; + for (const { make, path, method } of routes) { + test(`${method} ${path} requires an admin before work starts`, async () => { + const anonymous: GetSession = async () => null; + const member: GetSession = async () => ({ user: { id: "user-1", role: "user" } }); + for (const [getSession, status, message] of [ + [anonymous, 401, "unauthenticated"], + [member, 403, "admin required"], + ] as const) { + const response = await make({ getSession }).request(path, { method }); + expect(response.status).toBe(status); + expect(await response.text()).toBe(message); + } + }); + } +}); diff --git a/orchestrator/src/__tests__/config-broker.test.ts b/orchestrator/src/__tests__/config-broker.test.ts new file mode 100644 index 000000000..eea5a457c --- /dev/null +++ b/orchestrator/src/__tests__/config-broker.test.ts @@ -0,0 +1,36 @@ +import { describe, expect, spyOn, test } from "bun:test"; +import { loadConfig } from "../config.ts"; +import { log } from "../log.ts"; + +const env = { + NODE_ENV: "production", + CONTROL_PLANE_BEARER: "control-secret", + ORCHESTRATOR_DATABASE_URL: "postgres://localhost/test", + ENGRAM_KEK_MASTER_KEY: Buffer.alloc(32).toString("base64"), + BETTER_AUTH_SECRET: "test-auth-secret", +}; + +describe("broker bearer configuration", () => { + test.each([undefined, ""])("preserves the shared bearer fallback for %p", (bearer) => { + const warn = spyOn(log, "warn").mockImplementation(() => {}); + try { + expect(loadConfig({ ...env, CONNECTION_BROKER_BEARER: bearer }).connectionBrokerBearer) + .toBe("control-secret"); + expect(warn).toHaveBeenCalledTimes(1); + expect(warn.mock.calls[0]?.[0]).toContain("CONNECTION_BROKER_BEARER is unset"); + } finally { + warn.mockRestore(); + } + }); + + test("uses the dedicated bearer without a fallback warning", () => { + const warn = spyOn(log, "warn").mockImplementation(() => {}); + try { + expect(loadConfig({ ...env, CONNECTION_BROKER_BEARER: "broker-secret" }).connectionBrokerBearer) + .toBe("broker-secret"); + expect(warn).not.toHaveBeenCalled(); + } finally { + warn.mockRestore(); + } + }); +}); diff --git a/orchestrator/src/__tests__/connection-credential-broker.test.ts b/orchestrator/src/__tests__/connection-credential-broker.test.ts index 249ff08e6..e78d40323 100644 --- a/orchestrator/src/__tests__/connection-credential-broker.test.ts +++ b/orchestrator/src/__tests__/connection-credential-broker.test.ts @@ -3,6 +3,7 @@ import { describe, expect, test } from "bun:test"; import type { GoogleAccessToken, WifIdentity } from "../integrations/google-wif.ts"; import { integrationSnapshotHash } from "../integrations/grants.ts"; import { + bearerMatches, makeConnectionCredentialBrokerRoute, type CredentialBrokerSessionStore, } from "../routes/connection-credential-broker.ts"; @@ -229,3 +230,16 @@ describe("named-connection credential broker", () => { expect(exchanges).toBe(0); }); }); + +describe("broker bearer comparison", () => { + test.each([undefined, "", "Bearer "])("rejects an empty secret with header %p", (header) => { + expect(bearerMatches(header, "")).toBe(false); + }); + + test("requires the exact bearer", () => { + expect(bearerMatches("Bearer secret", "secret")).toBe(true); + for (const header of [undefined, "", "secret", "Basic secret", "Bearer secreT", "Bearer secret "]) { + expect(bearerMatches(header, "secret")).toBe(false); + } + }); +}); diff --git a/orchestrator/src/__tests__/session-files.route.test.ts b/orchestrator/src/__tests__/session-files.route.test.ts index 5e8ee6c8c..c2d06e511 100644 --- a/orchestrator/src/__tests__/session-files.route.test.ts +++ b/orchestrator/src/__tests__/session-files.route.test.ts @@ -90,6 +90,42 @@ describe("session file routes", () => { expect(called).toBeFalse(); }); + test.each(["x-upload-size", "content-length"])( + "cancels an oversized stream despite a small %s header", + async (header) => { + const chunk = new Uint8Array(1024 * 1024); + let cancelled = false; + let forwardedBytes = 0; + const body = new ReadableStream({ + pull(controller) { controller.enqueue(chunk); }, + cancel() { cancelled = true; }, + }); + const client: SessionFileClient = { + async writeFile(input) { + // A transport can wrap the generator error before the route sees it. + try { + for await (const message of input) { + if (message.frame.case === "chunk") forwardedBytes += message.frame.value.byteLength; + } + } catch { + throw new Error("transport failed"); + } + throw new Error("must stop before completion"); + }, + async *readFile() {}, + }; + const response = await app(client).request( + `/api/v1/sessions/${sessionId}/files?path=${encodeURIComponent(path)}`, + { method: "POST", body, headers: { [header]: "1" } }, + ); + expect(response.status).toBe(413); + expect(await response.json()).toEqual({ error: `file exceeds ${512 * 1024 * 1024} bytes` }); + expect(forwardedBytes).toBe(512 * 1024 * 1024); + expect(cancelled).toBe(true); + expect(body.locked).toBe(false); + }, + ); + test("streams authenticated downloads with verified metadata headers", async () => { const client: SessionFileClient = { async writeFile() { diff --git a/orchestrator/src/auth/types.ts b/orchestrator/src/auth/types.ts new file mode 100644 index 000000000..e9d54a7ac --- /dev/null +++ b/orchestrator/src/auth/types.ts @@ -0,0 +1,4 @@ +/** Session identity shared by HTTP and RPC authorization. */ +export type GetSession = (headers: Headers) => Promise<{ + user: { id: string; role?: string | null; email?: string | null; name?: string | null }; +} | null>; diff --git a/orchestrator/src/config.ts b/orchestrator/src/config.ts index b9d549870..8cdeff9a4 100644 --- a/orchestrator/src/config.ts +++ b/orchestrator/src/config.ts @@ -6,6 +6,7 @@ * the operator knows exactly what to set before the process can boot. */ +import { log } from "./log.ts"; import { parseAdminEmails } from "./auth/admin-allowlist.ts"; import { allowlistIsEmpty, @@ -37,12 +38,10 @@ export interface Config { /** CONTROL_PLANE_BEARER — required: the coordinator app-gRPC bearer token */ controlPlaneBearer: string; /** - * CONNECTION_BROKER_BEARER — the bearer the internal connection credential - * broker accepts (ADR 0109). The coordinator sends it from its own - * ENGRAM_CONNECTION_BROKER_BEARER env. Set a value DISTINCT from - * CONTROL_PLANE_BEARER so the mint surface has its own credential; when - * unset it falls back to CONTROL_PLANE_BEARER so existing deployments keep - * working until they set the dedicated secret. + * CONNECTION_BROKER_BEARER — bearer accepted by the credential broker. + * Must match the coordinator's ENGRAM_CONNECTION_BROKER_BEARER. Falls back + * to CONTROL_PLANE_BEARER when unset. Set both broker variables to the same + * dedicated secret to separate broker access from control-plane access. */ connectionBrokerBearer: string; /** @@ -390,9 +389,12 @@ export function loadConfig(env: Record = process.env const port = parseInt(portStr, 10); const baseUrl = optional("ORCHESTRATOR_PUBLIC_URL", `http://127.0.0.1:${port}`); const controlPlaneBearer = require("CONTROL_PLANE_BEARER"); - // The broker keeps working on the shared bearer until the deployment sets - // the dedicated secret (see the Config doc for the rollout note). const connectionBrokerBearer = optional("CONNECTION_BROKER_BEARER", controlPlaneBearer); + if (env["NODE_ENV"] === "production" && !env["CONNECTION_BROKER_BEARER"]) { + log.warn( + "CONNECTION_BROKER_BEARER is unset; the credential broker uses CONTROL_PLANE_BEARER. Set CONNECTION_BROKER_BEARER and the coordinator's ENGRAM_CONNECTION_BROKER_BEARER to the same dedicated secret.", + ); + } const githubAppLogin = optional("GITHUB_APP_LOGIN", ""); const controlPlaneGrpcUrl = optional("CONTROL_PLANE_GRPC_URL", "http://127.0.0.1:50061"); const controlPlaneHttpUrl = optional("CONTROL_PLANE_HTTP_URL", "http://127.0.0.1:8090"); diff --git a/orchestrator/src/control-plane/artifact-fetch.ts b/orchestrator/src/control-plane/artifact-fetch.ts index 0d3dbeb4f..20b606344 100644 --- a/orchestrator/src/control-plane/artifact-fetch.ts +++ b/orchestrator/src/control-plane/artifact-fetch.ts @@ -104,7 +104,7 @@ export function fetchArtifactBytes( maxBytes: number, ): Promise { return collectArtifactBytes( - defaultSessions as unknown as ArtifactStreamClient, + defaultSessions, sessionId, artifactId, { maxBytes }, diff --git a/orchestrator/src/integrations/slack-policy.ts b/orchestrator/src/integrations/slack-policy.ts index 9c9937bc3..e0ab05877 100644 --- a/orchestrator/src/integrations/slack-policy.ts +++ b/orchestrator/src/integrations/slack-policy.ts @@ -142,7 +142,7 @@ export function setSlackPolicyFactoryForTest( export function makeSlackPolicy(deps: SlackPolicyDeps = {}): CommunicationPolicy { if (policyOverride) return policyOverride(deps); const getClient = - deps.client ?? (async () => (await getSlackClient()) as unknown as SlackPolicyClient); + deps.client ?? getSlackClient; const fetchArtifact: FetchArtifactFn = deps.fetchArtifact ?? ((sessionId, artifactId) => fetchArtifactBytes(sessionId, artifactId, MAX_SLACK_UPLOAD_BYTES)); diff --git a/orchestrator/src/routes/admin.ts b/orchestrator/src/routes/admin.ts index 33cea20d6..887c177af 100644 --- a/orchestrator/src/routes/admin.ts +++ b/orchestrator/src/routes/admin.ts @@ -34,33 +34,16 @@ */ import { Hono } from "hono"; -import { HTTPException } from "hono/http-exception"; -import { getSessionFromHeaders } from "../auth/session.ts"; -import { abilityFor } from "../authz/ability.ts"; +import { requireAdmin, type GetSession } from "./guard.ts"; import { config } from "../config.ts"; export function makeAdminRoute( - deps: { httpUrl?: string; bearer?: string } = {}, + deps: { httpUrl?: string; bearer?: string; getSession?: GetSession } = {}, ): Hono { const app = new Hono(); const httpBase = (deps.httpUrl ?? config.controlPlaneHttpUrl).replace(/\/$/, ""); const bearer = deps.bearer ?? config.controlPlaneBearer; - /** Require admin; throws HTTPException(401/403) otherwise. */ - async function requireAdmin(headers: Headers): Promise { - const session = await getSessionFromHeaders(headers); - if (!session) { - throw new HTTPException(401, { message: "unauthenticated" }); - } - const ability = abilityFor({ - id: session.user.id, - role: session.user.role ?? "user", - }); - if (!ability.can("manage", "all")) { - throw new HTTPException(403, { message: "admin required" }); - } - } - /** Forward a POST to the coordinator REST API. */ async function forwardPost( path: string, @@ -80,7 +63,7 @@ export function makeAdminRoute( // POST /api/v1/admin/sessions/:id/pause — freeze the session's microVM in place. // Admin-only. The session stays `active`; the guest vCPUs stop until resumed. app.post("/api/v1/admin/sessions/:id/pause", async (c) => { - await requireAdmin(c.req.raw.headers); + await requireAdmin(c.req.raw.headers, deps.getSession); const id = c.req.param("id"); const upstream = await forwardPost(`/api/v1/admin/sessions/${encodeURIComponent(id)}/pause`, {}); const body = upstream.status === 204 ? null : await upstream.text(); @@ -94,7 +77,7 @@ export function makeAdminRoute( // Admin-only. Counterpart to /pause; the in-place unfreeze, NOT the // idle-rehydrate at /sessions/:id/resume (which is SessionService.Resume). app.post("/api/v1/admin/sessions/:id/resume", async (c) => { - await requireAdmin(c.req.raw.headers); + await requireAdmin(c.req.raw.headers, deps.getSession); const id = c.req.param("id"); const upstream = await forwardPost(`/api/v1/admin/sessions/${encodeURIComponent(id)}/resume`, {}); const body = upstream.status === 204 ? null : await upstream.text(); diff --git a/orchestrator/src/routes/artifacts.ts b/orchestrator/src/routes/artifacts.ts index ee42ab810..d6319c3f8 100644 --- a/orchestrator/src/routes/artifacts.ts +++ b/orchestrator/src/routes/artifacts.ts @@ -155,9 +155,7 @@ async function streamCoordinatorArtifact( export function makeArtifactsRoute(deps?: ArtifactsDeps): Hono { const app = new Hono(); - const sessionsClient: SessionsClient = - (deps?.sessions as SessionsClient | undefined) ?? - (defaultSessions as unknown as SessionsClient); + const sessionsClient: SessionsClient = deps?.sessions ?? defaultSessions; const guardFn = makeGuard(deps?.getSession, deps?.resolveOwner); const resolveSession = deps?.getSession ?? getSessionFromHeaders; let store = deps?.store; diff --git a/orchestrator/src/routes/connection-credential-broker.ts b/orchestrator/src/routes/connection-credential-broker.ts index 87825032b..40696e6bd 100644 --- a/orchestrator/src/routes/connection-credential-broker.ts +++ b/orchestrator/src/routes/connection-credential-broker.ts @@ -81,7 +81,8 @@ const log = rootLog.child({ component: "connection-credential-broker" }); /** Amortized expiry sweep period for the token cache. */ const CACHE_SWEEP_INTERVAL_MS = 60_000; -function bearerMatches(header: string | undefined, expected: string): boolean { +export function bearerMatches(header: string | undefined, expected: string): boolean { + if (expected.length === 0) return false; const actual = header?.startsWith("Bearer ") ? header.slice(7) : ""; const actualBytes = Buffer.from(actual); const expectedBytes = Buffer.from(expected); @@ -115,8 +116,7 @@ export function makeConnectionCredentialBrokerRoute(deps: { } = {}): Hono { const app = new Hono(); const db = deps.db ?? getDb(); - // The broker's OWN bearer (CONNECTION_BROKER_BEARER) — the coordinator sends - // it from ENGRAM_CONNECTION_BROKER_BEARER. Not the shared control-plane one. + // This must match the coordinator's ENGRAM_CONNECTION_BROKER_BEARER. const bearer = deps.bearer ?? config.connectionBrokerBearer; const now = deps.now ?? (() => new Date()); const issuer = deps.issuer ?? googleOidcIssuer(); diff --git a/orchestrator/src/routes/connector-logo.ts b/orchestrator/src/routes/connector-logo.ts index 7a93ceb33..d1d4bcb95 100644 --- a/orchestrator/src/routes/connector-logo.ts +++ b/orchestrator/src/routes/connector-logo.ts @@ -12,12 +12,13 @@ * Injectable deps (store, getSession) for tests. */ +import type { GetSession } from "../auth/types.ts"; import { Hono } from "hono"; import { getSessionFromHeaders } from "../auth/session.ts"; import { makeConnectorLogoStore, type ConnectorLogoStore } from "../db/connector-logos.ts"; -export type GetSession = (headers: Headers) => Promise<{ user: unknown } | null>; +export type { GetSession } from "../auth/types.ts"; export interface ConnectorLogoRouteDeps { store?: ConnectorLogoStore; diff --git a/orchestrator/src/routes/events.ts b/orchestrator/src/routes/events.ts index 8fbf94073..ac99eb029 100644 --- a/orchestrator/src/routes/events.ts +++ b/orchestrator/src/routes/events.ts @@ -55,9 +55,7 @@ export interface EventsDeps { export function makeEventsRoute(deps?: EventsDeps): Hono { const app = new Hono(); - const sessionsClient: SessionsClient = - (deps?.sessions as SessionsClient | undefined) ?? - (defaultSessions as unknown as SessionsClient); + const sessionsClient: SessionsClient = deps?.sessions ?? defaultSessions; const guardFn = makeGuard(deps?.getSession, deps?.resolveOwner); app.get("/api/v1/sessions/:id/events", async (c) => { diff --git a/orchestrator/src/routes/guard.ts b/orchestrator/src/routes/guard.ts index 33e321fee..91bbde5c4 100644 --- a/orchestrator/src/routes/guard.ts +++ b/orchestrator/src/routes/guard.ts @@ -16,6 +16,7 @@ * const user = await guard(c, 'read'); // throws HTTPException on failure */ +import type { GetSession } from "../auth/types.ts"; import type { Context } from "hono"; import { HTTPException } from "hono/http-exception"; import { subject } from "@casl/ability"; @@ -28,10 +29,7 @@ import type { Actions } from "../authz/ability.ts"; // Types // --------------------------------------------------------------------------- -/** Injected getSession implementation (same shape as passthrough.ts). */ -export type GetSession = (headers: Headers) => Promise<{ - user: { id: string; role?: string | null; email?: string | null; name?: string | null }; -} | null>; +export type { GetSession } from "../auth/types.ts"; /** Injected session-owner resolver. */ export type ResolveOwner = (sessionId: string) => Promise; @@ -57,6 +55,20 @@ export type GuardResult = { ok: true; user: GuardUser } | { ok: false; status: 4 // Pure authorization check // --------------------------------------------------------------------------- +/** Require an admin for an HTTP request. */ +export async function requireAdmin( + headers: Headers, + getSession: GetSession = getSessionFromHeaders, +): Promise { + const session = await getSession(headers); + if (!session) throw new HTTPException(401, { message: "unauthenticated" }); + const user = { id: session.user.id, role: session.user.role ?? "user" }; + if (!abilityFor(user).can("manage", "all")) { + throw new HTTPException(403, { message: "admin required" }); + } + return user; +} + /** * Resolve + authorize a session-scoped request from raw `Headers` — the * mechanics shared by the Hono-`Context` guard below (`makeGuard`) and the diff --git a/orchestrator/src/routes/ide.ts b/orchestrator/src/routes/ide.ts index 6d18a06a5..aa905f054 100644 --- a/orchestrator/src/routes/ide.ts +++ b/orchestrator/src/routes/ide.ts @@ -82,9 +82,7 @@ export function parseIdePath(pathname: string, search: string): { sessionId: str export function makeIdeRoute(deps?: IdeDeps): { app: Hono } { const app = new Hono(); const sessions: IdeSessionsClient = deps?.sessions ?? defaultSessions; - const relay: PortRelayClient = - (deps?.portRelay as PortRelayClient | undefined) ?? - (defaultPortRelay as unknown as PortRelayClient); + const relay: PortRelayClient = deps?.portRelay ?? defaultPortRelay; const guardFn = makeGuard(deps?.getSession, deps?.resolveOwner); // Bare `/ide` → `/ide/` so code-server's relative asset paths resolve @@ -137,9 +135,7 @@ export function makeIdeUpgradeHandler( deps?: IdeDeps, ): (req: IncomingMessage, socket: Socket, head: Buffer) => Promise { const sessions: IdeSessionsClient = deps?.sessions ?? defaultSessions; - const relay: PortRelayClient = - (deps?.portRelay as PortRelayClient | undefined) ?? - (defaultPortRelay as unknown as PortRelayClient); + const relay: PortRelayClient = deps?.portRelay ?? defaultPortRelay; const headerGuard = makeHeaderGuard(deps?.getSession, deps?.resolveOwner); // A dedicated WS server (noServer) — NOT the shell's, whose handleProtocols diff --git a/orchestrator/src/routes/integration-oauth.ts b/orchestrator/src/routes/integration-oauth.ts index a03c69cf6..e5bace18d 100644 --- a/orchestrator/src/routes/integration-oauth.ts +++ b/orchestrator/src/routes/integration-oauth.ts @@ -25,12 +25,13 @@ * Generic over any oauth-facet connector — Slack and Linear are the first. */ +import type { GetSession } from "../auth/types.ts"; import { Hono } from "hono"; import type { Context } from "hono"; import { HTTPException } from "hono/http-exception"; import { ConnectError } from "@connectrpc/connect"; import { getSessionFromHeaders } from "../auth/session.ts"; -import { abilityFor } from "../authz/ability.ts"; +import { requireAdmin } from "./guard.ts"; import { config } from "../config.ts"; import { loadRegistry } from "../connectors/registry.ts"; import type { Connector } from "../connectors/registry.ts"; @@ -55,10 +56,6 @@ type OauthCredentialClient = Pick< | "grantServiceAccount" >; -type GetSession = ( - headers: Headers, -) => Promise<{ user: { id: string; role?: string | null } } | null>; - export interface IntegrationOauthDeps { connectors?: { list(): Promise> }; oauthCredential?: OauthCredentialClient; @@ -89,14 +86,6 @@ export function makeIntegrationOauthRoute(deps?: IntegrationOauthDeps): Hono { return `${config.baseUrl.replace(/\/$/, "")}/api/v1/integrations/${encodeURIComponent(provider)}/oauth/callback`; } - async function requireAdmin(headers: Headers): Promise<{ id: string }> { - const session = await getSession(headers); - if (!session) throw new HTTPException(401, { message: "unauthenticated" }); - const ability = abilityFor({ id: session.user.id, role: session.user.role ?? "user" }); - if (!ability.can("manage", "all")) throw new HTTPException(403, { message: "admin required" }); - return { id: session.user.id }; - } - async function requireUser(headers: Headers): Promise<{ id: string }> { const session = await getSession(headers); if (!session) throw new HTTPException(401, { message: "unauthenticated" }); @@ -136,7 +125,7 @@ export function makeIntegrationOauthRoute(deps?: IntegrationOauthDeps): Hono { } app.get("/api/v1/integrations/:provider/oauth/authorize", async (c) => { - await requireAdmin(c.req.raw.headers); + await requireAdmin(c.req.raw.headers, getSession); const provider = c.req.param("provider"); const connector = await oauthConnector(provider); if (connector.oauth?.grant !== "authorization_code") { @@ -191,7 +180,7 @@ export function makeIntegrationOauthRoute(deps?: IntegrationOauthDeps): Hono { // JSON body (`{ subject }`); omitted, the coordinator keeps the sealed one. // The response is JSON: the sheet stays on the page. app.post("/api/v1/integrations/:provider/oauth/grant", async (c) => { - await requireAdmin(c.req.raw.headers); + await requireAdmin(c.req.raw.headers, getSession); const provider = c.req.param("provider"); const connector = await oauthConnector(provider); const grant = connector.oauth?.grant; @@ -264,7 +253,7 @@ export function makeIntegrationOauthRoute(deps?: IntegrationOauthDeps): Hono { } } else { // The callback carries the admin's session cookie. - await requireAdmin(c.req.raw.headers); + await requireAdmin(c.req.raw.headers, getSession); } const connector = await oauthConnector(provider); diff --git a/orchestrator/src/routes/integration-op.ts b/orchestrator/src/routes/integration-op.ts index 5793cf223..3b3d5f1c3 100644 --- a/orchestrator/src/routes/integration-op.ts +++ b/orchestrator/src/routes/integration-op.ts @@ -11,22 +11,14 @@ import { Hono } from "hono"; import { HTTPException } from "hono/http-exception"; -import { getSessionFromHeaders } from "../auth/session.ts"; -import { abilityFor } from "../authz/ability.ts"; +import { requireAdmin, type GetSession } from "./guard.ts"; import { runIntegrationOp, type RunOpDeps } from "../integrations/run-op.ts"; -export function makeIntegrationOpRoute(deps?: RunOpDeps): Hono { +export function makeIntegrationOpRoute(deps?: RunOpDeps & { getSession?: GetSession }): Hono { const app = new Hono(); - async function requireAdmin(headers: Headers): Promise { - const session = await getSessionFromHeaders(headers); - if (!session) throw new HTTPException(401, { message: "unauthenticated" }); - const ability = abilityFor({ id: session.user.id, role: session.user.role ?? "user" }); - if (!ability.can("manage", "all")) throw new HTTPException(403, { message: "admin required" }); - } - app.post("/api/v1/integrations/:provider/run-op", async (c) => { - await requireAdmin(c.req.raw.headers); + await requireAdmin(c.req.raw.headers, deps?.getSession); const provider = c.req.param("provider"); let req: { method?: string; path?: string; body?: unknown; contentType?: string }; try { diff --git a/orchestrator/src/routes/me.ts b/orchestrator/src/routes/me.ts index c7d20f877..b12563a28 100644 --- a/orchestrator/src/routes/me.ts +++ b/orchestrator/src/routes/me.ts @@ -152,7 +152,7 @@ export function makeMeRoute(deps?: MeDeps): Hono { // time (tests inject fakes). const resolveStore = (): UserSecretStore => deps?.secrets ?? makeUserSecretStore(); const resolveCatalog = (): HarnessCatalogReader => - deps?.harnessCatalog ?? (defaultHarnessCatalog as unknown as HarnessCatalogReader); + deps?.harnessCatalog ?? defaultHarnessCatalog; const resolveOAuth = (): OAuthCredentialClient => deps?.oauth ?? defaultOAuthCredential; diff --git a/orchestrator/src/routes/oidc-key-admin.ts b/orchestrator/src/routes/oidc-key-admin.ts index ce742ba3d..7387ecdd2 100644 --- a/orchestrator/src/routes/oidc-key-admin.ts +++ b/orchestrator/src/routes/oidc-key-admin.ts @@ -10,11 +10,11 @@ * Admin-only (browser session + CASL manage-all), mirroring routes/admin.ts. */ +import type { GetSession } from "../auth/types.ts"; import { Hono } from "hono"; -import { HTTPException } from "hono/http-exception"; import { getSessionFromHeaders } from "../auth/session.ts"; -import { abilityFor } from "../authz/ability.ts"; +import { requireAdmin } from "./guard.ts"; import { makeIntegrationOidcKeyStore, type IntegrationOidcKeyStore, @@ -24,10 +24,7 @@ import { log as rootLog } from "../log.ts"; const log = rootLog.child({ component: "oidc-key-admin" }); -/** Narrow session lookup so tests inject a plain fake. */ -export type GetSession = ( - headers: Headers, -) => Promise<{ user: { id: string; role?: string | null } } | null>; +export type { GetSession } from "../auth/types.ts"; export function makeOidcKeyAdminRoute(deps: { keys?: IntegrationOidcKeyStore; @@ -38,26 +35,13 @@ export function makeOidcKeyAdminRoute(deps: { const now = deps.now ?? (() => new Date()); const getSession = deps.getSession ?? getSessionFromHeaders; - async function requireAdmin(headers: Headers): Promise { - const session = await getSession(headers); - if (!session) throw new HTTPException(401, { message: "unauthenticated" }); - const ability = abilityFor({ - id: session.user.id, - role: session.user.role ?? "user", - }); - if (!ability.can("manage", "all")) { - throw new HTTPException(403, { message: "admin required" }); - } - return session.user.id; - } - app.post("/api/v1/admin/integrations/oidc/rotate", async (c) => { - const adminUserId = await requireAdmin(c.req.raw.headers); + const admin = await requireAdmin(c.req.raw.headers, getSession); const keys = deps.keys ?? makeIntegrationOidcKeyStore(); const rotatedAt = now(); const rotated = await keys.rotate(rotatedAt, OIDC_KEY_PUBLISH_OVERLAP_MS); log.info( - { adminUserId, kid: rotated.kid }, + { adminUserId: admin.id, kid: rotated.kid }, "oidc signing key rotated by admin request", ); return c.json({ diff --git a/orchestrator/src/routes/preview-proxy.ts b/orchestrator/src/routes/preview-proxy.ts index 5fc3e31f1..0376a4097 100644 --- a/orchestrator/src/routes/preview-proxy.ts +++ b/orchestrator/src/routes/preview-proxy.ts @@ -580,9 +580,7 @@ function previewErrorResponse(err: unknown): Response { export function makePreviewProxyMiddleware(deps?: PreviewProxyDeps): MiddlewareHandler { const baseDomain = deps?.previewBaseDomain ?? config.previewBaseDomain; const loginUrl = deps?.loginUrl ?? defaultLoginUrl(); - const relay: PortRelayClient = - (deps?.portRelay as PortRelayClient | undefined) ?? - (defaultPortRelay as unknown as PortRelayClient); + const relay: PortRelayClient = deps?.portRelay ?? defaultPortRelay; // Lazy store so importing this module doesn't call getDb() at load. let store = deps?.store; const getStore = (): SessionAppStore => (store ??= makeSessionAppStore()); diff --git a/orchestrator/src/routes/preview-ws.ts b/orchestrator/src/routes/preview-ws.ts index c7f6ddd90..02bc0022c 100644 --- a/orchestrator/src/routes/preview-ws.ts +++ b/orchestrator/src/routes/preview-ws.ts @@ -82,9 +82,7 @@ export function makePreviewUpgradeHandler( deps?: PreviewWsDeps, ): (req: IncomingMessage, socket: Socket, head: Buffer) => Promise { const baseDomain = deps?.previewBaseDomain ?? config.previewBaseDomain; - const relay: PortRelayClient = - (deps?.portRelay as PortRelayClient | undefined) ?? - (defaultPortRelay as unknown as PortRelayClient); + const relay: PortRelayClient = deps?.portRelay ?? defaultPortRelay; let store = deps?.store; const getStore = (): SessionAppStore => (store ??= makeSessionAppStore()); const resolveSession: GetSession = diff --git a/orchestrator/src/routes/reviews-dispatch.ts b/orchestrator/src/routes/reviews-dispatch.ts index 5da8a0864..a93dca18b 100644 --- a/orchestrator/src/routes/reviews-dispatch.ts +++ b/orchestrator/src/routes/reviews-dispatch.ts @@ -1,6 +1,7 @@ /** Bearer-authenticated CI dispatch edge for PR reviews (ADR 0100): an * enrolled repo gets a built-in run under the `review.dispatch` event. */ +import type { GetSession } from "../auth/types.ts"; import { Hono } from "hono"; import { getSessionFromHeaders } from "../auth/session.ts"; @@ -9,10 +10,6 @@ import { getDb } from "../db/client.ts"; import { dispatchAutomationReview, type ReviewCoordinate } from "../reviews/automation-review.ts"; import { makeEnrolledRepos, type EnrolledRepos } from "../reviews/enrolled-repos.ts"; -type GetSession = ( - headers: Headers, -) => Promise<{ user: { id: string } } | null>; - export interface ReviewsDispatchDeps { getSession?: GetSession; /** The PR-review built-in's `repos` input: which repos get reviews. */ diff --git a/orchestrator/src/routes/session-files.ts b/orchestrator/src/routes/session-files.ts index a2a878d11..7ca8389b7 100644 --- a/orchestrator/src/routes/session-files.ts +++ b/orchestrator/src/routes/session-files.ts @@ -72,7 +72,7 @@ function errorResponse(error: unknown): Response { export function makeSessionFilesRoute(deps: SessionFileRouteDeps = {}): Hono { const app = new Hono(); - const client = deps.sessions ?? (defaultSessions as unknown as SessionFileClient); + const client = deps.sessions ?? defaultSessions; const guard = makeGuard(deps.getSession, deps.resolveOwner); app.post("/api/v1/sessions/:id/files", async (c) => { @@ -92,6 +92,8 @@ export function makeSessionFilesRoute(deps: SessionFileRouteDeps = {}): Hono { if (body == null && sizeBytes !== 0n) { return c.json({ error: "request body is required" }, 400); } + // Keep the limit error if the transport wraps the generator failure. + let uploadError: ConnectError | undefined; async function* frames() { yield { frame: { @@ -106,27 +108,41 @@ export function makeSessionFilesRoute(deps: SessionFileRouteDeps = {}): Hono { }; if (body == null) return; const reader = body.getReader(); + let totalBytes = 0; try { while (true) { const result = await reader.read(); if (result.done) return; + totalBytes += result.value.byteLength; + if (totalBytes > MAX_FILE_BYTES) { + uploadError = new ConnectError( + `file exceeds ${MAX_FILE_BYTES} bytes`, + Code.ResourceExhausted, + ); + throw uploadError; + } yield { frame: { case: "chunk" as const, value: result.value }, }; } } finally { - reader.releaseLock(); + try { + await reader.cancel(uploadError); + } finally { + reader.releaseLock(); + } } } try { const result = await client.writeFile(frames()); + if (uploadError) return errorResponse(uploadError); return c.json({ path: result.path, size_bytes: Number(result.sizeBytes), sha256: result.sha256, }); } catch (error) { - return errorResponse(error); + return errorResponse(uploadError ?? error); } }); diff --git a/orchestrator/src/routes/shell.ts b/orchestrator/src/routes/shell.ts index 16a29c7fa..03633d1e3 100644 --- a/orchestrator/src/routes/shell.ts +++ b/orchestrator/src/routes/shell.ts @@ -207,9 +207,7 @@ function waitForDrain(raw: { bufferedAmount?: number }): Promise { export function makeShellUpgradeHandler( deps?: ShellDeps, ): (req: IncomingMessage, socket: Socket, head: Buffer) => Promise { - const relayClient: ShellRelayClient = - (deps?.shellRelay as ShellRelayClient | undefined) ?? - (defaultShellRelay as unknown as ShellRelayClient); + const relayClient: ShellRelayClient = deps?.shellRelay ?? defaultShellRelay; const guard = makeHeaderGuard(deps?.getSession, deps?.resolveOwner); const wss = new WebSocketServer({ noServer: true, diff --git a/orchestrator/src/routes/spec-events.ts b/orchestrator/src/routes/spec-events.ts index 79435f0fd..12b3ccfd2 100644 --- a/orchestrator/src/routes/spec-events.ts +++ b/orchestrator/src/routes/spec-events.ts @@ -17,7 +17,7 @@ export interface SpecEventsRouteDeps { export function makeSpecEventsRoute(deps: SpecEventsRouteDeps): Hono { const app = new Hono(); const authorize = makeSpecMemberHeaderGuard(deps.resolveMembership, deps.getSession); - const sessionsClient = deps.sessions ?? (defaultSessions as unknown as SessionsClient); + const sessionsClient = deps.sessions ?? defaultSessions; app.get("/api/v1/specs/:id/events", async (c) => { const specId = c.req.param("id"); diff --git a/orchestrator/src/routes/vnc.ts b/orchestrator/src/routes/vnc.ts index 5e48cf10b..05c52985f 100644 --- a/orchestrator/src/routes/vnc.ts +++ b/orchestrator/src/routes/vnc.ts @@ -71,9 +71,7 @@ export function makeVncUpgradeHandler( deps?: VncDeps, ): (req: IncomingMessage, socket: Socket, head: Buffer) => Promise { const sessions = deps?.sessions ?? defaultSessions; - const portRelay: PortRelayClient = - (deps?.portRelay as PortRelayClient | undefined) ?? - (defaultPortRelay as unknown as PortRelayClient); + const portRelay: PortRelayClient = deps?.portRelay ?? defaultPortRelay; const guard = makeHeaderGuard(deps?.getSession, deps?.resolveOwner); const wss = new WebSocketServer({ noServer: true, diff --git a/orchestrator/src/rpc/api-key.ts b/orchestrator/src/rpc/api-key.ts index 3127fd27a..6f1b57e0c 100644 --- a/orchestrator/src/rpc/api-key.ts +++ b/orchestrator/src/rpc/api-key.ts @@ -33,6 +33,7 @@ * Injectable deps (getSession, backend) for tests. */ +import type { GetSession } from "../auth/types.ts"; import { ConnectError, Code } from "@connectrpc/connect"; import type { ConnectRouter, HandlerContext } from "@connectrpc/connect"; import { and, eq, like, notExists } from "drizzle-orm"; @@ -45,11 +46,7 @@ import { requireAdmin } from "./require.ts"; import { getDb } from "../db/client.ts"; import { apikey, user } from "../db/schema.ts"; -export type GetSession = ( - headers: Headers, -) => Promise<{ - user: { id: string; role?: string | null; email?: string | null; name?: string | null }; -} | null>; +export type { GetSession } from "../auth/types.ts"; /** The two roles a key can carry — exactly the admin plugin's user roles. */ const ROLES = new Set(["admin", "user"]); diff --git a/orchestrator/src/rpc/artifacts.ts b/orchestrator/src/rpc/artifacts.ts index 077a4e836..44d94b493 100644 --- a/orchestrator/src/rpc/artifacts.ts +++ b/orchestrator/src/rpc/artifacts.ts @@ -12,6 +12,7 @@ * Injectable deps (getSession, store, identities, now) for tests. */ +import type { GetSession } from "../auth/types.ts"; import type { ConnectRouter, HandlerContext } from "@connectrpc/connect"; import { ArtifactService } from "../gen/engram/app/v1/artifact_pb.ts"; @@ -35,11 +36,7 @@ import { } from "../artifacts/service.ts"; import { mintRawToken, rawArtifactPath } from "../crypto/raw-token.ts"; -export type GetSession = ( - headers: Headers, -) => Promise<{ - user: { id: string; role?: string | null; email?: string | null }; -} | null>; +export type { GetSession } from "../auth/types.ts"; export interface ArtifactRpcDeps { getSession?: GetSession; diff --git a/orchestrator/src/rpc/automations.ts b/orchestrator/src/rpc/automations.ts index f15641264..6d2746ebb 100644 --- a/orchestrator/src/rpc/automations.ts +++ b/orchestrator/src/rpc/automations.ts @@ -6,6 +6,7 @@ * the per-org edit surface (the ADR 0119 built-in editing model). */ +import type { GetSession } from "../auth/types.ts"; import { create } from "@bufbuild/protobuf"; import { ConnectError, Code } from "@connectrpc/connect"; import type { ConnectRouter } from "@connectrpc/connect"; @@ -108,9 +109,7 @@ import { getSlackClient } from "../integrations/slack.ts"; import { makeLinearIssueClient } from "../integrations/linear-issues.ts"; import type { WebhookAliasMapping } from "../automations/template.ts"; -export type GetSession = ( - headers: Headers, -) => Promise<{ user: { id: string; role?: string | null } } | null>; +export type { GetSession } from "../auth/types.ts"; export interface OrgSecretClient { putSecret(req: { name: string; value: string }): Promise; @@ -600,7 +599,7 @@ export function registerAutomations(router: ConnectRouter, deps?: AutomationDeps const store = deps?.store ?? makeAutomationStore(getDb()); const profiles = () => deps?.profiles ?? makeProfileStore(getDb()); const harnessCatalog = (): HarnessCatalogClient => - deps?.harnessCatalog ?? (defaultHarnessCatalog as unknown as HarnessCatalogClient); + deps?.harnessCatalog ?? defaultHarnessCatalog; const modelRouters = (): ModelRouterStore => deps?.modelRouters ?? makeModelRouterStore(getDb()); const connectors = deps?.connectors ?? { list: () => makeConnectorStore(getDb()).list() }; const integrationEvents = () => deps?.integrationEvents ?? makeIntegrationEventStore(getDb()); diff --git a/orchestrator/src/rpc/image-guard.ts b/orchestrator/src/rpc/image-guard.ts index 5b5c24f54..d6eb6a389 100644 --- a/orchestrator/src/rpc/image-guard.ts +++ b/orchestrator/src/rpc/image-guard.ts @@ -25,7 +25,7 @@ export function makeDisableImageGuard(deps?: { images?: ImagesClient; }): (req: unknown, ctx: HandlerContext) => Promise { const store: ProfileStore = deps?.store ?? makeProfileStore(getDb()); - const images: ImagesClient = deps?.images ?? (defaultImages as unknown as ImagesClient); + const images: ImagesClient = deps?.images ?? defaultImages; return async (req: unknown) => { const imageUri = (req as { imageUri?: string }).imageUri; diff --git a/orchestrator/src/rpc/integration.ts b/orchestrator/src/rpc/integration.ts index 79ed128aa..a5021fea5 100644 --- a/orchestrator/src/rpc/integration.ts +++ b/orchestrator/src/rpc/integration.ts @@ -11,6 +11,7 @@ * Injectable deps (getSession, connectors) for tests. */ +import type { GetSession } from "../auth/types.ts"; import { ConnectError, Code } from "@connectrpc/connect"; import type { ConnectRouter } from "@connectrpc/connect"; @@ -81,9 +82,7 @@ function sniffLogoMediaType(data: Uint8Array): string | null { return null; } -export type GetSession = ( - headers: Headers, -) => Promise<{ user: { id: string; role?: string | null } } | null>; +export type { GetSession } from "../auth/types.ts"; /** The slice of the coordinator OrgSecretService this service reads/writes. */ export interface OrgSecretAccess { @@ -355,8 +354,8 @@ export function registerIntegration(router: ConnectRouter, deps?: IntegrationDep getSessionFromHeaders; const connectors: ConnectorStore = deps?.connectors ?? makeConnectorStore(getDb()); const connectorLogos: ConnectorLogoStore = deps?.connectorLogos ?? makeConnectorLogoStore(getDb()); - const orgSecret: OrgSecretAccess = deps?.orgSecret ?? (defaultOrgSecret as unknown as OrgSecretAccess); - const mint: MintAccess = deps?.mint ?? (defaultMint as unknown as MintAccess); + const orgSecret: OrgSecretAccess = deps?.orgSecret ?? defaultOrgSecret; + const mint: MintAccess = deps?.mint ?? defaultMint; const integrationOp: IntegrationOpAccess = deps?.integrationOp ?? defaultIntegrationOp; const oauthCredential: OauthCredentialAccess = deps?.oauthCredential ?? defaultOauthCredential; const connections = deps?.connections ?? makeIntegrationConnectionStore(getDb()); diff --git a/orchestrator/src/rpc/mint.ts b/orchestrator/src/rpc/mint.ts index d0b3f3c2b..f9f35d7ce 100644 --- a/orchestrator/src/rpc/mint.ts +++ b/orchestrator/src/rpc/mint.ts @@ -10,6 +10,7 @@ * Injectable deps (getSession, mint) for tests. */ +import type { GetSession } from "../auth/types.ts"; import type { ConnectRouter } from "@connectrpc/connect"; import { MintService, type MintKind } from "../gen/engram/app/v1/mint_pb.ts"; @@ -17,9 +18,7 @@ import { getSessionFromHeaders } from "../auth/session.ts"; import { requireAdmin } from "./require.ts"; import { mint as defaultMint } from "../control-plane/client.ts"; -export type GetSession = ( - headers: Headers, -) => Promise<{ user: { id: string; role?: string | null } } | null>; +export type { GetSession } from "../auth/types.ts"; /** The slice of the coordinator MintService client this proxy uses. */ export interface MintClient { @@ -36,7 +35,7 @@ export function registerMint(router: ConnectRouter, deps?: MintDeps): void { const getSession: GetSession = deps?.getSession ?? getSessionFromHeaders; - const client: MintClient = deps?.mint ?? (defaultMint as unknown as MintClient); + const client: MintClient = deps?.mint ?? defaultMint; router.service(MintService, { // Admin-only: the mint-kind registry describes how to wire a Plane-A diff --git a/orchestrator/src/rpc/model-routers.ts b/orchestrator/src/rpc/model-routers.ts index 45910fd3c..badcf9a48 100644 --- a/orchestrator/src/rpc/model-routers.ts +++ b/orchestrator/src/rpc/model-routers.ts @@ -60,7 +60,7 @@ function modelToProto(row: RouterModelRow) { export function registerModelRouters(router: ConnectRouter, deps?: ModelRouterServiceDeps): void { const getSession = deps?.getSession ?? getSessionFromHeaders; const store = deps?.store ?? makeModelRouterStore(getDb()); - const secrets = deps?.orgSecret ?? (defaultOrgSecret as unknown as SecretMetadataClient); + const secrets = deps?.orgSecret ?? defaultOrgSecret; const refresh = deps?.refresh ?? refreshRouterCatalog; router.service(ModelRouterService, { diff --git a/orchestrator/src/rpc/mount-catalog.ts b/orchestrator/src/rpc/mount-catalog.ts index 58b111e7c..bfa04b86e 100644 --- a/orchestrator/src/rpc/mount-catalog.ts +++ b/orchestrator/src/rpc/mount-catalog.ts @@ -12,6 +12,7 @@ * Injectable deps (getSession, mountCatalog) for tests. */ +import type { GetSession } from "../auth/types.ts"; import type { ConnectRouter } from "@connectrpc/connect"; import { MountCatalogService } from "../gen/engram/app/v1/mount_catalog_pb.ts"; @@ -20,9 +21,7 @@ import { requireAdmin, requireUser } from "./require.ts"; import { mountCatalog as defaultMountCatalog } from "../control-plane/client.ts"; import type { MountCatalogClient } from "../skills/catalog.ts"; -export type GetSession = ( - headers: Headers, -) => Promise<{ user: { id: string; role?: string | null } } | null>; +export type { GetSession } from "../auth/types.ts"; export interface MountCatalogDeps { getSession?: GetSession; @@ -35,7 +34,7 @@ export function registerMountCatalog(router: ConnectRouter, deps?: MountCatalogD deps?.getSession ?? getSessionFromHeaders; const catalog: MountCatalogClient = - deps?.mountCatalog ?? (defaultMountCatalog as unknown as MountCatalogClient); + deps?.mountCatalog ?? defaultMountCatalog; router.service(MountCatalogService, { // Org-shared catalog: any authenticated user may list/get the uploaded skills diff --git a/orchestrator/src/rpc/org-secret.ts b/orchestrator/src/rpc/org-secret.ts index 758450991..c622c49f1 100644 --- a/orchestrator/src/rpc/org-secret.ts +++ b/orchestrator/src/rpc/org-secret.ts @@ -12,6 +12,7 @@ * Injectable deps (getSession, orgSecret) for tests. */ +import type { GetSession } from "../auth/types.ts"; import type { ConnectRouter } from "@connectrpc/connect"; import { OrgSecretService } from "../gen/engram/app/v1/org_secret_pb.ts"; @@ -19,9 +20,7 @@ import { getSessionFromHeaders } from "../auth/session.ts"; import { requireAdmin } from "./require.ts"; import { orgSecret as defaultOrgSecret } from "../control-plane/client.ts"; -export type GetSession = ( - headers: Headers, -) => Promise<{ user: { id: string; role?: string | null } } | null>; +export type { GetSession } from "../auth/types.ts"; /** Org-secret metadata — never the value. */ export interface OrgSecretMetaRow { @@ -49,7 +48,7 @@ export function registerOrgSecret(router: ConnectRouter, deps?: OrgSecretDeps): deps?.getSession ?? getSessionFromHeaders; const client: OrgSecretClient = - deps?.orgSecret ?? (defaultOrgSecret as unknown as OrgSecretClient); + deps?.orgSecret ?? defaultOrgSecret; router.service(OrgSecretService, { // Admin-only: org-secret names describe the deployment's integration / diff --git a/orchestrator/src/rpc/papercuts.ts b/orchestrator/src/rpc/papercuts.ts index a41cc1bae..5e96903f2 100644 --- a/orchestrator/src/rpc/papercuts.ts +++ b/orchestrator/src/rpc/papercuts.ts @@ -1,5 +1,6 @@ /** Orchestrator-native PapercutService. */ +import type { GetSession } from "../auth/types.ts"; import { ConnectError, Code } from "@connectrpc/connect"; import type { ConnectRouter } from "@connectrpc/connect"; import { timestampFromDate } from "@bufbuild/protobuf/wkt"; @@ -17,11 +18,7 @@ import { } from "../db/papercuts.ts"; import { makeProfileStore, type ProfileStore } from "../db/profiles.ts"; -export type GetSession = ( - headers: Headers, -) => Promise<{ - user: { id: string }; -} | null>; +export type { GetSession } from "../auth/types.ts"; export interface PapercutDeps { getSession?: GetSession; diff --git a/orchestrator/src/rpc/passthrough.ts b/orchestrator/src/rpc/passthrough.ts index 201e0291e..e43294a08 100644 --- a/orchestrator/src/rpc/passthrough.ts +++ b/orchestrator/src/rpc/passthrough.ts @@ -21,6 +21,7 @@ * - TaskService.* → native impl (Task 19) */ +import type { GetSession } from "../auth/types.ts"; import { ConnectError, Code } from "@connectrpc/connect"; import type { ConnectRouter, Transport, HandlerContext } from "@connectrpc/connect"; import type { DescService } from "@bufbuild/protobuf"; @@ -50,11 +51,7 @@ export interface PassthroughSpec { * Injected getSession implementation. The default is getSessionFromHeaders * (auth/session.ts); tests inject a stub. */ -export type GetSession = ( - headers: Headers, -) => Promise<{ - user: { id: string; role?: string | null; email?: string | null }; -} | null>; +export type { GetSession } from "../auth/types.ts"; /** * Injected session-owner resolver. The default is the DB-backed diff --git a/orchestrator/src/rpc/pr-refs.ts b/orchestrator/src/rpc/pr-refs.ts index 6e723f27c..99676de32 100644 --- a/orchestrator/src/rpc/pr-refs.ts +++ b/orchestrator/src/rpc/pr-refs.ts @@ -1,5 +1,6 @@ /** Orchestrator-native PrRefService (ADR 0100). */ +import type { GetSession } from "../auth/types.ts"; import { timestampFromDate } from "@bufbuild/protobuf/wkt"; import { Code, ConnectError } from "@connectrpc/connect"; import type { ConnectRouter } from "@connectrpc/connect"; @@ -17,11 +18,7 @@ import { type PrRef, } from "../gen/engram/app/v1/pr_ref_pb.ts"; -export type GetSession = ( - headers: Headers, -) => Promise<{ - user: { id: string }; -} | null>; +export type { GetSession } from "../auth/types.ts"; export interface PrRefDeps { getSession?: GetSession; diff --git a/orchestrator/src/rpc/profiles.ts b/orchestrator/src/rpc/profiles.ts index d9ff7a070..e69166bb1 100644 --- a/orchestrator/src/rpc/profiles.ts +++ b/orchestrator/src/rpc/profiles.ts @@ -13,6 +13,7 @@ * Injectable deps (getSession, store, images) for tests. */ +import type { GetSession } from "../auth/types.ts"; import { ConnectError, Code } from "@connectrpc/connect"; import type { ConnectRouter } from "@connectrpc/connect"; @@ -94,9 +95,7 @@ export interface HarnessCatalogClient { }>; } -export type GetSession = ( - headers: Headers, -) => Promise<{ user: { id: string; role?: string | null; email?: string | null } } | null>; +export type { GetSession } from "../auth/types.ts"; export interface ProfileDeps { getSession?: GetSession; @@ -277,9 +276,9 @@ export function registerProfiles(router: ConnectRouter, deps?: ProfileDeps): voi deps?.getSession ?? getSessionFromHeaders; const store: ProfileStore = deps?.store ?? makeProfileStore(getDb()); - const images: ImagesClient = deps?.images ?? (defaultImages as unknown as ImagesClient); + const images: ImagesClient = deps?.images ?? defaultImages; const harnessCatalog: HarnessCatalogClient = - deps?.harnessCatalog ?? (defaultHarnessCatalog as unknown as HarnessCatalogClient); + deps?.harnessCatalog ?? defaultHarnessCatalog; const mountCatalog: MountCatalogClient = deps?.mountCatalog ?? defaultCatalog(); // Lazy default: construct the store (and thus touch getDb()) only when a // handler actually reads connectors, so importing/registering without a DB @@ -308,12 +307,12 @@ export function registerProfiles(router: ConnectRouter, deps?: ProfileDeps): voi // The compile path needs the RICHER catalog view (auth env vars), so // the default wiring binds the production client, not the narrow // validation-only dep. Tests inject `discoverRepos` wholesale. - harnessCatalog: defaultHarnessCatalog as unknown as DiscoverReposDeps["harnessCatalog"], + harnessCatalog: defaultHarnessCatalog, connections, // The probe boots ownerless (programmatic credentials); user tokens // are never resolved. secrets: { get: async () => null, getAll: async () => ({}) }, - sessions: defaultSessions as unknown as DiscoverReposDeps["sessions"], + sessions: defaultSessions, }; return runRepoDiscovery(discoverDeps, profileId); }); diff --git a/orchestrator/src/rpc/require.ts b/orchestrator/src/rpc/require.ts index d8a720549..bc7ae6199 100644 --- a/orchestrator/src/rpc/require.ts +++ b/orchestrator/src/rpc/require.ts @@ -8,18 +8,14 @@ * their service module. */ +import type { GetSession } from "../auth/types.ts"; import { Code, ConnectError } from "@connectrpc/connect"; import type { HandlerContext } from "@connectrpc/connect"; import { getSessionFromHeaders } from "../auth/session.ts"; import { isServiceAccountEmail } from "./api-key.ts"; -/** Injected getSession implementation (same shape as passthrough.ts). */ -export type GetSession = ( - headers: Headers, -) => Promise<{ - user: { id: string; role?: string | null; email?: string | null }; -} | null>; +export type { GetSession } from "../auth/types.ts"; export interface RpcUser { id: string; diff --git a/orchestrator/src/rpc/reviews.ts b/orchestrator/src/rpc/reviews.ts index 9751cc558..a62e0031d 100644 --- a/orchestrator/src/rpc/reviews.ts +++ b/orchestrator/src/rpc/reviews.ts @@ -1,5 +1,6 @@ /** Orchestrator-native ReviewService (ADR 0100). */ +import type { GetSession } from "../auth/types.ts"; import { timestampFromDate } from "@bufbuild/protobuf/wkt"; import { Code, ConnectError } from "@connectrpc/connect"; import type { ConnectRouter } from "@connectrpc/connect"; @@ -31,11 +32,7 @@ import { type ReviewVerdict as ReviewVerdictProto, } from "../gen/engram/app/v1/review_pb.ts"; -export type GetSession = ( - headers: Headers, -) => Promise<{ - user: { id: string; role?: string | null }; -} | null>; +export type { GetSession } from "../auth/types.ts"; export interface ReviewDeps { getSession?: GetSession; diff --git a/orchestrator/src/rpc/tasks.ts b/orchestrator/src/rpc/tasks.ts index 4cd920488..476fcb1c8 100644 --- a/orchestrator/src/rpc/tasks.ts +++ b/orchestrator/src/rpc/tasks.ts @@ -47,6 +47,7 @@ * used by default. getSession (better-auth) is also injectable. */ +import type { GetSession } from "../auth/types.ts"; import { ConnectError, Code } from "@connectrpc/connect"; import { create } from "@bufbuild/protobuf"; import type { ConnectRouter } from "@connectrpc/connect"; @@ -135,10 +136,7 @@ export interface SessionsClient { deleteSession(req: { sessionId: string }): Promise; } -/** Injectable better-auth getSession function. */ -export type GetSession = (headers: Headers) => Promise<{ - user: { id: string; role?: string | null; email?: string | null }; -} | null>; +export type { GetSession } from "../auth/types.ts"; /** Dependency bag for registerTasks — all optional, real singletons used by default. */ export interface TaskDeps { @@ -771,7 +769,7 @@ export function registerTasks(router: ConnectRouter, deps?: TaskDeps): void { const getSession: GetSession = deps?.getSession ?? getSessionFromHeaders; const sessionsClient: SessionsClient = - deps?.sessions ?? (defaultSessions as unknown as SessionsClient); + deps?.sessions ?? defaultSessions; const getDbFn = (): Db => deps?.db ?? getDb(); // The secret store defaults to a Drizzle store over the same DB. Resolved // lazily so importing this module does not require a DB at import time. @@ -784,7 +782,7 @@ export function registerTasks(router: ConnectRouter, deps?: TaskDeps): void { // Lazy like the other DB-backed stores: registration itself must not require // a configured database. const resolveUsers = (): UserIdentityStore => deps?.users ?? makeUserIdentityStore(getDbFn()); - const imagesClient: ImagesClient = deps?.images ?? (defaultImages as unknown as ImagesClient); + const imagesClient: ImagesClient = deps?.images ?? defaultImages; // Lazy like the other DB-backed stores (ADR 0107 attention derivation). let pendingCallsStoreMemo: PendingToolCallStore | undefined; const pendingCallsStore = { @@ -794,7 +792,7 @@ export function registerTasks(router: ConnectRouter, deps?: TaskDeps): void { }, } as PendingToolCallStore; const harnessCatalogClient: HarnessCatalogClient = - deps?.harnessCatalog ?? (defaultHarnessCatalog as unknown as HarnessCatalogClient); + deps?.harnessCatalog ?? defaultHarnessCatalog; // Lazy default (see profiles.ts): touch getDb() only when a handler reads // connectors, so registering without a DB doesn't throw. const connectors: CustomConnectorSource = deps?.connectors ?? { diff --git a/orchestrator/src/skills/catalog.ts b/orchestrator/src/skills/catalog.ts index b71fcb8b8..19f31c527 100644 --- a/orchestrator/src/skills/catalog.ts +++ b/orchestrator/src/skills/catalog.ts @@ -74,7 +74,7 @@ export interface MountCatalogClient { /** The real singleton client (typed down to the subset used here). */ export function defaultCatalog(): MountCatalogClient { - return defaultMountCatalog as unknown as MountCatalogClient; + return defaultMountCatalog; } /** diff --git a/orchestrator/src/tools/coordination.ts b/orchestrator/src/tools/coordination.ts index 10f97fbab..cff5ba9eb 100644 --- a/orchestrator/src/tools/coordination.ts +++ b/orchestrator/src/tools/coordination.ts @@ -33,7 +33,6 @@ import { OauthSubjectKind } from "../gen/engram/app/v1/oauth_pb.ts"; import { integrationSnapshotHash } from "../integrations/grants.ts"; import { compileSessionCreateInput, - type HarnessCatalogClient, type SessionCreateInput, } from "../rpc/task-create.ts"; import type { ImagesClient } from "../rpc/profiles.ts"; @@ -284,7 +283,7 @@ async function compileChildInput( { images: imagesClient, connectors: { list: () => makeConnectorStore(db).list() }, - harnessCatalog: harnessCatalog as unknown as HarnessCatalogClient, + harnessCatalog, toolRegistry: productionTools, resolveUserToken: (envVar) => (ownerId ? secrets.get(ownerId, envVar) : Promise.resolve(null)), resolveAllUserTokens: () => (ownerId ? secrets.getAll(ownerId) : Promise.resolve({})), From 5b34b7e7e9a44ef2ab2ed5d2ff11c6898cb672d5 Mon Sep 17 00:00:00 2001 From: Nikhil Unni Date: Wed, 2 Dec 2026 11:04:37 -0800 Subject: [PATCH 2/3] fix(orchestrator): bound file uploads by the declared size The upload stream stopped only at the 512 MiB ceiling, so a request that declared one byte still sent 512 MiB to the coordinator before the host rejected it. The stream now stops at the declared size. A Content-Length above the ceiling is also rejected before the RPC starts, even when x-upload-size is small. The guest writes to a temporary file and removes it when the upload fails, so a stopped upload leaves no partial file. Co-Authored-By: Claude Opus 5.5 --- .../src/__tests__/session-files.route.test.ts | 34 ++++++++++++++++--- orchestrator/src/routes/session-files.ts | 15 +++++--- 2 files changed, 40 insertions(+), 9 deletions(-) diff --git a/orchestrator/src/__tests__/session-files.route.test.ts b/orchestrator/src/__tests__/session-files.route.test.ts index c2d06e511..5304c33ec 100644 --- a/orchestrator/src/__tests__/session-files.route.test.ts +++ b/orchestrator/src/__tests__/session-files.route.test.ts @@ -90,10 +90,34 @@ describe("session file routes", () => { expect(called).toBeFalse(); }); + test("rejects an oversized content-length before the RPC", async () => { + let called = false; + const client: SessionFileClient = { + async writeFile() { + called = true; + throw new Error("not reached"); + }, + async *readFile() {}, + }; + const response = await app(client).request( + `/api/v1/sessions/${sessionId}/files?path=${encodeURIComponent(path)}`, + { + method: "POST", + body: bytes, + headers: { + "x-upload-size": String(bytes.length), + "content-length": String(512 * 1024 * 1024 + 1), + }, + }, + ); + expect(response.status).toBe(413); + expect(called).toBeFalse(); + }); + test.each(["x-upload-size", "content-length"])( - "cancels an oversized stream despite a small %s header", + "cancels a stream that exceeds its %s header", async (header) => { - const chunk = new Uint8Array(1024 * 1024); + const chunk = new Uint8Array(1024); let cancelled = false; let forwardedBytes = 0; const body = new ReadableStream({ @@ -116,11 +140,11 @@ describe("session file routes", () => { }; const response = await app(client).request( `/api/v1/sessions/${sessionId}/files?path=${encodeURIComponent(path)}`, - { method: "POST", body, headers: { [header]: "1" } }, + { method: "POST", body, headers: { [header]: "1500" } }, ); expect(response.status).toBe(413); - expect(await response.json()).toEqual({ error: `file exceeds ${512 * 1024 * 1024} bytes` }); - expect(forwardedBytes).toBe(512 * 1024 * 1024); + expect(await response.json()).toEqual({ error: "request body exceeds the declared 1500 bytes" }); + expect(forwardedBytes).toBe(1024); expect(cancelled).toBe(true); expect(body.locked).toBe(false); }, diff --git a/orchestrator/src/routes/session-files.ts b/orchestrator/src/routes/session-files.ts index 7ca8389b7..9847dfc68 100644 --- a/orchestrator/src/routes/session-files.ts +++ b/orchestrator/src/routes/session-files.ts @@ -85,14 +85,21 @@ export function makeSessionFilesRoute(deps: SessionFileRouteDeps = {}): Hono { return c.json({ error: "x-upload-size must be a non-negative integer" }, 400); } const sizeBytes = BigInt(rawSize); - if (sizeBytes > BigInt(MAX_FILE_BYTES)) { + const contentLength = c.req.header("content-length"); + if ( + sizeBytes > BigInt(MAX_FILE_BYTES) || + (contentLength !== undefined && /^\d+$/.test(contentLength) && + BigInt(contentLength) > BigInt(MAX_FILE_BYTES)) + ) { return c.json({ error: `file exceeds ${MAX_FILE_BYTES} bytes` }, 413); } const body = c.req.raw.body; if (body == null && sizeBytes !== 0n) { return c.json({ error: "request body is required" }, 400); } - // Keep the limit error if the transport wraps the generator failure. + // The declared size is the stream bound. Keep this error if the + // transport wraps the generator failure. + const maxBytes = Number(sizeBytes); let uploadError: ConnectError | undefined; async function* frames() { yield { @@ -114,9 +121,9 @@ export function makeSessionFilesRoute(deps: SessionFileRouteDeps = {}): Hono { const result = await reader.read(); if (result.done) return; totalBytes += result.value.byteLength; - if (totalBytes > MAX_FILE_BYTES) { + if (totalBytes > maxBytes) { uploadError = new ConnectError( - `file exceeds ${MAX_FILE_BYTES} bytes`, + `request body exceeds the declared ${maxBytes} bytes`, Code.ResourceExhausted, ); throw uploadError; From 24f401de40cc0f20665d36d233a24990ac956c68 Mon Sep 17 00:00:00 2001 From: Nikhil Unni Date: Wed, 2 Dec 2026 11:04:38 -0800 Subject: [PATCH 3/3] fix(orchestrator): remove the broker bearer warning that never fires The warning ran only when NODE_ENV is "production". No shipped deployment sets NODE_ENV (the Helm chart, the orchestrator image, and Tilt do not), so the warning never ran. The Helm chart also cannot set a dedicated broker bearer: it gives the coordinator's ENGRAM_CONNECTION_BROKER_BEARER the CONTROL_PLANE_BEARER key. A warning that fires there would tell operators to do what the chart cannot do. The test now covers the fallback itself. Co-Authored-By: Claude Opus 5.5 --- .../src/__tests__/config-broker.test.ts | 29 +++++-------------- orchestrator/src/config.ts | 6 ---- 2 files changed, 7 insertions(+), 28 deletions(-) diff --git a/orchestrator/src/__tests__/config-broker.test.ts b/orchestrator/src/__tests__/config-broker.test.ts index eea5a457c..dbf1623c3 100644 --- a/orchestrator/src/__tests__/config-broker.test.ts +++ b/orchestrator/src/__tests__/config-broker.test.ts @@ -1,9 +1,7 @@ -import { describe, expect, spyOn, test } from "bun:test"; +import { describe, expect, test } from "bun:test"; import { loadConfig } from "../config.ts"; -import { log } from "../log.ts"; const env = { - NODE_ENV: "production", CONTROL_PLANE_BEARER: "control-secret", ORCHESTRATOR_DATABASE_URL: "postgres://localhost/test", ENGRAM_KEK_MASTER_KEY: Buffer.alloc(32).toString("base64"), @@ -11,26 +9,13 @@ const env = { }; describe("broker bearer configuration", () => { - test.each([undefined, ""])("preserves the shared bearer fallback for %p", (bearer) => { - const warn = spyOn(log, "warn").mockImplementation(() => {}); - try { - expect(loadConfig({ ...env, CONNECTION_BROKER_BEARER: bearer }).connectionBrokerBearer) - .toBe("control-secret"); - expect(warn).toHaveBeenCalledTimes(1); - expect(warn.mock.calls[0]?.[0]).toContain("CONNECTION_BROKER_BEARER is unset"); - } finally { - warn.mockRestore(); - } + test.each([undefined, ""])("falls back to the control-plane bearer for %p", (bearer) => { + expect(loadConfig({ ...env, CONNECTION_BROKER_BEARER: bearer }).connectionBrokerBearer) + .toBe("control-secret"); }); - test("uses the dedicated bearer without a fallback warning", () => { - const warn = spyOn(log, "warn").mockImplementation(() => {}); - try { - expect(loadConfig({ ...env, CONNECTION_BROKER_BEARER: "broker-secret" }).connectionBrokerBearer) - .toBe("broker-secret"); - expect(warn).not.toHaveBeenCalled(); - } finally { - warn.mockRestore(); - } + test("uses the dedicated bearer when it is set", () => { + expect(loadConfig({ ...env, CONNECTION_BROKER_BEARER: "broker-secret" }).connectionBrokerBearer) + .toBe("broker-secret"); }); }); diff --git a/orchestrator/src/config.ts b/orchestrator/src/config.ts index 8cdeff9a4..7a3c081a3 100644 --- a/orchestrator/src/config.ts +++ b/orchestrator/src/config.ts @@ -6,7 +6,6 @@ * the operator knows exactly what to set before the process can boot. */ -import { log } from "./log.ts"; import { parseAdminEmails } from "./auth/admin-allowlist.ts"; import { allowlistIsEmpty, @@ -390,11 +389,6 @@ export function loadConfig(env: Record = process.env const baseUrl = optional("ORCHESTRATOR_PUBLIC_URL", `http://127.0.0.1:${port}`); const controlPlaneBearer = require("CONTROL_PLANE_BEARER"); const connectionBrokerBearer = optional("CONNECTION_BROKER_BEARER", controlPlaneBearer); - if (env["NODE_ENV"] === "production" && !env["CONNECTION_BROKER_BEARER"]) { - log.warn( - "CONNECTION_BROKER_BEARER is unset; the credential broker uses CONTROL_PLANE_BEARER. Set CONNECTION_BROKER_BEARER and the coordinator's ENGRAM_CONNECTION_BROKER_BEARER to the same dedicated secret.", - ); - } const githubAppLogin = optional("GITHUB_APP_LOGIN", ""); const controlPlaneGrpcUrl = optional("CONTROL_PLANE_GRPC_URL", "http://127.0.0.1:50061"); const controlPlaneHttpUrl = optional("CONTROL_PLANE_HTTP_URL", "http://127.0.0.1:8090");