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 deb94f1..267ee49 100644 --- a/worker/src/agent-access-api.ts +++ b/worker/src/agent-access-api.ts @@ -16,12 +16,85 @@ import { type AgentBrowserOptions, } from './agent-authority'; +const browserBodyTimeoutMs = 10_000; + export interface AgentAccessApiOptions extends AgentBrowserOptions { readonly service: AgentAccessServicePort; readonly configuration: AgentAccessConfiguration; 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() + browserBodyTimeoutMs; + 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, browserBodyTimeoutMs); + request.signal.addEventListener('abort', onAbort, { once: true }); + if (request.signal.aborted) onAbort(); + }); + // 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 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); + } + } + } + } 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, @@ -82,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({ @@ -90,16 +178,18 @@ 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. + currentContext = await currentMutationContext(); + } + await options.service.revokeGrant(currentContext, grantId); response = new Response(null, { status: 204, headers: { @@ -125,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'], ); @@ -152,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 6224ed2..db4cd2e 100644 --- a/worker/src/agent-access-runtime.test.ts +++ b/worker/src/agent-access-runtime.test.ts @@ -424,6 +424,211 @@ describe('Agent Access host composition', () => { ).rejects.toThrow(); }); + 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(); + 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', + }); + let emptyChunks = 0; + const input = + shape === 'null' + ? undefined + : shape === 'zero-byte-array' + ? new Uint8Array(0) + : 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 }), + 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', + ] 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 === '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 === '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', + 'immediate-empty', + ] 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(controller) { + entered(); + if (shape === 'immediate-empty') + controller.enqueue(new Uint8Array(0)); + }, + 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 if (shape === 'immediate-empty') + await vi.advanceTimersByTimeAsync(10_000); + 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();