Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 47 additions & 0 deletions orchestrator/src/__tests__/admin-guard.test.ts
Original file line number Diff line number Diff line change
@@ -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);
}
});
}
});
21 changes: 21 additions & 0 deletions orchestrator/src/__tests__/config-broker.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { describe, expect, test } from "bun:test";
import { loadConfig } from "../config.ts";

const env = {
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, ""])("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 when it is set", () => {
expect(loadConfig({ ...env, CONNECTION_BROKER_BEARER: "broker-secret" }).connectionBrokerBearer)
.toBe("broker-secret");
});
});
14 changes: 14 additions & 0 deletions orchestrator/src/__tests__/connection-credential-broker.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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);
}
});
});
60 changes: 60 additions & 0 deletions orchestrator/src/__tests__/session-files.route.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,66 @@ 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 a stream that exceeds its %s header",
async (header) => {
const chunk = new Uint8Array(1024);
let cancelled = false;
let forwardedBytes = 0;
const body = new ReadableStream<Uint8Array>({
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]: "1500" } },
);
expect(response.status).toBe(413);
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);
},
);

test("streams authenticated downloads with verified metadata headers", async () => {
const client: SessionFileClient = {
async writeFile() {
Expand Down
4 changes: 4 additions & 0 deletions orchestrator/src/auth/types.ts
Original file line number Diff line number Diff line change
@@ -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>;
12 changes: 4 additions & 8 deletions orchestrator/src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,12 +37,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;
/**
Expand Down Expand Up @@ -390,8 +388,6 @@ export function loadConfig(env: Record<string, string | undefined> = 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);
const githubAppLogin = optional("GITHUB_APP_LOGIN", "");
const controlPlaneGrpcUrl = optional("CONTROL_PLANE_GRPC_URL", "http://127.0.0.1:50061");
Expand Down
2 changes: 1 addition & 1 deletion orchestrator/src/control-plane/artifact-fetch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ export function fetchArtifactBytes(
maxBytes: number,
): Promise<FetchedArtifact> {
return collectArtifactBytes(
defaultSessions as unknown as ArtifactStreamClient,
defaultSessions,
sessionId,
artifactId,
{ maxBytes },
Expand Down
2 changes: 1 addition & 1 deletion orchestrator/src/integrations/slack-policy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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));
Expand Down
25 changes: 4 additions & 21 deletions orchestrator/src/routes/admin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<void> {
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,
Expand All @@ -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();
Expand All @@ -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();
Expand Down
4 changes: 1 addition & 3 deletions orchestrator/src/routes/artifacts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
6 changes: 3 additions & 3 deletions orchestrator/src/routes/connection-credential-broker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down Expand Up @@ -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();
Expand Down
3 changes: 2 additions & 1 deletion orchestrator/src/routes/connector-logo.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
4 changes: 1 addition & 3 deletions orchestrator/src/routes/events.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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) => {
Expand Down
20 changes: 16 additions & 4 deletions orchestrator/src/routes/guard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand All @@ -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<string | null>;
Expand All @@ -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<GuardUser> {
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
Expand Down
8 changes: 2 additions & 6 deletions orchestrator/src/routes/ide.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -137,9 +135,7 @@ export function makeIdeUpgradeHandler(
deps?: IdeDeps,
): (req: IncomingMessage, socket: Socket, head: Buffer) => Promise<boolean> {
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
Expand Down
Loading
Loading