From 674c98059e2ca92b49c1673a51078ca94f6c0224 Mon Sep 17 00:00:00 2001 From: Nathan Rover Date: Wed, 11 Nov 2026 23:07:12 -0500 Subject: [PATCH 1/2] Accept bounded empty transport bodies for agent grant revocation --- worker/src/agent-access-api.ts | 81 ++++++++- worker/src/agent-access-runtime.test.ts | 199 +++++++++++++++++++++ worker/src/agent-browser-freshness.test.ts | 72 ++++++++ 3 files changed, 346 insertions(+), 6 deletions(-) diff --git a/worker/src/agent-access-api.ts b/worker/src/agent-access-api.ts index deb94f1..48daba6 100644 --- a/worker/src/agent-access-api.ts +++ b/worker/src/agent-access-api.ts @@ -22,6 +22,61 @@ export interface AgentAccessApiOptions extends AgentBrowserOptions { readonly limit: (request: Request) => Promise; } +/** A transport may represent an empty DELETE as a stream rather than null. */ +async function requireEmptyBody(request: Request): Promise { + if (request.body === null) return; + const reader = request.body.getReader(); + const invalid = new ApiError(400, 'invalid_request'); + const timeout = new ApiError(408, 'request_timeout'); + const expiresAt = performance.now() + 10_000; + let timer: ReturnType | undefined; + let onAbort: (() => void) | undefined; + let cancelled = false; + const cancel = (reason: unknown): void => { + if (cancelled) return; + cancelled = true; + // A source may never settle cancellation; it cannot hold this route open. + try { + void reader.cancel(reason).catch(() => {}); + } catch { + /* Best effort. */ + } + }; + const boundary = new Promise((_resolve, reject) => { + onAbort = () => { + reject(timeout); + cancel(timeout); + }; + timer = setTimeout(onAbort, 10_000); + request.signal.addEventListener('abort', onAbort, { once: true }); + if (request.signal.aborted) onAbort(); + }); + // Also observe an already-aborted boundary if header validation fails first. + void boundary.catch(() => {}); + try { + const declared = request.headers.get('Content-Length'); + if (declared !== null && !/^0+$/u.test(declared)) throw invalid; + // No payload bytes are buffered. Bound even a source yielding only empty chunks. + for (let reads = 0; reads < 16; reads += 1) { + if (performance.now() >= expiresAt) throw timeout; + const chunk = await Promise.race([reader.read(), boundary]); + if (performance.now() >= expiresAt || request.signal.aborted) + throw timeout; + if (chunk.done) return; + if (chunk.value.byteLength !== 0) throw invalid; + } + throw invalid; + } catch (error) { + cancel(error); + throw error; + } finally { + if (timer !== undefined) clearTimeout(timer); + if (onAbort !== undefined) + request.signal.removeEventListener('abort', onAbort); + reader.releaseLock(); + } +} + /** Existing-login consent and owner-only views. Public OAuth routes live in AA. */ export function createAgentAccessApi( options: AgentAccessApiOptions, @@ -90,16 +145,30 @@ export function createAgentAccessApi( scopes: options.configuration.scopes, }); } else if (grant !== null) { - if ( - url.search !== '' || - (request.method === 'DELETE' && request.body !== null) - ) - throw new ApiError(400, 'invalid_request'); + if (url.search !== '') throw new ApiError(400, 'invalid_request'); const grantId = boundedString(grant[1], 1, 128); if (request.method === 'GET') response = json(await options.service.getGrant(context, grantId)); else { - await options.service.revokeGrant(context, grantId); + let currentContext = context; + if (request.body !== null) { + await requireEmptyBody(request); + // Empty input still adds an awaited boundary before a protected mutation. + sameBrowserHeaders(); + const current = await requireAgentBrowserContext( + request, + options, + true, + ); + sameBrowserHeaders(); + if ( + current.authenticated.rawSessionId !== sessionId || + current.context.access.principalId !== principalId + ) + throw new ApiError(403, 'browser_credential_changed'); + currentContext = current.context; + } + await options.service.revokeGrant(currentContext, grantId); response = new Response(null, { status: 204, headers: { diff --git a/worker/src/agent-access-runtime.test.ts b/worker/src/agent-access-runtime.test.ts index 6224ed2..abae72f 100644 --- a/worker/src/agent-access-runtime.test.ts +++ b/worker/src/agent-access-runtime.test.ts @@ -424,6 +424,205 @@ describe('Agent Access host composition', () => { ).rejects.toThrow(); }); + it.each(['null', 'empty-stream', 'zero-byte-array'] as const)( + 'revokes an actual active grant with a %s DELETE body and invalidates access and refresh', + async (shape) => { + const f = await fixture(); + const { tokens, requestId } = await f.approved(); + const path = `/api/agent-access/grants/${requestId}`; + expect(await body(await f.runtime.api(f.request(path)))).toMatchObject({ + status: 'active', + }); + const input = + shape === 'null' + ? undefined + : shape === 'zero-byte-array' + ? new Uint8Array(0) + : new ReadableStream({ + start(controller) { + controller.close(); + }, + }); + const init = { + method: 'DELETE', + ...(input === undefined ? {} : { body: input }), + duplex: 'half', + }; + const request = f.request(path, 'admin', init); + expect(request.body === null).toBe(shape === 'null'); + const result = await f.runtime.api(request); + expect(result?.status).toBe(204); + expect(await body(await f.runtime.api(f.request(path)))).toMatchObject({ + status: 'revoked', + }); + await expect( + f.runtime.service.authenticate({ + token: tokens.access_token, + resource: AGENT_RESOURCE, + }), + ).rejects.toThrow(); + await expect( + f.runtime.service.refresh({ + clientId: client.clientId, + resource: AGENT_RESOURCE, + refreshToken: tokens.refresh_token, + }), + ).rejects.toThrow(); + }, + ); + + it.each([ + 'bytes', + 'large', + 'chunked', + 'false-zero-length', + 'declared-nonempty', + 'endless-empty', + ] as const)( + 'rejects a %s DELETE body, cancels without waiting and leaves the active grant usable', + async (shape) => { + const f = await fixture(); + const { tokens, requestId } = await f.approved(); + let reads = 0; + const cancel = vi.fn(() => new Promise(() => {})); + const stream = new ReadableStream( + { + pull(controller) { + reads += 1; + if ( + shape === 'endless-empty' || + (shape === 'chunked' && reads === 1) + ) + controller.enqueue(new Uint8Array(0)); + else + controller.enqueue( + shape === 'large' + ? new Uint8Array(64 * 1024) + : new Uint8Array([1]), + ); + }, + cancel, + }, + { highWaterMark: 0 }, + ); + const headers = new Headers(); + if (shape === 'false-zero-length') headers.set('Content-Length', '0'); + if (shape === 'declared-nonempty') headers.set('Content-Length', '1'); + const init = { method: 'DELETE', headers, body: stream, duplex: 'half' }; + const request = f.request( + `/api/agent-access/grants/${requestId}`, + 'admin', + init, + ); + const result = await f.runtime.api(request); + expect(result?.status).toBe(400); + expect(await body(result)).toEqual({ error: 'invalid_request' }); + expect(cancel).toHaveBeenCalledOnce(); + expect(request.body?.locked).toBe(false); + expect(reads).toBe( + shape === 'declared-nonempty' + ? 0 + : shape === 'endless-empty' + ? 16 + : shape === 'chunked' + ? 2 + : 1, + ); + expect( + await body( + await f.runtime.api( + f.request(`/api/agent-access/grants/${requestId}`), + ), + ), + ).toMatchObject({ status: 'active' }); + await expect( + f.runtime.service.authenticate({ + token: tokens.access_token, + resource: AGENT_RESOURCE, + }), + ).resolves.toMatchObject({ grantId: requestId }); + }, + ); + + it.each([ + 'stalled', + 'empty-trickle', + 'cancel-rejects', + 'signal-abort', + ] as const)( + 'bounds a %s DELETE body without revoking the active grant', + async (shape) => { + const f = await fixture(); + const { requestId } = await f.approved(); + let entered = () => {}; + const reading = new Promise((resolve) => { + entered = resolve; + }); + let source: ReadableStreamDefaultController | undefined; + const cancel = vi.fn(() => + shape === 'cancel-rejects' + ? Promise.reject(new Error('Synthetic cancellation rejected')) + : new Promise(() => {}), + ); + const stream = new ReadableStream( + { + start(controller) { + source = controller; + }, + pull() { + entered(); + }, + cancel, + }, + { highWaterMark: 0 }, + ); + const controller = new AbortController(); + const init = { + method: 'DELETE', + body: stream, + duplex: 'half', + signal: controller.signal, + }; + const request = f.request( + `/api/agent-access/grants/${requestId}`, + 'admin', + init, + ); + vi.useFakeTimers({ + toFake: ['setTimeout', 'clearTimeout', 'performance'], + }); + try { + let settled = false; + const pending = f.runtime.api(request).finally(() => { + settled = true; + }); + await reading; + if (shape === 'signal-abort') controller.abort(); + else { + await vi.advanceTimersByTimeAsync(9_000); + if (shape === 'empty-trickle') source!.enqueue(new Uint8Array(0)); + await vi.advanceTimersByTimeAsync(999); + expect(settled).toBe(false); + await vi.advanceTimersByTimeAsync(1); + } + const result = await pending; + expect(result?.status).toBe(408); + expect(await body(result)).toEqual({ error: 'request_timeout' }); + expect(cancel).toHaveBeenCalledOnce(); + expect(request.body?.locked).toBe(false); + expect( + await body( + await f.runtime.api( + f.request(`/api/agent-access/grants/${requestId}`), + ), + ), + ).toMatchObject({ status: 'active' }); + } finally { + vi.useRealTimers(); + } + }, + ); + it('honors real stored Admin revocation without caching or reseeding', async () => { const f = await fixture(); const { tokens } = await f.approved(); diff --git a/worker/src/agent-browser-freshness.test.ts b/worker/src/agent-browser-freshness.test.ts index cbc73c8..87486ae 100644 --- a/worker/src/agent-browser-freshness.test.ts +++ b/worker/src/agent-browser-freshness.test.ts @@ -960,6 +960,78 @@ describe('actual AA approval authority after delayed browser input', () => { ); }); +describe('current browser authority after bounded empty revocation input', () => { + it.each(['session', 'role', 'headers'] as const)( + 'refuses %s changes during an empty DELETE read before the actual active grant mutation', + async (kind) => { + const f = await fixture(); + const approval = await f.pendingApproval('device_code'); + const consent = await f.runtime.api( + f.browser('/api/agent-access/approval', 'POST', approval.input), + ); + expect(consent?.status).toBe(200); + await approval.issue(await value(consent)); + const path = '/api/agent-access/grants/' + approval.requestId; + expect(await value(await f.runtime.api(f.browser(path)))).toMatchObject({ + status: 'active', + }); + const reading = barrier(); + const resume = barrier(); + let reads = 0; + let commits = 0; + f.hooks.afterGrantRead = async () => { + reads += 1; + }; + f.hooks.afterGrantCommit = async () => { + commits += 1; + }; + const stream = new ReadableStream( + { + async pull(controller) { + reading.release(); + await resume.ready; + controller.close(); + }, + }, + { highWaterMark: 0 }, + ); + const base = f.browser(path, 'DELETE'); + const init = { + method: 'DELETE', + headers: base.headers, + body: stream, + duplex: 'half', + }; + const request = new Request(base.url, init); + const pending = f.runtime.api(request); + await Promise.race([ + reading.ready, + pending.then(() => { + throw new Error('The actual empty body was not read'); + }), + ]); + try { + if (kind === 'session') await f.revokeSession(); + else if (kind === 'role') await f.revokeAdmin(); + else request.headers.set('Cookie', f.cookie(other)); + } finally { + resume.release(); + } + const result = await pending; + expect(result?.status).toBe(kind === 'session' ? 401 : 403); + expect(reads).toBe(0); + expect(commits).toBe(0); + f.hooks.afterGrantRead = undefined; + f.hooks.afterGrantCommit = undefined; + if (kind === 'session') await f.restoreSession(); + if (kind === 'role') await f.restoreAdmin(); + expect(await value(await f.runtime.api(f.browser(path)))).toMatchObject({ + status: 'active', + }); + }, + ); +}); + describe('staff KB command browser authority around bounded input and real SDK work', () => { it('executes a current authorized browser command through the actual KB service', async () => { const f = await fixture(); From e70bc7cf9bc15f81463ef7f177f6d2e7331b0aa2 Mon Sep 17 00:00:00 2001 From: Nathan Rover Date: Wed, 11 Nov 2026 23:26:50 -0500 Subject: [PATCH 2/2] Keep empty-body revocation reads cooperative and document the deadline --- docs/KNOWLEDGE_COMPOSITION.md | 10 ++-- worker/src/agent-access-api.ts | 78 ++++++++++++++----------- worker/src/agent-access-runtime.test.ts | 42 +++++++------ 3 files changed, 73 insertions(+), 57 deletions(-) diff --git a/docs/KNOWLEDGE_COMPOSITION.md b/docs/KNOWLEDGE_COMPOSITION.md index 959cf79..fbcffa0 100644 --- a/docs/KNOWLEDGE_COMPOSITION.md +++ b/docs/KNOWLEDGE_COMPOSITION.md @@ -253,11 +253,13 @@ after the service returns; it does not roll back an approval already committed. Host-owned JSON POST bodies for portal reads, staff commands, agent test reports and consent approvals have a ten-second total read deadline, in -addition to the byte limit. Trickle input does not restart that deadline. +addition to the byte limit. Empty-body grant revocations share that deadline: +nonempty input is rejected, and zero-byte chunks periodically yield to let +the deadline and cancellation run. Trickle input does not restart the deadline. An expired body read returns `408 request_timeout`, cancels the reader and -starts no KB read or consent/report command. This bounds body reading; -authentication, storage work and SDK-owned protocol parsing keep their own -boundaries. +starts no KB/grant read or consent/report/revocation command. This bounds body +reading; authentication, storage work and SDK-owned protocol parsing keep their +own boundaries. `/api/agent-access/*` composes the released protocol plus browser-only consent and known-grant controls. Discovery is at diff --git a/worker/src/agent-access-api.ts b/worker/src/agent-access-api.ts index 48daba6..267ee49 100644 --- a/worker/src/agent-access-api.ts +++ b/worker/src/agent-access-api.ts @@ -16,6 +16,8 @@ import { type AgentBrowserOptions, } from './agent-authority'; +const browserBodyTimeoutMs = 10_000; + export interface AgentAccessApiOptions extends AgentBrowserOptions { readonly service: AgentAccessServicePort; readonly configuration: AgentAccessConfiguration; @@ -28,7 +30,7 @@ async function requireEmptyBody(request: Request): Promise { const reader = request.body.getReader(); const invalid = new ApiError(400, 'invalid_request'); const timeout = new ApiError(408, 'request_timeout'); - const expiresAt = performance.now() + 10_000; + const expiresAt = performance.now() + browserBodyTimeoutMs; let timer: ReturnType | undefined; let onAbort: (() => void) | undefined; let cancelled = false; @@ -47,25 +49,41 @@ async function requireEmptyBody(request: Request): Promise { reject(timeout); cancel(timeout); }; - timer = setTimeout(onAbort, 10_000); + timer = setTimeout(onAbort, browserBodyTimeoutMs); request.signal.addEventListener('abort', onAbort, { once: true }); if (request.signal.aborted) onAbort(); }); - // Also observe an already-aborted boundary if header validation fails first. + // Input validation can fail before the race; keep any boundary rejection handled. void boundary.catch(() => {}); try { const declared = request.headers.get('Content-Length'); if (declared !== null && !/^0+$/u.test(declared)) throw invalid; - // No payload bytes are buffered. Bound even a source yielding only empty chunks. - for (let reads = 0; reads < 16; reads += 1) { + // No bytes are buffered. Empty chunks periodically yield so deadline/abort + // callbacks can run even when a source completes every read immediately. + let emptyReads = 0; + while (true) { if (performance.now() >= expiresAt) throw timeout; const chunk = await Promise.race([reader.read(), boundary]); if (performance.now() >= expiresAt || request.signal.aborted) throw timeout; if (chunk.done) return; if (chunk.value.byteLength !== 0) throw invalid; + emptyReads += 1; + if (emptyReads === 16) { + emptyReads = 0; + let yieldTimer: ReturnType | undefined; + try { + await Promise.race([ + boundary, + new Promise((resolve) => { + yieldTimer = setTimeout(resolve, 0); + }), + ]); + } finally { + if (yieldTimer !== undefined) clearTimeout(yieldTimer); + } + } } - throw invalid; } catch (error) { cancel(error); throw error; @@ -137,6 +155,21 @@ export function createAgentAccessApi( sameBrowserHeaders(); const principalId = context.access.principalId; const sessionId = authenticated.rawSessionId; + async function currentMutationContext() { + sameBrowserHeaders(); + const current = await requireAgentBrowserContext( + request, + options, + true, + ); + sameBrowserHeaders(); + if ( + current.authenticated.rawSessionId !== sessionId || + current.context.access.principalId !== principalId + ) + throw new ApiError(403, 'browser_credential_changed'); + return current.context; + } if (path === '/api/agent-access/state') { if (url.search !== '') throw new ApiError(400, 'invalid_request'); response = json({ @@ -154,19 +187,7 @@ export function createAgentAccessApi( if (request.body !== null) { await requireEmptyBody(request); // Empty input still adds an awaited boundary before a protected mutation. - sameBrowserHeaders(); - const current = await requireAgentBrowserContext( - request, - options, - true, - ); - sameBrowserHeaders(); - if ( - current.authenticated.rawSessionId !== sessionId || - current.context.access.principalId !== principalId - ) - throw new ApiError(403, 'browser_credential_changed'); - currentContext = current.context; + currentContext = await currentMutationContext(); } await options.service.revokeGrant(currentContext, grantId); response = new Response(null, { @@ -194,7 +215,7 @@ export function createAgentAccessApi( } else { if (url.search !== '') throw new ApiError(400, 'invalid_request'); const body = optionalKeysObject( - await readJson(request, { timeoutMs: 10_000 }), + await readJson(request, { timeoutMs: browserBodyTimeoutMs }), ['requestId', 'decision'], ['approvedScopes', 'userCode'], ); @@ -221,21 +242,8 @@ export function createAgentAccessApi( }; // Body input is an awaited browser boundary. Account/role authority in // AA cannot establish that the original host session is still live. - sameBrowserHeaders(); - const current = await requireAgentBrowserContext( - request, - options, - true, - ); - sameBrowserHeaders(); - if ( - current.authenticated.rawSessionId !== sessionId || - current.context.access.principalId !== principalId - ) - throw new ApiError(403, 'browser_credential_changed'); - response = json( - await options.service.approve(current.context, command), - ); + const currentContext = await currentMutationContext(); + response = json(await options.service.approve(currentContext, command)); } // The service may have awaited private reads or a committed mutation. // Withhold its response if the original browser no longer has authority; diff --git a/worker/src/agent-access-runtime.test.ts b/worker/src/agent-access-runtime.test.ts index abae72f..db4cd2e 100644 --- a/worker/src/agent-access-runtime.test.ts +++ b/worker/src/agent-access-runtime.test.ts @@ -424,7 +424,12 @@ describe('Agent Access host composition', () => { ).rejects.toThrow(); }); - it.each(['null', 'empty-stream', 'zero-byte-array'] as const)( + it.each([ + 'null', + 'empty-stream', + 'zero-byte-array', + 'finite-empty-chunks', + ] as const)( 'revokes an actual active grant with a %s DELETE body and invalidates access and refresh', async (shape) => { const f = await fixture(); @@ -433,16 +438,22 @@ describe('Agent Access host composition', () => { expect(await body(await f.runtime.api(f.request(path)))).toMatchObject({ status: 'active', }); + let emptyChunks = 0; const input = shape === 'null' ? undefined : shape === 'zero-byte-array' ? new Uint8Array(0) - : new ReadableStream({ - start(controller) { - controller.close(); + : new ReadableStream( + { + pull(controller) { + if (shape === 'finite-empty-chunks' && emptyChunks++ < 33) + controller.enqueue(new Uint8Array(0)); + else controller.close(); + }, }, - }); + { highWaterMark: 0 }, + ); const init = { method: 'DELETE', ...(input === undefined ? {} : { body: input }), @@ -477,7 +488,6 @@ describe('Agent Access host composition', () => { 'chunked', 'false-zero-length', 'declared-nonempty', - 'endless-empty', ] as const)( 'rejects a %s DELETE body, cancels without waiting and leaves the active grant usable', async (shape) => { @@ -489,10 +499,7 @@ describe('Agent Access host composition', () => { { pull(controller) { reads += 1; - if ( - shape === 'endless-empty' || - (shape === 'chunked' && reads === 1) - ) + if (shape === 'chunked' && reads === 1) controller.enqueue(new Uint8Array(0)); else controller.enqueue( @@ -520,13 +527,7 @@ describe('Agent Access host composition', () => { expect(cancel).toHaveBeenCalledOnce(); expect(request.body?.locked).toBe(false); expect(reads).toBe( - shape === 'declared-nonempty' - ? 0 - : shape === 'endless-empty' - ? 16 - : shape === 'chunked' - ? 2 - : 1, + shape === 'declared-nonempty' ? 0 : shape === 'chunked' ? 2 : 1, ); expect( await body( @@ -549,6 +550,7 @@ describe('Agent Access host composition', () => { 'empty-trickle', 'cancel-rejects', 'signal-abort', + 'immediate-empty', ] as const)( 'bounds a %s DELETE body without revoking the active grant', async (shape) => { @@ -569,8 +571,10 @@ describe('Agent Access host composition', () => { start(controller) { source = controller; }, - pull() { + pull(controller) { entered(); + if (shape === 'immediate-empty') + controller.enqueue(new Uint8Array(0)); }, cancel, }, @@ -598,6 +602,8 @@ describe('Agent Access host composition', () => { }); await reading; if (shape === 'signal-abort') controller.abort(); + else if (shape === 'immediate-empty') + await vi.advanceTimersByTimeAsync(10_000); else { await vi.advanceTimersByTimeAsync(9_000); if (shape === 'empty-trickle') source!.enqueue(new Uint8Array(0));