diff --git a/AGENTS.md b/AGENTS.md index 5b63e62b..7a8ec59f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -165,6 +165,10 @@ The core innovation: instead of 2,500 MCP tools (~244K tokens), two tools handle - `src/events/callback.ts` opens the sealed destination secret ANS presents, checks the KV subscription record and synchronously signs the MCP callback, with no Cloudflare API call. ANS owns retries. - `npm run test:events` runs local workerd coverage with simulated external HTTP endpoints. See `docs/mcp-events.md` for live tests and lifecycle constraints. +### Asset upload tokens + +`GlobalOutbound` checks the configured API origin and base path before selecting credentials for any `execute` request. The four asset upload POSTs (`/pages/assets/check-missing`, `/pages/assets/upload`, `/pages/assets/upsert-hashes`, `/accounts/{account_id}/workers/assets/upload`) require the upload JWT rather than the MCP session token. `src/asset-upload-token.ts` checks shape and expiry; the upload API owns signature and upload-scope validation. The proxy rejects missing or unusable JWTs without sending the request, does not follow redirects or retry network failures, and skips MCP scope refusal review for these requests. All other requests keep session authentication and policy checks. + ### Worker Loader API Code execution uses Cloudflare's Worker Loader API to dynamically create isolated worker instances. The API token is passed via props (never enters user code isolate). A `globalOutbound` service restricts network access. @@ -189,7 +193,7 @@ The consent page offers minimal, read-only and full-access templates. Minimal is - Forge merges operations that exist under both accounts and zones into `/{account_or_zone}/{account_or_zone_id}/…`; `processSpec` splits each back into its `/accounts/{account_id}/…` and `/zones/{zone_id}/…` paths, so Code Mode sees paths it can call as written and `execute` finds an endpoint's permissions by the path it calls. Since cloudflare/forge#59 (`openapi@fdbc7d9`), the document gives `account_or_zone` its `accounts`/`zones` enum; `cf` fills it from `--zone` - All `$ref` references resolved inline before storage - `openapi.forge.json` describes each response body as the API sends it: in Cloudflare's envelope (`{ success, errors, messages, result }`, plus `result_info` on lists), or bare for the few APIs without one. Releases before `openapi@d8e3026` (30 October 2026) left the envelope out of most success schemas; nothing here supports them any more. Nothing rewrites a response or its schema: `spec.json` keeps each schema as it is, `cloudflare.request()` returns the body as it is (JSON parsed, text as a string, binary as a `Uint8Array`, GraphQL as `{ data, errors? }`) and throws for a failed request, and the direct tools check and return the body as it is (see Envelope under Response schema checks) -- `cloudflare.request()` takes what an operation declares the way `fetch` does: `{ method, path, query, headers, body }`. `headers` carries the spec's header parameters (`cf-r2-jurisdiction`, `If-Match`), and `GlobalOutbound` always replaces `Authorization` with the session's token. The body's JavaScript type alone decides how it is sent: a string, bytes, `Blob`, `FormData`, `URLSearchParams` or stream as it is, anything else as JSON. `Content-Type` defaults to `application/json` for JSON and strings, and `FormData` always gets `fetch`'s own. Nothing sniffs a string: Zaraz publish, the one endpoint whose JSON body is a string, needs `JSON.stringify`. `contentType` and `rawBody` are honoured but no longer documented. `tests/execute-requests.test.ts` sends every header parameter and request media type the spec declares +- `cloudflare.request()` takes what an operation declares the way `fetch` does: `{ method, path, query, headers, body }`. `headers` carries the spec's header parameters (`cf-r2-jurisdiction`, `If-Match`), and `GlobalOutbound` selects credentials as described under Asset upload tokens. The body's JavaScript type alone decides how it is sent: a string, bytes, `Blob`, `FormData`, `URLSearchParams` or stream as it is, anything else as JSON. `Content-Type` defaults to `application/json` for JSON and strings, and `FormData` always gets `fetch`'s own. Nothing sniffs a string: Zaraz publish, the one endpoint whose JSON body is a string, needs `JSON.stringify`. `contentType` and `rawBody` are honoured but no longer documented. `tests/execute-requests.test.ts` sends every header parameter and request media type the spec declares - Products and minimal operation metadata extracted - Three artifacts: `spec.json`, `products.json`, and `permissions.json`, each operation's `x-api-token-group` by path and method, which `execute` uses to explain a refused request - A lone 2025-era `tools/list` for the direct tools is answered by `src/tools/tool-list-response.ts` from the listing encoded once per isolate, before the SDK sees it: the SDK's per-request `JSON.stringify` of the multi-MB listing was ~23% of the Worker's production CPU. Cursors, 2026-07-28 requests and anything unusual still go to the SDK, and `tests/tool-list-response.test.ts` checks both answers are identical diff --git a/README.md b/README.md index 02c2c3ac..2ea01db8 100644 --- a/README.md +++ b/README.md @@ -175,6 +175,17 @@ execute({ }); ``` +### Static asset uploads + +In Code Mode, mint the upload JWT with the MCP connection's credentials, then pass it as `Authorization: Bearer ` only on the asset POSTs. The outbound proxy applies the same authentication rules to `cloudflare.request()` and `fetch()`. + +| Product | Get an upload JWT | Send assets with the JWT | Finish with MCP connection credentials | +| --- | --- | --- | --- | +| Pages | `GET /accounts/{id}/pages/projects/{project}/upload-token` | `POST /pages/assets/check-missing`, `/pages/assets/upload`, and `/pages/assets/upsert-hashes` | Create the Pages deployment with the multipart manifest. | +| Workers | `POST /accounts/{id}/workers/scripts/{script}/assets-upload-session` | `POST /accounts/{id}/workers/assets/upload?base64=true` with base64 file bytes in multipart `FormData` | Create the Worker version with the completion JWT in multipart metadata at `assets.jwt`. | + +The proxy does not substitute the MCP credential for a missing or unusable upload JWT, follow upload redirects, or retry ambiguous network failures. Cloudflare validates the JWT and its upload scope. An upload authentication error does not prompt an MCP OAuth reconnect; use a fresh JWT for the intended project or Worker instead. Do not return JWTs in tool output or logs. + ### GraphQL Analytics API The server automatically detects and handles Cloudflare's GraphQL Analytics API endpoints. GraphQL queries work seamlessly through the same `execute` tool: diff --git a/src/asset-upload-token.ts b/src/asset-upload-token.ts new file mode 100644 index 00000000..01cd769f --- /dev/null +++ b/src/asset-upload-token.ts @@ -0,0 +1,57 @@ +import { z } from 'zod' + +const ASSET_UPLOAD_PATHS = new Set([ + '/pages/assets/check-missing', + '/pages/assets/upload', + '/pages/assets/upsert-hashes' +]) + +const WORKERS_ASSET_UPLOAD_PATH = /^\/accounts\/[0-9a-f]{32}\/workers\/assets\/upload$/ + +const JWT_SEGMENT = /^[A-Za-z0-9_-]+$/ + +const CLOCK_SKEW_SECONDS = 60 + +export function isAssetUploadPath(path: string): boolean { + return ASSET_UPLOAD_PATHS.has(path) || WORKERS_ASSET_UPLOAD_PATH.test(path) +} + +const JwtObject = z.looseObject({}) + +const JwtClaims = z.looseObject({ exp: z.number() }) + +function decodeSegment(segment: string): string { + const base64 = segment.replaceAll('-', '+').replaceAll('_', '/') + return atob(base64 + '='.repeat((4 - (base64.length % 4)) % 4)) +} + +function isUnexpiredJwt(token: string, nowSeconds: number): boolean { + const segments = token.split('.') + if (segments.length !== 3 || !segments.every((segment) => JWT_SEGMENT.test(segment))) { + return false + } + try { + const header = JwtObject.safeParse(JSON.parse(decodeSegment(segments[0]))) + const claims = JwtClaims.safeParse(JSON.parse(decodeSegment(segments[1]))) + if (!header.success || !claims.success) { + return false + } + return claims.data.exp + CLOCK_SKEW_SECONDS > nowSeconds + } catch { + return false + } +} + +export function assetUploadAuthorization( + request: Request, + path: string, + sessionToken: string, + nowSeconds: number = Date.now() / 1000 +): { token?: string } | undefined { + if (request.method !== 'POST' || !isAssetUploadPath(path)) { + return undefined + } + const match = /^Bearer (\S+)$/.exec(request.headers.get('authorization') ?? '') + const token = match?.[1] + return token && token !== sessionToken && isUnexpiredJwt(token, nowSeconds) ? { token } : {} +} diff --git a/src/tools/execute.ts b/src/tools/execute.ts index 8ef1bb19..5c36d2d4 100644 --- a/src/tools/execute.ts +++ b/src/tools/execute.ts @@ -20,6 +20,7 @@ import { authorize, explainRefusal, isCatalogScope } from '../api-permissions' import { MISSING_SCOPE_HEADER, REFUSAL_HINT_HEADER, reviewResponse } from '../api-refusals' import { policyRefusalHint, sameSubscription, subscriptionCreate } from '../policy-guards' import type { SubscriptionKey } from '../policy-guards' +import { assetUploadAuthorization } from '../asset-upload-token' import { DECLINED_HINT, NEEDS_CONFIRMATION_HEADER, @@ -99,10 +100,17 @@ type GlobalOutboundProps = { */ export class GlobalOutbound extends WorkerEntrypoint { async fetch(request: Request): Promise { - const allowed = new URL(this.env.CLOUDFLARE_API_BASE).hostname - const requested = new URL(request.url).hostname - if (requested !== allowed) { - return new Response(`Forbidden: requests to ${requested} are not allowed`, { status: 403 }) + const apiBase = new URL(this.env.CLOUDFLARE_API_BASE) + const requested = new URL(request.url) + const basePath = apiBase.pathname.replace(/\/$/, '') + if ( + requested.origin !== apiBase.origin || + (requested.pathname !== basePath && !requested.pathname.startsWith(`${basePath}/`)) + ) { + return new Response('Forbidden: request is outside the Cloudflare API base URL.', { + status: 403, + headers: { [NOT_SENT_HEADER]: '1' } + }) } const policyHint = await policyRefusalHint(request, this.ctx.props.confirmedSubscription) if (policyHint) { @@ -122,28 +130,46 @@ export class GlobalOutbound extends WorkerEntrypoint { } ) } - // Inject auth header — token comes from props, never enters user code isolate. - // It replaces any Authorization the code sent: appended, the two would be - // joined into one value the API can't read. The headers are rebuilt from - // their entries: in workerd, a copy made with new Headers(request.headers) + const path = requested.pathname.slice(basePath.length) + const { apiToken } = this.ctx.props + const upload = assetUploadAuthorization(request, path, apiToken) + if (upload && !upload.token) { + return new Response( + 'This endpoint requires an upload JWT. Get one from the Pages upload-token or Workers assets-upload-session endpoint, then pass it as Authorization: Bearer .', + { status: 401, headers: { [NOT_SENT_HEADER]: '1' } } + ) + } + + // Appending Authorization would join two bearers into one unusable value. + // Rebuild from entries: in workerd, a copy made with new Headers(request.headers) // lost every header but Authorization when fetchWithRetry copied it again. const headers = new Headers([ ...[...request.headers].filter(([name]) => name.toLowerCase() !== 'authorization'), - ['Authorization', `Bearer ${this.ctx.props.apiToken}`] + ['Authorization', `Bearer ${upload?.token ?? apiToken}`] ]) - const authedRequest = new Request(request, { headers }) + const authedRequest = new Request(request, { + headers, + redirect: upload ? 'manual' : request.redirect + }) // No 429 is retried here: the sandbox waits out rate limits, where the wait // holds back the run's other requests and counts against its wait budget. const response = await fetchWithRetry(authedRequest, undefined, { caller: this.ctx.props.fetchWithRetryCaller, - retryRateLimited: false + retryRateLimited: false, + ...(upload && { maxRetries: 0 }) }) + if (upload && [301, 302, 303, 307, 308].includes(response.status)) { + const redirectHeaders = new Headers(response.headers) + redirectHeaders.delete('Location') + return new Response(response.body, { status: response.status, headers: redirectHeaders }) + } - const basePath = new URL(this.env.CLOUDFLARE_API_BASE).pathname.replace(/\/$/, '') - const path = new URL(request.url).pathname.slice(basePath.length) // What the response's rate limits ask of the run: the sandbox holds its // next requests back for it, and tells the agent about a 429. const noticed = await withRateLimitNotice(response, request.method, path) + if (upload) { + return noticed + } // Cloudflare's 401/403 bodies don't say why, and some lists come back empty // instead of refused. Report both as refusals with an explanation the @@ -677,7 +703,9 @@ When the session has access to multiple accounts, pass account_id. ${ACCOUNT_DIS To turn on a product for an account, such as R2, create an account subscription: POST /accounts/{account_id}/subscriptions with body { rate_plan: { id } }. Rate plan IDs include r2_paid (R2 Storage) and teams_free (Zero Trust). Only plans with no base charge can be created. The server asks the user to confirm first. Your code must be an async arrow function that returns the result. -A failed request throws an Error naming the method, path, HTTP status and Cloudflare's errors. For HTTP 401/403 it also says which permission the endpoint needs and whether reconnecting will help. Requests slow down by themselves near a rate limit. For HTTP 429 the error says how long Cloudflare asks to wait; until then, requests under the same limit are not sent and throw too, so stop instead of catching and continuing. +A failed request throws an Error naming the method, path, HTTP status and Cloudflare's errors. For HTTP 401/403 on a request using the MCP connection, it also says which permission the endpoint needs and whether reconnecting will help. Requests slow down by themselves near a rate limit. For HTTP 429 the error says how long Cloudflare asks to wait; until then, requests under the same limit are not sent and throw too, so stop instead of catching and continuing. + +For static assets, first get a JWT using the Pages project's GET upload-token or the Worker's POST assets-upload-session endpoint. Pass that JWT as Authorization: Bearer only to the Pages asset POSTs (check-missing, upload, upsert-hashes) or the Workers assets/upload POST (multipart FormData with query: { base64: true }). Do not pass the JWT as authorization when creating a deployment or Worker version; the Workers upload completion JWT goes in version metadata at assets.jwt. An upload JWT refusal is not an MCP OAuth scope challenge. Example: Worker with bindings (a multipart/form-data upload): async () => { diff --git a/tests/asset-upload-token.test.ts b/tests/asset-upload-token.test.ts new file mode 100644 index 00000000..e01d5d87 --- /dev/null +++ b/tests/asset-upload-token.test.ts @@ -0,0 +1,99 @@ +import { describe, expect, it } from 'vitest' +import { assetUploadAuthorization, isAssetUploadPath } from '../src/asset-upload-token' + +const NOW = 1_800_000_000 +const SESSION = 'session-token' +const ACCOUNT = '0123456789abcdef0123456789abcdef' + +function base64Url(value: object): string { + return btoa(JSON.stringify(value)).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '') +} + +function jwt(claims: object): string { + return `${base64Url({ alg: 'HS256', typ: 'JWT' })}.${base64Url(claims)}.${base64Url({ test: true })}` +} + +function post(token: string | undefined, method = 'POST'): Request { + return new Request('https://api.cloudflare.com/client/v4/pages/assets/upload', { + method, + headers: token === undefined ? {} : { authorization: `Bearer ${token}` } + }) +} + +describe('isAssetUploadPath', () => { + it.each([ + '/pages/assets/check-missing', + '/pages/assets/upload', + '/pages/assets/upsert-hashes', + `/accounts/${ACCOUNT}/workers/assets/upload` + ])('accepts %s', (path) => { + expect(isAssetUploadPath(path)).toBe(true) + }) + + it.each([ + '/pages/assets/upload/extra', + '/pages/assets', + `/accounts/${ACCOUNT}/workers/scripts/app/assets-upload-session`, + `/accounts/${ACCOUNT}/pages/projects/site/upload-token`, + '/accounts/not-an-id/workers/assets/upload', + '/user/tokens' + ])('refuses %s', (path) => { + expect(isAssetUploadPath(path)).toBe(false) + }) +}) + +describe('assetUploadAuthorization', () => { + const valid = jwt({ exp: NOW + 300 }) + + it('keeps an unexpired upload JWT on an asset upload path', () => { + expect(assetUploadAuthorization(post(valid), '/pages/assets/upload', SESSION, NOW)).toEqual({ + token: valid + }) + }) + + it('ignores the bearer on any other path', () => { + expect( + assetUploadAuthorization(post(valid), `/accounts/${ACCOUNT}/workers/scripts`, SESSION, NOW) + ).toBeUndefined() + }) + + it('ignores the bearer on a GET', () => { + expect( + assetUploadAuthorization(post(valid, 'GET'), '/pages/assets/upload', SESSION, NOW) + ).toBeUndefined() + }) + + it('ignores an expired JWT', () => { + expect( + assetUploadAuthorization(post(jwt({ exp: NOW - 120 })), '/pages/assets/upload', SESSION, NOW) + ).toEqual({}) + }) + + it('ignores a JWT without an expiry', () => { + expect( + assetUploadAuthorization(post(jwt({ sub: 'x' })), '/pages/assets/upload', SESSION, NOW) + ).toEqual({}) + }) + + it('ignores a bearer that is not a JWT', () => { + expect( + assetUploadAuthorization(post('someone-else'), '/pages/assets/upload', SESSION, NOW) + ).toEqual({}) + expect(assetUploadAuthorization(post('a.b.c'), '/pages/assets/upload', SESSION, NOW)).toEqual( + {} + ) + }) + + it('ignores the session token itself', () => { + const session = jwt({ exp: NOW + 300 }) + expect(assetUploadAuthorization(post(session), '/pages/assets/upload', session, NOW)).toEqual( + {} + ) + }) + + it('ignores a request without Authorization', () => { + expect(assetUploadAuthorization(post(undefined), '/pages/assets/upload', SESSION, NOW)).toEqual( + {} + ) + }) +}) diff --git a/tests/execute-requests.test.ts b/tests/execute-requests.test.ts index 03ddc0cd..73e491f5 100644 --- a/tests/execute-requests.test.ts +++ b/tests/execute-requests.test.ts @@ -22,6 +22,12 @@ const ACCOUNT = '00000000000000000000000000000001' const ZONE = '00000000000000000000000000000002' const API_TOKEN = 'test-api-token-execute-requests' +function uploadToken(purpose = 'upload', lifetime = 300): string { + const encode = (value: object) => + btoa(JSON.stringify(value)).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '') + return `${encode({ alg: 'HS256', typ: 'JWT' })}.${encode({ exp: Math.floor(Date.now() / 1000) + lifetime, purpose })}.${encode({ test: true })}` +} + afterEach(async () => { await clearKv(env.OAUTH_KV) await clearSpec() @@ -296,6 +302,169 @@ describe('execute: how headers are sent', () => { expect(received[0].headers.get('authorization')).toBe(`Bearer ${API_TOKEN}`) }) + it('uses the Pages upload JWT for the three asset calls, but not for deployment', async () => { + const uploadJwt = uploadToken() + const project = `/accounts/${ACCOUNT}/pages/projects/site` + const { received, isError, text } = await run( + `async () => { + const { result } = await cloudflare.request({ method: "GET", path: "${project}/upload-token" }); + const headers = { Authorization: "Bearer " + result.jwt }; + const { result: missing } = await cloudflare.request({ method: "POST", path: "/pages/assets/check-missing", headers, body: { hashes: ["file-hash"] } }); + await cloudflare.request({ method: "POST", path: "/pages/assets/upload", headers, body: missing.map(key => ({ key, value: "aGk=", metadata: { contentType: "text/plain" }, base64: true })) }); + await cloudflare.request({ method: "POST", path: "/pages/assets/upsert-hashes", headers, body: { hashes: ["file-hash"] } }); + const form = new FormData(); + form.set("manifest", JSON.stringify({ "/index.html": "file-hash" })); + return cloudflare.request({ method: "POST", path: "${project}/deployments", headers, body: form }); + }`, + ({ path }) => + HttpResponse.json( + cfSuccess( + path.endsWith('/upload-token') + ? { jwt: uploadJwt } + : path.endsWith('/check-missing') + ? ['file-hash'] + : {} + ) + ) + ) + expect(isError, text).toBe(false) + expect( + received.map(({ method, path, headers }) => [method, path, headers.get('authorization')]) + ).toEqual([ + ['GET', `${project}/upload-token`, `Bearer ${API_TOKEN}`], + ['POST', '/pages/assets/check-missing', `Bearer ${uploadJwt}`], + ['POST', '/pages/assets/upload', `Bearer ${uploadJwt}`], + ['POST', '/pages/assets/upsert-hashes', `Bearer ${uploadJwt}`], + ['POST', `${project}/deployments`, `Bearer ${API_TOKEN}`] + ]) + expect(JSON.parse(received[2].text)).toEqual([ + { key: 'file-hash', value: 'aGk=', metadata: { contentType: 'text/plain' }, base64: true } + ]) + expect((await formOf(received[4])).get('manifest')).toBe('{"/index.html":"file-hash"}') + }) + + it('uses the Workers upload JWT for multipart assets and the completion JWT in version metadata', async () => { + const uploadJwt = uploadToken() + const completionJwt = uploadToken('complete') + const script = `/accounts/${ACCOUNT}/workers/scripts/site` + const upload = `/accounts/${ACCOUNT}/workers/assets/upload` + const { received, isError, text } = await run( + `async () => { + const { result } = await cloudflare.request({ method: "POST", path: "${script}/assets-upload-session", body: { manifest: { "/index.html": { hash: "file-hash", size: 2 } } } }); + const form = new FormData(); + form.append("file-hash", new Blob(["aGk="], { type: "text/html" }), "file-hash"); + const response = await fetch("${API_BASE}${upload}?base64=true", { method: "POST", headers: { authorization: "Bearer " + result.jwt }, body: form }); + if (!response.ok) throw new Error("Upload failed: " + response.status); + const { result: completion } = await response.json(); + const version = new FormData(); + version.set("metadata", new Blob([JSON.stringify({ assets: { jwt: completion.jwt } })], { type: "application/json" })); + return cloudflare.request({ method: "POST", path: "${script}/versions", body: version }); + }`, + ({ path }) => + HttpResponse.json( + cfSuccess( + path === upload + ? { jwt: completionJwt } + : path.endsWith('/assets-upload-session') + ? { jwt: uploadJwt, buckets: [['file-hash']] } + : {} + ) + ) + ) + expect(isError, text).toBe(false) + expect( + received.map(({ method, path, headers }) => [method, path, headers.get('authorization')]) + ).toEqual([ + ['POST', `${script}/assets-upload-session`, `Bearer ${API_TOKEN}`], + ['POST', upload, `Bearer ${uploadJwt}`], + ['POST', `${script}/versions`, `Bearer ${API_TOKEN}`] + ]) + expect(received[1].query.get('base64')).toBe('true') + const asset = (await formOf(received[1])).get('file-hash') + expect(asset).toBeInstanceOf(File) + expect(asset).toMatchObject({ name: 'file-hash', type: 'text/html' }) + expect(await (asset as File).text()).toBe('aGk=') + const metadata = (await formOf(received[2])).get('metadata') + expect(await (metadata as File).text()).toBe(JSON.stringify({ assets: { jwt: completionJwt } })) + }) + + it.each([ + ['missing', ''], + ['malformed', 'headers: { Authorization: "Bearer not-an-upload-token" },'], + ['expired', `headers: { Authorization: "Bearer ${uploadToken('expired', -120)}" },`] + ])('does not send an asset upload with a %s JWT', async (_, headers) => { + const { received, text, isError } = await run( + `async () => cloudflare.request({ method: "POST", path: "/pages/assets/check-missing", ${headers} body: { hashes: ["a"] } })` + ) + expect(received).toHaveLength(0) + expect(isError).toBe(true) + expect(text).toContain('upload JWT') + }) + + it.each([ + `http://${new URL(API_BASE).host}${new URL(API_BASE).pathname}/pages/assets/upload`, + `${new URL(API_BASE).origin}/other/v4a/pages/assets/upload` + ])('does not send credentials outside the configured API base (%s)', async (url) => { + let calls = 0 + server.use( + http.post(url, () => { + calls++ + return HttpResponse.json(cfSuccess({})) + }) + ) + const { text } = await run( + `async () => (await fetch("${url}", { method: "POST", headers: { Authorization: "Bearer ${uploadToken()}" } })).status` + ) + expect(calls).toBe(0) + expect(text).toContain('403') + }) + + it('does not follow an upload redirect to a different path', async () => { + const path = `/accounts/${ACCOUNT}/workers/assets/upload` + const { received, text, isError } = await run( + `async () => cloudflare.request({ method: "POST", path: "${path}", query: { base64: true }, headers: { Authorization: "Bearer ${uploadToken()}" }, body: new FormData() })`, + (_, count) => + count === 1 + ? new HttpResponse(null, { + status: 307, + headers: { Location: `${API_BASE}/pages/assets/upload` } + }) + : HttpResponse.json(cfSuccess({})) + ) + expect(received.map(({ path }) => path)).toEqual([path]) + expect(isError, text).toBe(true) + expect(text).toContain('HTTP 307') + }) + + it('does not replay an asset upload after an ambiguous network failure', async () => { + const { received, isError } = await run( + `async () => cloudflare.request({ method: "POST", path: "/pages/assets/upload", headers: { Authorization: "Bearer ${uploadToken()}" }, body: [] })`, + () => HttpResponse.error() + ) + expect(received).toHaveLength(1) + expect(isError).toBe(true) + }) + + it("sends the session's token when the code names a JWT for any other path", async () => { + const received = await send( + `method: "GET", path: "${PATH}", headers: { Authorization: "Bearer ${uploadToken()}" }` + ) + expect(received.headers.get('authorization')).toBe(`Bearer ${API_TOKEN}`) + }) + + it('reads a refused asset upload as Cloudflare sent it, without asking for a scope', async () => { + const { text, isError } = await run( + `async () => cloudflare.request({ method: "POST", path: "/pages/assets/check-missing", headers: { Authorization: "Bearer ${uploadToken()}" }, body: {} })`, + () => + HttpResponse.json(cfError([{ code: 8000013, message: 'Authorization failed' }]), { + status: 403 + }) + ) + expect(isError).toBe(true) + expect(text).toContain('8000013') + expect(text).not.toContain('insufficient_scope') + }) + it('leaves out a header whose value is undefined or null', async () => { const received = await send( `method: "GET", path: "${PATH}", headers: { "cf-r2-jurisdiction": undefined, "If-None-Match": null, Prefer: "respond-async" }` diff --git a/tests/scope-challenge.test.ts b/tests/scope-challenge.test.ts index 02759a07..4c11db51 100644 --- a/tests/scope-challenge.test.ts +++ b/tests/scope-challenge.test.ts @@ -32,6 +32,7 @@ const GET_DNS = `async () => cloudflare.request({ method: "GET", path: "${DNS_PA const ACCOUNT_ID = 'acc-1' const KV_PATH = `/accounts/${ACCOUNT_ID}/storage/kv/namespaces` const CREATE_KV = `async () => cloudflare.request({ method: "POST", path: "${KV_PATH}", body: { title: "t" } })` +const WORKERS_UPLOAD_PATH = `/accounts/${ZONE_ID}/workers/assets/upload` const CHATGPT_REDIRECT = 'https://chatgpt.com/connector_platform_oauth_redirect' beforeEach(async () => { @@ -54,6 +55,9 @@ beforeEach(async () => { }, '/accounts/{account_id}/storage/kv/namespaces': { post: { summary: 'Create a Namespace', 'x-api-token-group': ['Workers KV Storage Write'] } + }, + '/accounts/{account_id}/workers/assets/upload': { + post: { summary: 'Upload Worker Assets', 'x-api-token-group': ['Workers Scripts Write'] } } }, ['dns'] @@ -112,6 +116,29 @@ describe('execute', () => { expectChallenge(await executeModern(token, CREATE_KV), 'workers-kv-storage.write') }) + it('does not request more OAuth scopes when the upload JWT is refused', async () => { + const token = await connectWithOAuth(BASELINE) + const uploadJwt = `eyJhbGciOiJIUzI1NiJ9.${btoa(JSON.stringify({ exp: Math.floor(Date.now() / 1000) + 300 })).replace(/=+$/, '')}.signature` + server.use( + http.post(`${API_BASE}${WORKERS_UPLOAD_PATH}`, ({ request }) => { + expect(request.headers.get('Authorization')).toBe(`Bearer ${uploadJwt}`) + return HttpResponse.json(cfError([{ code: 10000, message: 'Authentication error' }]), { + status: 401 + }) + }) + ) + const response = await executeModern( + token, + `async () => cloudflare.request({ method: "POST", path: "${WORKERS_UPLOAD_PATH}", query: { base64: true }, headers: { Authorization: "Bearer ${uploadJwt}" }, body: new FormData() })` + ) + const body = await parseMcpResult(response) + expect(response.status).toBe(200) + expect(response.headers.has('WWW-Authenticate')).toBe(false) + expect(body.result?._meta).not.toHaveProperty('mcp/www_authenticate') + expect(body.result?.isError).toBe(true) + expect(toolText(body)).toMatch(/HTTP 401[\s\S]*10000/) + }) + it('does not challenge a 401 when the connection holds an accepted scope', async () => { const token = await connectWithOAuth([...BASELINE, 'workers-kv-storage.write']) const response = await executeModern(token, CREATE_KV)