An open-source, faster Devin alternative
TypeScript
api-edge: computer keys carry a typed principal and session; refused on grant routes (work 080)
Mohamed Habib via Computerdef7aa011d63
diff --git a/cloudflare-workers/api-edge/migrations/0010_api_keys_session_key.sql b/cloudflare-workers/api-edge/migrations/0010_api_keys_session_key.sqlnew file mode 100644index 00000000..8b832614--- /dev/null+++ b/cloudflare-workers/api-edge/migrations/0010_api_keys_session_key.sql@@ -0,0 +1,6 @@+-- api_keys.session_key — the computer session a one-hour computer key was+-- minted for (serverless-agents-ws work 080). Set only on keys created by+-- /internal/computer-keys (created_by = 'computer'); NULL for every other key.+-- Forwarded to managed agents as the assertion's session_key claim, so grants+-- made to one thread resolve for that thread's keys only.+ALTER TABLE api_keys ADD COLUMN session_key TEXT;diff --git a/cloudflare-workers/api-edge/src/api_keys.ts b/cloudflare-workers/api-edge/src/api_keys.tsindex 516b544a..8659aa9c 100644--- a/cloudflare-workers/api-edge/src/api_keys.ts+++ b/cloudflare-workers/api-edge/src/api_keys.ts@@ -25,7 +25,7 @@ export async function hashAPIKey(key: string): Promise<string> {*/export async function createAPIKey(env: APIKeyEnv,- input: { orgID: string; userID: string; name: string; expiresAt?: number },+ input: { orgID: string; userID: string; name: string; expiresAt?: number; sessionKey?: string },): Promise<CreatedAPIKey> {const bytes = new Uint8Array(32);crypto.getRandomValues(bytes);@@ -36,10 +36,10 @@ export async function createAPIKey(const now = Math.floor(Date.now() / 1000);await env.OPENCOMPUTER_DB.prepare(- `INSERT INTO api_keys (id, org_id, created_by, key_hash, key_prefix, name, scopes, created_at, expires_at)- VALUES (?1, ?2, ?3, ?4, ?5, ?6, 'sandbox:*', ?7, ?8)`,+ `INSERT INTO api_keys (id, org_id, created_by, key_hash, key_prefix, name, scopes, created_at, expires_at, session_key)+ VALUES (?1, ?2, ?3, ?4, ?5, ?6, 'sandbox:*', ?7, ?8, ?9)`,)- .bind(id, input.orgID, input.userID, hash, prefix, input.name, now, input.expiresAt ?? null)+ .bind(id, input.orgID, input.userID, hash, prefix, input.name, now, input.expiresAt ?? null, input.sessionKey ?? null).run();return {diff --git a/cloudflare-workers/api-edge/src/computer_principal.test.ts b/cloudflare-workers/api-edge/src/computer_principal.test.tsnew file mode 100644index 00000000..2dea8fb8--- /dev/null+++ b/cloudflare-workers/api-edge/src/computer_principal.test.ts@@ -0,0 +1,116 @@+// Computer keys (work 080): a typed principal and session on the assertion,+// and no route that creates, attaches or grants a credential.+import { afterEach, describe, expect, it, vi } from "vitest";++import { isGrantRoute, mintManagedAgentsAssertion, proxyManagedAgents } from "./managed_agents";++const SESSION = "T06GJFPHY5R:C0C9F5SV47Q:1792176058.240229";+const COMPUTER = { orgID: "org_test", userID: "computer", principal: "computer" as const, sessionKey: SESSION };+const ENV = { MANAGED_AGENTS_API_URL: "https://managedagents.test", OC_MANAGED_AGENTS_SECRET: "test-secret" };++function claims(token: string): Record<string, unknown> {+ return JSON.parse(atob(token.split(".")[1].replace(/-/g, "+").replace(/_/g, "/"))) as Record<string, unknown>;+}++describe("computer principal", () => {+ afterEach(() => vi.unstubAllGlobals());++ it("puts the principal and session on the assertion", async () => {+ expect(claims(await mintManagedAgentsAssertion("s", COMPUTER))).toMatchObject({+ user_id: "computer",+ principal: "computer",+ session_key: SESSION,+ });+ });++ it("puts neither on a person's assertion", async () => {+ const payload = claims(await mintManagedAgentsAssertion("s", { orgID: "o", userID: "user_1", sessionKey: SESSION }));+ expect(payload.principal).toBeUndefined();+ expect(payload.session_key).toBeUndefined();+ });++ it.each([+ ["POST", "/connections"],+ ["PUT", "/connections/c1"],+ ["DELETE", "/connections/c1"],+ ["POST", "/connections/linear/link"],+ ["DELETE", "/connections/linear"],+ ["POST", "/connections/channel-identity/link"],+ ["POST", "/projects/p1/service-connections"],+ ["DELETE", "/projects/p1/service-connections"],+ ["POST", "/model-access/connections"],+ ["POST", "/model-access/connections/m1/complete"],+ ["PUT", "/projects/p1/model-access/bindings/openai/production"],+ ["POST", "/projects/p1/linear/connections"],+ ["PUT", "/linear/connections/l1/credentials"],+ ["POST", "/channels/slack/setups"],+ ["POST", "/channel-connections/claim"],+ ["POST", "/github/connect"],+ ["POST", "/projects/p1/github/connect"],+ ["POST", "/projects/p1/github/attach"],+ ["DELETE", "/projects/p1/github"],+ ])("refuses %s %s", (method, suffix) => {+ expect(isGrantRoute(method, suffix)).toBe(true);+ });++ it.each([+ ["GET", "/connections"],+ ["POST", "/connections/linear/fetch"],+ ["POST", "/connections/google/fetch"],+ ["GET", "/projects/p1/service-connections"],+ ["GET", "/projects/p1/secrets"],+ ["PUT", "/projects/p1/secrets/API_KEY"],+ ["POST", "/projects"],+ ["POST", "/deployments"],+ ["POST", "/sessions"],+ ["POST", "/automations/repository/credentials"],+ ])("allows %s %s", (method, suffix) => {+ expect(isGrantRoute(method, suffix)).toBe(false);+ });++ it("answers 403 to a computer key on a grant route and never reaches managed agents", async () => {+ const fetchMock = vi.fn();+ vi.stubGlobal("fetch", fetchMock);+ const res = await proxyManagedAgents(+ new Request("https://app.opencomputer.dev/api/managed-agents/connections/linear/link", { method: "POST" }),+ ENV,+ COMPUTER,+ "/api/managed-agents",+ );+ expect(res.status).toBe(403);+ expect(((await res.json()) as { error: { code: string } }).error.code).toBe("computer_key_forbidden");+ expect(fetchMock).not.toHaveBeenCalled();+ });++ it("lets a person's key through the same route", async () => {+ const fetchMock = vi.fn().mockResolvedValue(Response.json({ ok: true }));+ vi.stubGlobal("fetch", fetchMock);+ const res = await proxyManagedAgents(+ new Request("https://app.opencomputer.dev/api/managed-agents/connections/linear/link", { method: "POST" }),+ ENV,+ { orgID: "org_test", userID: "user_1" },+ "/api/managed-agents",+ );+ expect(res.status).toBe(200);+ expect(fetchMock).toHaveBeenCalledOnce();+ });++ it("forwards a computer key's fetch with its session", async () => {+ const fetchMock = vi.fn().mockResolvedValue(Response.json({ data: {} }));+ vi.stubGlobal("fetch", fetchMock);+ const res = await proxyManagedAgents(+ new Request("https://app.opencomputer.dev/api/managed-agents/connections/linear/fetch", {+ method: "POST",+ body: "{}",+ headers: { "content-type": "application/json" },+ }),+ ENV,+ COMPUTER,+ "/api/managed-agents",+ );+ expect(res.status).toBe(200);+ const sent = fetchMock.mock.calls[0][1] as RequestInit;+ const token = new Headers(sent.headers).get("x-opencomputer-agent-token") ?? "";+ expect(claims(token)).toMatchObject({ principal: "computer", session_key: SESSION });+ });+});diff --git a/cloudflare-workers/api-edge/src/index.test.ts b/cloudflare-workers/api-edge/src/index.test.tsindex 774f1091..60506a4d 100644--- a/cloudflare-workers/api-edge/src/index.test.ts+++ b/cloudflare-workers/api-edge/src/index.test.ts@@ -647,8 +647,8 @@ describe("/internal/computer-keys", () => {const mac = await crypto.subtle.sign("HMAC", key, new TextEncoder().encode(`${ts}.${body}`));return [...new Uint8Array(mac)].map((b) => b.toString(16).padStart(2, "0")).join("");};- const post = async (secret: string, orgID: string, authEnv: Env) => {- const body = JSON.stringify({ org_id: orgID });+ const post = async (secret: string, orgID: string, authEnv: Env, extra: Record<string, unknown> = {}) => {+ const body = JSON.stringify({ org_id: orgID, ...extra });const ts = Math.floor(Date.now() / 1000).toString();return worker.fetch(new Request("https://app.opencomputer.dev/internal/computer-keys", {@@ -687,5 +687,24 @@ describe("/internal/computer-keys", () => {expect(ttl).toBeLessThanOrEqual(3600_000);expect(runs[0][1]).toBe("org-x");expect(runs[0][2]).toBe("computer");+ expect(runs[0][8]).toBeNull();+ });++ it("records the session a key is for, and refuses a malformed one", async () => {+ const runs: unknown[][] = [];+ const db = {+ prepare: (sql: string) => ({+ bind: (...args: unknown[]) => ({+ first: async () => (sql.includes("FROM orgs") ? { id: "org-x" } : null),+ run: async () => { runs.push(args); return {}; },+ }),+ }),+ };+ const authEnv = { ...env, OC_MANAGED_CRED_HMAC_SECRET: MANAGED, OPENCOMPUTER_DB: db } as unknown as Env;+ expect((await post(MANAGED, "org-x", authEnv, { session_key: "T1:C1:1.2" })).status).toBe(200);+ expect(runs[0][8]).toBe("T1:C1:1.2");+ expect((await post(MANAGED, "org-x", authEnv, { session_key: "T1:C1" })).status).toBe(400);+ expect((await post(MANAGED, "org-x", authEnv, { session_key: 7 })).status).toBe(400);+ expect(runs).toHaveLength(1);});});diff --git a/cloudflare-workers/api-edge/src/index.ts b/cloudflare-workers/api-edge/src/index.tsindex c70bd965..3f5e8d47 100644--- a/cloudflare-workers/api-edge/src/index.ts+++ b/cloudflare-workers/api-edge/src/index.ts@@ -390,6 +390,29 @@ interface Caller {// Set only for act-as-org provisioning tokens (sessions-api). Least-privilege:// the dispatch gates these to sandbox + secret-store routes (provisionScopeGate).scope?: "sandbox-provision";+ // Set only for the organization's computer (work 080): its one-hour keys are+ // created_by COMPUTER_PRINCIPAL, a reserved id no person has. sessionKey is+ // the Slack thread the key was minted for, when the gateway named one.+ principal?: "computer";+ sessionKey?: string;+}++const COMPUTER_PRINCIPAL = "computer";+// The shape of blue's sessionKey(team, channel, thread); blue checks the+// session is live before it asks for a key.+const SESSION_KEY_RE = /^[A-Za-z0-9._-]{1,40}:[A-Za-z0-9._-]{1,40}:[A-Za-z0-9._-]{1,40}$/;++// One mapping from a key row to a Caller, for every reader (auth, refresh,+// warm-org), so the cached shapes cannot drift apart.+function callerFromRow(row: AuthRow): Caller {+ const computer = row.created_by === COMPUTER_PRINCIPAL;+ return {+ orgID: row.org_id,+ userID: row.created_by,+ ...(row.role ? { role: row.role } : {}),+ ...(computer ? { principal: "computer" as const } : {}),+ ...(computer && row.session_key ? { sessionKey: row.session_key } : {}),+ };}interface SandboxCreateResult {@@ -585,7 +608,7 @@ function bumpLastUsed(env: Env, hash: string, entry: AuthEntry, nowMs: number):.catch(() => {});}-const AUTH_KEY_SQL = `SELECT k.org_id, k.created_by, k.expires_at,+const AUTH_KEY_SQL = `SELECT k.org_id, k.created_by, k.expires_at, k.session_key,CASE WHEN m.role IN ('owner', 'admin') THEN 'admin' ELSE m.role END AS roleFROM api_keys kLEFT JOIN org_memberships m@@ -600,6 +623,7 @@ type AuthRow = {created_by: string | null;expires_at: number | null;role: string | null;+ session_key?: string | null;};// In-flight auth refreshes, keyed by hash — same single-flight shape as@@ -627,11 +651,7 @@ function refreshAuth(env: Env, hash: string): Promise<void> {return;}const at = Date.now();- const caller: Caller = {- orgID: row.org_id,- userID: row.created_by,- ...(row.role ? { role: row.role } : {}),- };+ const caller = callerFromRow(row);if (authCache.size >= CACHE_MAX) authCache.clear();authCache.set(hash, {caller,@@ -744,11 +764,7 @@ async function authenticate(req: Request, env: Env, ctx?: ExecutionContext, probif (!row) return null; // never cache negatives — a freshly-created key must work at onceif (row.expires_at && row.expires_at < nowSec) return null;- const caller: Caller = {- orgID: row.org_id,- userID: row.created_by,- ...(row.role ? { role: row.role } : {}),- };+ const caller = callerFromRow(row);if (authCache.size >= CACHE_MAX) authCache.clear();const entry: AuthEntry = { caller, expiresAt: row.expires_at, cachedAtMs: nowMs, lastBumpMs: 0 };authCache.set(hash, entry);@@ -5362,7 +5378,7 @@ export default {// what a real miss would have written. Drift here would be invisible: the// cache would hit and serve a subtly different caller.const rows = await env.OPENCOMPUTER_DB.prepare(- `SELECT k.key_hash, k.org_id, k.created_by, k.expires_at,+ `SELECT k.key_hash, k.org_id, k.created_by, k.expires_at, k.session_key,CASE WHEN m.role IN ('owner', 'admin') THEN 'admin' ELSE m.role END AS roleFROM api_keys kLEFT JOIN org_memberships m@@ -5374,16 +5390,13 @@ export default {created_by: string | null;expires_at: number | null;role: string | null;+ session_key: string | null;}>();const at = Date.now();let warmed = 0;for (const row of rows.results ?? []) {- const caller: Caller = {- orgID: row.org_id,- userID: row.created_by,- ...(row.role ? { role: row.role } : {}),- };+ const caller = callerFromRow(row);await coloPut("auth", row.key_hash, { caller, expiresAt: row.expires_at, cachedAtMs: at }, AUTH_STALE_MAX_MS / 1000);warmed++;}@@ -5439,7 +5452,9 @@ export default {// /internal/computer-keys — a one-hour org key for an organization's computer// (work 067): managed agents mints one when a session runs `opencomputer`,// instead of a long-lived key living on the VM. HMAC-auth'd with the scoped- // OC_MANAGED_CRED_HMAC_SECRET over `${ts}.${body}`. Body: { org_id }.+ // OC_MANAGED_CRED_HMAC_SECRET over `${ts}.${body}`. Body: { org_id,+ // session_key? }: the Slack thread the key is for (work 080), recorded on+ // the key and forwarded as the assertion's session_key claim.if (path === "/internal/computer-keys" && req.method === "POST") {const ts = req.headers.get("X-Timestamp") ?? "";const sig = req.headers.get("X-Signature") ?? "";@@ -5449,15 +5464,20 @@ export default {: false;if (!ok) return json({ error: "signature mismatch" }, 401);if (Math.abs(Math.floor(Date.now() / 1000) - Number(ts)) > 300) return json({ error: "timestamp out of window" }, 401);- const parsed = JSON.parse(body) as { org_id?: string };+ const parsed = JSON.parse(body) as { org_id?: string; session_key?: unknown };if (!parsed.org_id) return json({ error: "org_id required" }, 400);+ const sessionKey = parsed.session_key;+ if (sessionKey !== undefined && (typeof sessionKey !== "string" || !SESSION_KEY_RE.test(sessionKey))) {+ return json({ error: "session_key must be team:channel:thread" }, 400);+ }const org = await env.OPENCOMPUTER_DB.prepare(`SELECT id FROM orgs WHERE id = ?1`).bind(parsed.org_id).first();if (!org) return json({ error: "org not found" }, 404);const created = await createAPIKey(env, {orgID: parsed.org_id,- userID: "computer",+ userID: COMPUTER_PRINCIPAL,name: "Computer session",expiresAt: Math.floor(Date.now() / 1000) + 3600,+ ...(sessionKey ? { sessionKey } : {}),});return json({ key: created.key, expiresAt: created.expiresAt });}diff --git a/cloudflare-workers/api-edge/src/managed_agents.ts b/cloudflare-workers/api-edge/src/managed_agents.tsindex f393231b..df97200f 100644--- a/cloudflare-workers/api-edge/src/managed_agents.ts+++ b/cloudflare-workers/api-edge/src/managed_agents.ts@@ -24,6 +24,10 @@ export interface ManagedAgentsCaller {orgID: string;userID: string | null;role?: string;+ /** The organization's computer (work 080); absent for people's keys. */+ principal?: "computer";+ /** The computer session (Slack thread) the key was minted for. */+ sessionKey?: string;}const DEFAULT_MANAGED_AGENTS_API_URL = "https://managedagents.opencomputer.dev";@@ -101,6 +105,8 @@ export async function mintManagedAgentsAssertion(};if (caller.userID) payload.user_id = caller.userID;if (caller.role) payload.role = caller.role;+ if (caller.principal) payload.principal = caller.principal;+ if (caller.principal && caller.sessionKey) payload.session_key = caller.sessionKey;const encoder = new TextEncoder();const signingInput =`${b64url(encoder.encode(JSON.stringify(header)))}.` +@@ -2691,6 +2697,28 @@ async function deploySourceAgent(return publicSuccessResponse(deploymentResponse, "POST", "/deployments");}+// Routes that create, attach, grant or revoke a credential (work 080). A+// computer key may read and use connections (`POST /connections/:service/fetch`)+// but never change who can reach what: a thread can ask, only a person grants.+// Reads stay open; so do the automation routes the computer needs (work 067).+const COMPUTER_FETCH_ROUTE = /^\/connections\/[^/]+\/fetch$/;++export function isGrantRoute(method: string, suffix: string): boolean {+ if (method === "GET" || method === "HEAD") return false;+ if (/^\/connections(?:\/|$)/.test(suffix)) {+ return !(method === "POST" && COMPUTER_FETCH_ROUTE.test(suffix));+ }+ return (+ /^\/projects\/[^/]+\/service-connections$/.test(suffix) ||+ /^\/(?:projects\/[^/]+\/)?model-access(?:\/|$)/.test(suffix) ||+ isLinearRouteSuffix(suffix) ||+ /^\/channels(?:\/|$)/.test(suffix) ||+ suffix === "/channel-connections/claim" ||+ suffix === "/github/connect" ||+ /^\/projects\/[^/]+\/github(?:\/(?:connect|attach))?$/.test(suffix)+ );+}+function isAllowedManagedAgentsRoute(method: string, suffix: string): boolean {// The organization's computer: only the contract's routes (work 052).if (isComputerRouteSuffix(suffix)) return isComputerRoute(method, suffix);@@ -3546,6 +3574,21 @@ export async function proxyManagedAgents(if (!isAllowedManagedAgentsRoute(request.method.toUpperCase(), suffix)) {return Response.json({ error: "route not found" }, { status: 404 });}+ if (+ caller.principal === "computer" &&+ isGrantRoute(request.method.toUpperCase(), suffix)+ ) {+ return Response.json(+ {+ error: {+ code: "computer_key_forbidden",+ message:+ "The computer cannot connect, attach or grant credentials; a person does that from Slack or the dashboard.",+ },+ },+ { status: 403 },+ );+ }// The computer is a dashboard surface in v1; API keys do not reach it.if (isComputerRouteSuffix(suffix) &&