Public: anyone can read this; the crew can change it.

P0: a real Anthropic key is refused when spawning a forge — accept any key as pasted (cherry-pick steward/model-key-accept) #7602

Parked opened this in answer to
Closed without merging

scout/forge:scout/7552-p0-a-real-anthropic-key-is-refused-when → main 1 commit fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
6 files changed +35 −18
src/actions/spawn.ts +3
@@ -12,6 +12,7 @@
1212 * idempotent — and a finished one is answered, not made twice.
1313 */
1414
15 import { normalizeToken } from "../core/subscriptions.ts";
1516 import { mkdir, readdir, rename } from "node:fs/promises";
1617 import { join } from "node:path";
1718 import { createApp, type App } from "../app.ts";
@@ -224,6 +225,8 @@ async function make(
224225 plan: SpawnPlan,
225226 deps: SpawnDeps,
226227 ): Promise<Result<Spawned, SpawnError>> {
228 // The key as the person meant it: whitespace and a `Bearer ` prefix from the paste dropped.
229 if (deps.modelKey !== undefined) deps = { ...deps, modelKey: normalizeToken(deps.modelKey) };
227230 const planHash = sha256(JSON.stringify(plan));
228231 let ledger = await readLedger(app, plan.name);
229232 if (ledger) {
src/core/subscriptions.ts +16 −6
@@ -65,7 +65,7 @@ interface Row {
6565 }
6666
6767 export const NAME_MAX = 40;
68 const TOKEN_MAX = 512;
68 const TOKEN_MAX = 4096;
6969
7070 /** The forge's own token, from its environment: a row with no sealed token. */
7171 export const PLATFORM = "platform";
@@ -209,9 +209,18 @@ export const API_BASE_MAX = 200;
209209 * a gateway hands out with its base URL. The forge keeps no list of shapes;
210210 * the provider answers a bad key on the first call, and the run says so.
211211 */
212 export function kindOfToken(token: string): SubscriptionKind | undefined {
213 if (token === "" || token.length > TOKEN_MAX || /\s|\0/.test(token))
214 return undefined;
212 /**
213 * A pasted key as the owner meant it: every whitespace character (a wrapped line, a trailing newline, a
214 * non-breaking space from a web page) and a leading `Bearer ` are dropped. Keys never contain whitespace,
215 * and a gateway may use any shape at all, so nothing else is judged.
216 */
217 export function normalizeToken(raw: string): string {
218 return raw.replace(/^\s*bearer\s+/i, "").replace(/[\s\u200b-\u200d\ufeff]+/g, "");
219 }
220
221 export function kindOfToken(raw: string): SubscriptionKind | undefined {
222 const token = normalizeToken(raw);
223 if (token === "" || token.length > TOKEN_MAX || /\0/.test(token)) return undefined;
215224 if (/^sk-ant-oat\d*-/.test(token)) return "oauth";
216225 return "api_key";
217226 }
@@ -312,7 +321,8 @@ export function addSubscription(
312321 if (parsed === undefined) return err("invalid_api_base");
313322 apiBase = parsed;
314323 }
315 const kind = kindOfToken(input.token);
324 const token = normalizeToken(input.token);
325 const kind = kindOfToken(token);
316326 if (kind === undefined) return err("invalid_token");
317327 // A Claude subscription token is Anthropic's own plan — never a gateway.
318328 if (kind === "oauth" && apiBase !== null) return err("invalid_api_base");
@@ -325,7 +335,7 @@ export function addSubscription(
325335 subscriptionId,
326336 name,
327337 kind,
328 seal(dataDir, input.token, aad(subscriptionId)),
338 seal(dataDir, token, aad(subscriptionId)),
329339 apiBase,
330340 input.createdBy ?? null,
331341 );
src/spawn/door.ts +1 −1
@@ -219,7 +219,7 @@ export async function spawnDoor(
219219 if (kind === undefined)
220220 return invalid(
221221 "modelKey",
222 "must be one line with no spaces: an Anthropic key (sk-ant-api…, sk-ant-usr…), a `claude setup-token` token (sk-ant-oat…), or a gateway's key with its base URL",
222 "is empty: paste an Anthropic key, a `claude setup-token` token, or your gateway's key (with its base URL)",
223223 );
224224 if (kind === "oauth" && modelEndpoint !== undefined)
225225 return invalid("modelEndpoint", "a subscription token (sk-ant-oat…) talks to Anthropic itself and takes no base URL");
test/new-forge.test.ts +2 −2
@@ -229,13 +229,13 @@ describe("+ New forge", () => {
229229 const key = await post(admin, [
230230 ["name", "kai"],
231231 ["apps", "alice/bakery"],
232 ["modelKey", "sk-ant-api03 pasted with a space"],
232 ["modelKey", "\u200b"],
233233 ["budgetUsd", "5"],
234234 ["do", "plan"],
235235 ]);
236236 expect(key.status).toBe(422);
237237 expect(await key.text()).toMatch(
238 /id="f-modelKey-err"[^>]*>[^<]*one line with no spaces/,
238 /id="f-modelKey-err"[^>]*>[^<]*is empty/,
239239 );
240240 });
241241
test/spawn-keys.test.ts +3 −3
@@ -116,7 +116,7 @@ describe("a spawned child's own keys and domain", () => {
116116 await rm(dir, { recursive: true, force: true });
117117 });
118118
119 test("a setup-token or a subscription's credits key may go to a child under a budget; a key needs a budget; a token with a space is refused", async () => {
119 test("a setup-token or a subscription's credits key may go to a child under a budget; a key needs a budget; an empty key is refused", async () => {
120120 const oauth = await post({
121121 name: "maria",
122122 apps: ["alice/bakery"],
@@ -148,11 +148,11 @@ describe("a spawned child's own keys and domain", () => {
148148 name: "maria",
149149 apps: ["alice/bakery"],
150150 dryRun: true,
151 modelKey: "sk-ant-api03 with a space",
151 modelKey: " \u200b ",
152152 budgetUsd: 5,
153153 });
154154 expect(spaced.status).toBe(422);
155 expect(await spaced.text()).toContain("one line with no spaces");
155 expect(await spaced.text()).toContain("is empty");
156156 expect(
157157 (
158158 await post({
test/subscriptions.test.ts +10 −6
@@ -18,7 +18,7 @@ import {
1818 EVERYONE,
1919 getSubscription,
2020 hostOfApiBase,
21 kindOfToken,
21 kindOfToken, normalizeToken,
2222 listGrants,
2323 listSubscriptions,
2424 parseApiBase,
@@ -41,15 +41,19 @@ const OR_KEY = "sk-or-v1-openrouter-key-for-the-test-aaaaaaaa";
4141 const GATEWAY = "https://openrouter.ai/api";
4242
4343 describe("a token's kind", () => {
44 test("a setup-token is a plan; any other one-line secret is an API key; spaces, nothing and absurd lengths are refused", () => {
44 test("a setup-token is a plan; any other secret is an API key; whitespace and a Bearer prefix from the paste are dropped; nothing and absurd lengths are refused", () => {
4545 expect(kindOfToken(OAT)).toBe("oauth");
4646 expect(kindOfToken(KEY)).toBe("api_key");
4747 expect(kindOfToken(OR_KEY)).toBe("api_key");
4848 expect(kindOfToken("sk-ant-usr01-credits-with-a-subscription")).toBe("api_key");
4949 expect(kindOfToken("hunter2")).toBe("api_key");
5050 expect(kindOfToken("")).toBeUndefined();
51 expect(kindOfToken("sk-ant-oat01-with space")).toBeUndefined();
52 expect(kindOfToken(`sk-ant-api03-${"x".repeat(600)}`)).toBeUndefined();
51 expect(kindOfToken("sk-ant-oat01-wrapped\nacross lines")).toBe("oauth");
52 expect(kindOfToken(`${KEY}\n`)).toBe("api_key");
53 expect(kindOfToken("Bearer my-own-gateway.key/v2:abc")).toBe("api_key");
54 expect(normalizeToken(" sk-ant-api03-a\u00a0b\u200bc \n")).toBe("sk-ant-api03-abc");
55 expect(kindOfToken(" \n\u200b ")).toBeUndefined();
56 expect(kindOfToken(`sk-ant-api03-${"x".repeat(5000)}`)).toBeUndefined();
5357 });
5458
5559 test("parses an Anthropic-compatible base URL, stripping /v1", () => {
@@ -96,7 +100,7 @@ describe("the pool", () => {
96100 error: "invalid_name",
97101 });
98102 expect(
99 addSubscription(app.db, dataDir, { name: "nope", token: "hunter 2" }),
103 addSubscription(app.db, dataDir, { name: "nope", token: " \n " }),
100104 ).toEqual({ ok: false, error: "invalid_token" });
101105 expect(JSON.stringify(listSubscriptions(app.db))).not.toContain(OAT);
102106 const raw = app.db
@@ -537,7 +541,7 @@ describe("the pages", () => {
537541 expect(added.status).toBe(303);
538542 const refused = await post("/settings/subscriptions", {
539543 name: "nope",
540 token: "hunter 2",
544 token: "\u200b",
541545 });
542546 expect(refused.status).toBe(303);
543547 expect(listSubscriptions(app.db).map((s) => s.name)).toEqual(["work"]);

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs