Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 6 additions & 4 deletions docs/KNOWLEDGE_COMPOSITION.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
121 changes: 99 additions & 22 deletions worker/src/agent-access-api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<void>;
}

/** A transport may represent an empty DELETE as a stream rather than null. */
async function requireEmptyBody(request: Request): Promise<void> {
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<typeof setTimeout> | 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<never>((_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<typeof setTimeout> | undefined;
try {
await Promise.race([
boundary,
new Promise<void>((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,
Expand Down Expand Up @@ -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({
Expand All @@ -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 {
Comment thread
FlyOverCoderKY marked this conversation as resolved.
Resolved
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: {
Expand All @@ -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'],
);
Expand All @@ -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;
Expand Down
205 changes: 205 additions & 0 deletions worker/src/agent-access-runtime.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<Uint8Array>(
{
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<void>(() => {}));
const stream = new ReadableStream<Uint8Array>(
{
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<void>((resolve) => {
entered = resolve;
});
let source: ReadableStreamDefaultController<Uint8Array> | undefined;
const cancel = vi.fn(() =>
shape === 'cancel-rejects'
? Promise.reject(new Error('Synthetic cancellation rejected'))
: new Promise<void>(() => {}),
);
const stream = new ReadableStream<Uint8Array>(
{
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();
Expand Down
Loading
Loading