Skip to content

An open-source, faster Devin alternative

TypeScript

api-edge: mint keys with an explicit scope list (work 095 step 1) (#1017)

opencomputer-app[bot]1cb28e4bc509
diff --git a/cloudflare-workers/api-edge/src/api_keys.test.ts b/cloudflare-workers/api-edge/src/api_keys.test.ts
new file mode 100644
index 00000000..e099c40b
--- /dev/null
+++ b/cloudflare-workers/api-edge/src/api_keys.test.ts
@@ -0,0 +1,41 @@
+import { describe, expect, it } from "vitest";
+import { COMPUTER_SESSION_KEY_SCOPES, KEY_SCOPES, createAPIKey, type APIKeyEnv } from "./api_keys";
+
+function fakeEnv(): { env: APIKeyEnv; runs: unknown[][] } {
+ const runs: unknown[][] = [];
+ const db = {
+ prepare: () => ({
+ bind: (...args: unknown[]) => ({
+ run: async () => {
+ runs.push(args);
+ return {};
+ },
+ }),
+ }),
+ };
+ return { env: { OPENCOMPUTER_DB: db } as unknown as APIKeyEnv, runs };
+}
+
+const base = { orgID: "org-x", userID: "user-x", name: "k" };
+
+describe("createAPIKey scopes (work 095)", () => {
+ it("stores and returns the scopes the minter names", async () => {
+ const { env, runs } = fakeEnv();
+ const created = await createAPIKey(env, { ...base, scopes: ["sessions:read", "sessions:read", "terminals"] });
+ expect(created.scopes).toEqual(["sessions:read", "terminals"]);
+ expect(runs[0][9]).toBe("sessions:read,terminals");
+ });
+
+ it("refuses an empty list or a wildcard, which would read as everything", async () => {
+ const { env, runs } = fakeEnv();
+ for (const scopes of [[], ["*"], ["sandbox:*"], ["sessions:read", "*"], ["a,b"], [""]]) {
+ await expect(createAPIKey(env, { ...base, scopes })).rejects.toThrow("explicit list");
+ }
+ expect(runs).toHaveLength(0);
+ });
+
+ it("mints no key that can write secrets", () => {
+ expect(KEY_SCOPES).not.toContain("secrets:write");
+ expect(COMPUTER_SESSION_KEY_SCOPES).not.toContain("secrets:write");
+ });
+});
diff --git a/cloudflare-workers/api-edge/src/api_keys.ts b/cloudflare-workers/api-edge/src/api_keys.ts
index 75606a5a..c07bc3ec 100644
--- a/cloudflare-workers/api-edge/src/api_keys.ts
+++ b/cloudflare-workers/api-edge/src/api_keys.ts
@@ -30,10 +30,36 @@ export async function createAPIKey(
return (await createAPIKeyWithHash(env, input)).created;
}
+/**
+ * The scopes a new key names (work 095). The computer API reads them; a key
+ * made before scopes carries `sandbox:*`, which it reads as all of these.
+ * `secrets:write` is deliberately absent: no key gets it without naming it,
+ * and nothing here mints one that does.
+ */
+export const KEY_SCOPES: readonly string[] = [
+ "sessions:read",
+ "sessions:write",
+ "asks:answer",
+ "terminals",
+];
+
+/**
+ * The scopes of the one-hour key a computer session mints. Listed apart from
+ * KEY_SCOPES so that widening people's keys never widens a session's.
+ */
+export const COMPUTER_SESSION_KEY_SCOPES: readonly string[] = [
+ "sessions:read",
+ "sessions:write",
+ "asks:answer",
+ "terminals",
+];
+
export interface CreateAPIKeyInput {
orgID: string;
userID: string;
name: string;
+ /** Every minter names its scopes; there is no default. */
+ scopes: readonly string[];
expiresAt?: number;
sessionKey?: string;
}
@@ -54,12 +80,17 @@ export async function createAPIKeyWithHash(
const prefix = plainKey.slice(0, 8);
const id = crypto.randomUUID();
const now = Math.floor(Date.now() / 1000);
+ const scopes = [...new Set(input.scopes)];
+ if (scopes.length === 0 || scopes.some((scope) => !/^[a-z]+(:[a-z]+)?$/.test(scope))) {
+ // An empty list or a wildcard would read as "everything" downstream.
+ throw new Error("api key scopes must be an explicit list");
+ }
await env.OPENCOMPUTER_DB.prepare(
`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)`,
+ VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?10, ?7, ?8, ?9)`,
)
- .bind(id, input.orgID, input.userID, hash, prefix, input.name, now, input.expiresAt ?? null, input.sessionKey ?? null)
+ .bind(id, input.orgID, input.userID, hash, prefix, input.name, now, input.expiresAt ?? null, input.sessionKey ?? null, scopes.join(","))
.run();
const created: CreatedAPIKey = {
@@ -68,7 +99,7 @@ export async function createAPIKeyWithHash(
name: input.name,
key: plainKey,
keyPrefix: prefix,
- scopes: ["sandbox:*"],
+ scopes,
createdAt: new Date(now * 1000).toISOString(),
...(input.expiresAt !== undefined
? { expiresAt: new Date(input.expiresAt * 1000).toISOString() }
diff --git a/cloudflare-workers/api-edge/src/cli_auth.test.ts b/cloudflare-workers/api-edge/src/cli_auth.test.ts
index a91eb30e..2c00d69f 100644
--- a/cloudflare-workers/api-edge/src/cli_auth.test.ts
+++ b/cloudflare-workers/api-edge/src/cli_auth.test.ts
@@ -451,7 +451,8 @@ describe("CLI device authorization edge contract", () => {
expect(insert?.args[2]).toBe(userID);
expect(insert?.args[3]).toMatch(/^[0-9a-f]{64}$/);
expect(insert?.args).not.toContain(body.credential.key);
- expect(insert?.sql).toContain("'sandbox:*'");
+ expect(insert?.sql).not.toContain("sandbox:*");
+ expect(insert?.args[9]).toBe("sessions:read,sessions:write,asks:answer,terminals");
const [, providerInit] = providerFetch.mock.calls[0];
const providerForm = new URLSearchParams(String(providerInit?.body));
expect(providerForm.get("grant_type")).toBe("urn:ietf:params:oauth:grant-type:device_code");
@@ -504,7 +505,7 @@ describe("CLI device authorization edge contract", () => {
hash: insert?.args[3],
name: "oc CLI on test",
kind: "user",
- scopes: ["sandbox:*"],
+ scopes: ["sessions:read", "sessions:write", "asks:answer", "terminals"],
expiresAt: null,
userId: userID,
});
@@ -843,12 +844,13 @@ describe("CLI identity and credential lifecycle", () => {
expect(body.name).toBe("Dashboard key");
expect(body.key).toMatch(/^osb_[0-9a-f]{64}$/);
expect(body.keyPrefix).toBe(String(body.key).slice(0, 8));
- expect(body.scopes).toEqual(["sandbox:*"]);
+ expect(body.scopes).toEqual(["sessions:read", "sessions:write", "asks:answer", "terminals"]);
const insert = db.executed.find((entry) =>
entry.sql.includes("INSERT INTO api_keys") && entry.args[5] === "Dashboard key"
);
expect(insert?.args).not.toContain(body.key);
expect(insert?.args[7]).toBeNull();
+ expect(insert?.args[9]).toBe("sessions:read,sessions:write,asks:answer,terminals");
});
it("stores and returns an expiry when a dashboard key is created with one", async () => {
diff --git a/cloudflare-workers/api-edge/src/computer_api.test.ts b/cloudflare-workers/api-edge/src/computer_api.test.ts
index e0201a40..2b90e418 100644
--- a/cloudflare-workers/api-edge/src/computer_api.test.ts
+++ b/cloudflare-workers/api-edge/src/computer_api.test.ts
@@ -815,7 +815,7 @@ describe("key create and revoke tell blue", () => {
hash: await hashAPIKey(created.key),
name: "ci",
kind: "user",
- scopes: ["sandbox:*"],
+ scopes: ["sessions:read", "sessions:write", "asks:answer", "terminals"],
expiresAt: null,
createdAt: created.createdAt,
userId: USER,
diff --git a/cloudflare-workers/api-edge/src/dashboard.ts b/cloudflare-workers/api-edge/src/dashboard.ts
index f4f03d28..10decc67 100644
--- a/cloudflare-workers/api-edge/src/dashboard.ts
+++ b/cloudflare-workers/api-edge/src/dashboard.ts
@@ -26,7 +26,7 @@ import {
} from "./autumn_webhook";
import { planSchedule, summarizeWorkMinutePlan, trialEndsAt } from "./billing_summary";
import { emitBillingEvent, type BillingEventsEnv } from "./billing_events";
-import { createAPIKeyWithHash } from "./api_keys";
+import { KEY_SCOPES, createAPIKeyWithHash } from "./api_keys";
import { createdKeyForSync, revokeComputerKey, syncComputerKey } from "./computer_keys";
import {
proxyManagedAgents,
@@ -502,6 +502,7 @@ async function handleCreateAPIKey(
orgID: caller.orgID,
userID: caller.userID,
name,
+ scopes: KEY_SCOPES,
expiresAt,
});
// Tell the computer API about the key (work 084); never the key itself.
diff --git a/cloudflare-workers/api-edge/src/index.test.ts b/cloudflare-workers/api-edge/src/index.test.ts
index bfabff8f..3a57b2cd 100644
--- a/cloudflare-workers/api-edge/src/index.test.ts
+++ b/cloudflare-workers/api-edge/src/index.test.ts
@@ -696,6 +696,8 @@ describe("/internal/computer-keys", () => {
expect(runs[0][1]).toBe("org-x");
expect(runs[0][2]).toBe("computer");
expect(runs[0][8]).toBeNull();
+ // Work 095: an explicit list, never a wildcard and never secrets:write.
+ expect(runs[0][9]).toBe("sessions:read,sessions:write,asks:answer,terminals");
});
it("records the session a key is for, and refuses a malformed one", async () => {
diff --git a/cloudflare-workers/api-edge/src/index.ts b/cloudflare-workers/api-edge/src/index.ts
index f823c6ba..23e88ba0 100644
--- a/cloudflare-workers/api-edge/src/index.ts
+++ b/cloudflare-workers/api-edge/src/index.ts
@@ -46,7 +46,13 @@ import {
} from "./billing_onramp";
export { ManagedAgentBillingService } from "./managed_agent_billing_service";
import { runRetentionSweep } from "./retention";
-import { createAPIKey, createAPIKeyWithHash, hashAPIKey } from "./api_keys";
+import {
+ COMPUTER_SESSION_KEY_SCOPES,
+ KEY_SCOPES,
+ createAPIKey,
+ createAPIKeyWithHash,
+ hashAPIKey,
+} from "./api_keys";
import { envWithD1Retry } from "./d1_retry";
import {
handleAgentWebhookInvocation,
@@ -1429,6 +1435,7 @@ async function authCLIExchange(req: Request, env: Env, ctx?: ExecutionContext):
orgID: identity.org.id,
userID: identity.user.id,
name: credentialName,
+ scopes: KEY_SCOPES,
});
credential = made.created;
// Tell the computer API about the key (work 084); never the key itself.
@@ -2187,6 +2194,7 @@ export default {
orgID: parsed.org_id,
userID: COMPUTER_PRINCIPAL,
name: "Computer session",
+ scopes: COMPUTER_SESSION_KEY_SCOPES,
expiresAt: Math.floor(Date.now() / 1000) + 3600,
...(sessionKey ? { sessionKey } : {}),
});