diff --git a/README.md b/README.md index d21f5e5..c250e1b 100644 --- a/README.md +++ b/README.md @@ -36,6 +36,13 @@ targets Codex-provider mode. Their compatibility remains unproven until actual per-client runs; other T3 providers are also unproven. An official SDK protocol test does not establish support for those applications. +Hosts can list the signed-in owner's linked agents with the owner-scoped, +paginated `listGrants` ([owner grant listing](docs/API.md#owner-grant-listing)) +and can opt individual protected-resource authenticators in to bounded +multipart uploads with header-only bearer credentials +([opt-in multipart uploads](docs/HTTP.md#opt-in-multipart-uploads)). Both are +unreleased source additions and change no package version. + Read the [architecture](docs/ARCHITECTURE.md), [API](docs/API.md), and [HTTP composition](docs/HTTP.md) before wiring a host. The [project plan](docs/PROJECT_PLAN.md) distinguishes source work from host gates; diff --git a/docs/API.md b/docs/API.md index b32e03d..c25013e 100644 --- a/docs/API.md +++ b/docs/API.md @@ -80,6 +80,8 @@ camelCase; OAuth token responses use the standard snake_case fields. | `revokeToken` | `{ clientId, token, tokenTypeHint? }` | void; unknown tokens are harmless | | `getGrant` | browser context, `grantId` | `GrantView` | | `revokeGrant` | browser context, `grantId` | void | +| `listGrants` | browser context, `{ ownerPrincipal, cursor?, limit?, statuses? }` | `GrantPage` | +| `backfillGrantIndex` | `{ cursor?, limit? }` (host maintenance, no browser context) | `BackfillGrantIndexResult` | `BrowserApprovalContext` is exactly `{ authentication: "browser-session", access: AccessContext }`. It comes from @@ -116,6 +118,103 @@ current permissions with the approved scope definitions; `roles` and `entitlements` are always empty. The host must authorize the actual resource operation using this restricted context. +## Owner grant listing + +Hosts that render a connected-agents page call `listGrants` from the trusted +browser session instead of keeping their own owner-to-grant index: + +```ts +const page = await service.listGrants(browserContext, { + ownerPrincipal: browserContext.access.principalId, + limit: 20, +}); +for (const grant of page.grants) render(grant); // escape display strings +// Next page: pass page.nextCursor back unchanged; null means no older entries. +// Revoke from a CSRF/origin-checked host mutation using a listed grantId: +await service.revokeGrant(browserContext, selectedGrantId); +``` + +- **Owner-only.** The context must pass the same approval-permission and + current-resolver checks as `getGrant`, and `ownerPrincipal` must equal the + trusted session principal; otherwise the call fails with `access_denied`. + A non-string, empty, control-character, or over-512-character principal and + unknown input fields are `invalid_request`. +- **Bounded pages.** `limit` defaults to 20 and + may not exceed 100. A page performs one owner-index + head read plus at most `limit` index reads and `limit` grant-head reads; it + never scans storage. Results are newest indexed first. Because inactive, + filtered, or removed grants still consume their slot, a page may hold fewer + than `limit` grants, even none, while `nextCursor` is non-null. Approvals + made while paging appear on a fresh first page and never duplicate entries. +- **Owner-bound cursor.** `nextCursor` is an opaque `pgc1.` string bound to + the owner's index partition. It carries a public, unkeyed checksum that + detects inconsistent or accidental edits; it is not tamper-proof, because a + caller can recompute the checksum. A cursor from another owner, an edit that + does not match its checksum, or any malformed value fails with + `invalid_request` and reveals nothing. Safety never depends on the cursor: + every page re-verifies the session and owner, a cursor for another owner's + partition is always rejected, and a position past the owner's current head + is clamped. A deliberately recomputed position only repositions the caller + within their own grants. +- **Safe views.** Each item is exactly the `GrantView` that `getGrant` returns. + Credential hashes, consent fingerprints, PKCE challenges, redirects, and raw + storage records are never included. +- **Statuses.** Listing covers grants the owner approved. Each item carries + its current status: `pending` (approved, credentials not yet issued), + `active`, `revoked`, or `expired` (derived from the absolute expiry as in + `getGrant`). Unapproved authorization requests and denied requests are not + linked agents and are not listed; `getGrant` still reads them by ID. Pass + `statuses`, a non-empty set of distinct values from `pending`, `active`, + `revoked`, and `expired`, to keep only matching items, for example + `statuses: ["active"]`. Because denied requests are never listed, a + `denied` filter value is rejected with `invalid_request` instead of + silently returning empty pages. + +The owner index is a separate Storage Core collection, +`agent-access.owner-index.v1`, with one partition per hashed +(issuer, resource, owner). Storage Core transactions are single-partition, so +the index cannot share the grant partition's transaction and no cross-partition +atomicity is claimed. Instead, approval commits the owner's index entry (head +counter, membership, and entry in one owner-partition transaction) _before_ the +grant's approval transition. A committed approval therefore always has an +entry. If the approval is then refused, conflicts, or has an unknown outcome, +the leftover entry is harmless: listing re-reads each authoritative grant head +and returns it only when its issuer, resource, and owner match. Revocation and +expiry change only the grant head, which listing reads, so they need no index +write. Membership records make indexing idempotent. + +**Upgrade provisioning.** After this change every approval also reads and +writes `agent-access.owner-index.v1`. Storage Core adapters that keep all +collections in one table or database need no action. A host whose store +provisions collections, tables, or roles explicitly must provision this +collection with the same read/write/transaction rights as +`agent-access.records.v1` before deploying; otherwise approvals fail closed +with `server_error` while existing grants, tokens, and resource access keep +working. + +Grants approved before this index existed have no entries. They remain fully +usable through `getGrant`, `revokeGrant`, and every token operation, but do not +appear in `listGrants` until the host runs the bounded, idempotent backfill: + +```ts +let cursor: string | null = null; +do { + const step = await service.backfillGrantIndex({ + limit: 100, + ...(cursor === null ? {} : { cursor }), + }); + cursor = step.nextCursor; +} while (cursor !== null); +``` + +Each call scans at most `limit` physical grant rows (default 100, maximum 1000) through Storage Core's authoritative scan and indexes approved, owned +heads for this issuer and resource. Reruns and concurrent approvals add nothing +twice. The scan cursor is the storage adapter's own continuation and is passed +through unchanged. A non-string or empty cursor, or one exceeding the +configured input bound, fails as `invalid_request`; a cursor the adapter +itself rejects fails as `server_error`. Run it from a host maintenance job +behind host rate limits, never from an agent-facing route. + ## Internal credential and validation helpers These implementation helpers are not exported from the package entry point; @@ -156,9 +255,44 @@ when constructed without a status override. ## Retention and activation -The first API deliberately has no list or sweep operation. A host retention -job must keep the entire partition, including consumed refresh hashes and +The API deliberately has no sweep operation; `listGrants` is owner-scoped +discovery, not a retention enumerator. A host retention job must keep the +entire partition, including consumed refresh hashes and Audit events, until the absolute family lifetime has ended. Cleanup must use bounded storage operations and a reviewed host retention policy. Deleting consumed hashes early would disable reuse detection. Source validation does not publish the package, configure a trusted publisher, or activate a host. + +Owner-index rows hold only a grant ID and a sequence number. Listing skips +an entry whose grant head is missing (removed by retention), owned by another +principal, or never approved. Such entries arise only from host retention or +from an approval that failed or lost its outcome after its write-ahead index +commit, so they are rare, but each still occupies a slot on its page. A host +maintenance job may prune them with bounded keyed work. Owner-index and grant +partitions cannot be updated atomically together, so pruning can never be made +strictly race-free against an approval. `approve` commits the index entry +first, and its grant transaction can still commit shortly after the request +deadline, because the deadline is checked before the transaction is sent. +Treat a pending head as possibly in flight well past its expiry: + +1. Read an owner's `entry:` row and the referenced grant head. +2. Skip the entry if the head is owned by that principal and approved, or if + the head is `pending` and the current time is earlier than its request + expiry plus a grace period longer than the host's longest approval request + or storage timeout (for example, at least ten minutes). +3. Otherwise (the head is missing, terminal, approved for another principal, + or pending beyond that grace period), delete the `entry:` and matching + `grant:` rows. +4. Run `backfillGrantIndex` to completion on a recurring schedule, not only + once after pruning. It is idempotent and restores any entry that a residual + race removed for a grant that is now approved for its owner, for example an + approval whose transaction outlived the grace period or a device request + that reused a retained locator. Until that repair runs, such a grant stays + fully usable and revocable by ID but is missing from `listGrants`. + +Hosts that cannot schedule recurring backfill should not prune: dangling +entries are only skipped page slots, never a disclosure or authorization path. + +Never delete an owner-index `head` row while the owner has entries, because +the head orders new entries; a reset head makes later approvals for that owner +fail closed. diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 8b98832..c867d60 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -65,6 +65,17 @@ enables a keyed read; only a matching complete credential hash authorizes its transition. No cross-partition, cross-collection, or role-change transaction is claimed. Required lifecycle work never depends on the lossy Spine event bus. +Owner discovery uses a separate owner-index collection with one partition per +hashed issuer, resource, and owner. Because the index lives in another +partition, it is a write-ahead locator rather than part of the grant +transaction: approval commits the owner entry first, then the grant +transition. Listing re-reads every authoritative grant head and returns it only +when the owner, issuer, and resource still match, so a leftover entry from a +failed approval never surfaces another principal's grant. Status changes touch +only the grant head. Pages are bounded keyed reads, not scans; a bounded, +idempotent backfill indexes grants approved before the index existed. See +[API.md](API.md#owner-grant-listing). + Credentials use Web Crypto randomness and hashing. Raw device, authorization, access, and refresh credentials are returned to the client and never persisted, logged, or included in Audit. This also excludes user codes, PKCE verifiers, diff --git a/docs/HTTP.md b/docs/HTTP.md index c4e4034..637fa14 100644 --- a/docs/HTTP.md +++ b/docs/HTTP.md @@ -61,19 +61,81 @@ attach permissive CORS headers to browser consent endpoints. ## Protected resources -`createProtectedResourceAuthenticator({ service, configuration })` returns -`{ authenticate(request, requiredScopes?) }`. Its Promise resolves to -`DelegatedAccess` or an error `Response`. It accepts one `Authorization: Bearer` +`createProtectedResourceAuthenticator({ service, configuration, multipart? })` +returns `{ authenticate(request, requiredScopes?) }`. Its Promise resolves to +`ProtectedResourceAccess` (a `DelegatedAccess`, plus `form` for an opted-in +multipart request) or an error `Response`. It accepts one `Authorization: Bearer` credential, rejects query `access_token`, and emits a `WWW-Authenticate` challenge with `resource_metadata` on authentication errors. An insufficient scope returns HTTP 403 and the required scope in the challenge. Unavailable authority returns HTTP 503. -The helper never consumes the host's resource body. It rejects form and -multipart content types, so credentials cannot arrive simultaneously in form -and header transports. Hosts requiring form resource operations must implement -their own bounded check for forbidden body credentials around the service's -`authenticate` method. The host still authorizes the actual operation using +By default the helper never consumes the host's resource body. It rejects form +and multipart content types, so credentials cannot arrive simultaneously in +form and header transports. URL-encoded form resource operations remain +unsupported; hosts requiring them must implement their own bounded check for +forbidden body credentials around the service's `authenticate` method. + +### Opt-in multipart uploads + +File-upload endpoints can opt in per authenticator: + +```ts +const uploads = createProtectedResourceAuthenticator({ + service, + configuration, + multipart: { maxBytes: 4 * 1024 * 1024 }, // omit maxBytes for the 1 MiB default +}); +const result = await uploads.authenticate(request, ["files.write"]); +if (result instanceof Response) return result; +const file = result.form?.get("file"); // already parsed and inspected +``` + +Only an authenticator created with `multipart` accepts `multipart/form-data`; +every other authenticator keeps rejecting it. `maxBytes` defaults to +1 MiB (1048576 bytes) and must be a positive integer no larger +than 16 MiB (16777216 bytes); an invalid bound throws `OAuthError` at +construction. Larger uploads need a separate host transport, such as a +pre-authorized direct upload. + +The order is fixed. Header checks run first: Content-Type parameters are +parsed quote-aware (RFC 9110, so quoted values may contain `;`), there must +be exactly one valid RFC 2046 `boundary` parameter (a token, or a quoted +string when it uses spaces or other separators), and a declared +`Content-Length` must be well formed and no larger than the bound. A declared oversize body returns HTTP 413 before any byte +is read. The `Authorization: Bearer` header is then authenticated exactly as +for other requests, so a missing or invalid bearer returns its 401 challenge +without reading the body. Only after the bearer is accepted is the body parsed. Because an upload can +take arbitrarily long, the bearer is authenticated again after parsing, and +the returned access reflects that second check: revocation, expiry, or an +authority change during the upload fails closed. + +Credentials still come only from the header. The body is read from +`request.clone()` through a byte counter, so the host's original `Request` +stays unread on success. An oversized or unbounded stream is stopped at the +bound with HTTP 413. On every rejection after the multipart headers are +examined, both tee branches are cancelled so the upload source itself closes; +the host must not read the body of a rejected request. The parsed form is returned as `result.form` so the host need +not parse twice; the host may instead read its untouched original body. For simple file +uploads, budget about twice `maxBytes` per in-flight upload: the tee retains +the unread original while the clone is parsed. This is not a general memory +bound. The bound limits streamed bytes only; the runtime's parsed `FormData` +adds per-part objects and string representations, so bodies with many small +parts or large text fields can cost more. Keep `maxBytes` small for +endpoints that accept many fields, and apply host request concurrency limits. The authenticator rejects with HTTP +400 `invalid_request` any part named `access_token`, `refresh_token`, +`id_token`, `client_secret`, `client_assertion`, `client_assertion_type`, +`device_code`, or `code_verifier` (case-insensitive), and any part name, text value, +or filename containing an issued Agent Access credential. Query `access_token` is +still rejected. File contents are not scanned. Missing, duplicate, or invalid +boundaries, an empty body, and a malformed multipart body are HTTP 400 +`invalid_request`. Every 4xx rejection carries the usual `WWW-Authenticate` +challenge; a 503 `server_error` (for example, unavailable current authority) +carries none, as for other resource requests. No rejection includes submitted +values. Non-multipart requests through an opted-in +authenticator behave exactly as before and carry no `form`. + +The host still authorizes the actual operation using the returned restricted `access`; accepting a token alone does not authorize an operation. Resource transport CORS, routing, body limits, and host limiter remain host responsibilities. diff --git a/packages/agent-access/README.md b/packages/agent-access/README.md index 3d603b9..d2e6718 100644 --- a/packages/agent-access/README.md +++ b/packages/agent-access/README.md @@ -29,6 +29,23 @@ routes with `createAgentAccessHttp` and protect resource handlers with context for the actual operation. Keep browser approval and its CSRF/origin checks in the host. +Hosts that render a connected-agents page list the signed-in owner's approved +grants with `listGrants(browserContext, { ownerPrincipal, cursor, limit })`. +Pages are owner-only, bounded (default 20, maximum 100), and continue with an +owner-bound opaque cursor. Each item is the same safe `GrantView` that +`getGrant` returns, including its current status, and can be revoked with +`revokeGrant`. Grants approved before listing existed appear after the host +runs the bounded, idempotent `backfillGrantIndex` maintenance call. + +File-upload endpoints may opt in to multipart bodies per authenticator with +`createProtectedResourceAuthenticator({ service, configuration, multipart: { maxBytes } })`. +The bearer still comes only from the `Authorization` header. The body is bounded +before and during streaming, parsed from a clone so the original request stays +readable on success, rejected (with the upload source cancelled) when any part +carries credential fields, and returned as `result.form`. The bearer is +authenticated again after parsing, so revocation during a slow upload fails +closed. Without the option, multipart bodies are rejected as before. + Actual existing-login/Admin-consent integration and per-client acceptance remain open for each host. The fictional protocol example does not establish those results. diff --git a/packages/agent-access/src/crypto.ts b/packages/agent-access/src/crypto.ts index 37e6a82..11b261e 100644 --- a/packages/agent-access/src/crypto.ts +++ b/packages/agent-access/src/crypto.ts @@ -139,3 +139,24 @@ export function scopeFingerprint( })); return sha256(`agent-access:scopes:v1:${JSON.stringify(selected)}`); } + +/** Owner-index partition; unambiguous JSON framing separates the bound identifiers. */ +export function ownerIndexPartition( + issuer: string, + resource: string, + ownerId: string, +): Promise { + return sha256( + `agent-access:owner-index:v1:${JSON.stringify([issuer, resource, ownerId])}`, + ); +} + +/** Integrity check for a public listing cursor. It is not a secret and never authorizes. */ +export async function grantCursorCheck( + ownerPartition: string, + position: number, +): Promise { + return ( + await sha256(`agent-access:grant-cursor:v1:${ownerPartition}.${position}`) + ).slice(0, 22); +} diff --git a/packages/agent-access/src/http.ts b/packages/agent-access/src/http.ts index 4a07625..6936b45 100644 --- a/packages/agent-access/src/http.ts +++ b/packages/agent-access/src/http.ts @@ -51,9 +51,26 @@ export interface AgentAccessHttp { handle(request: Request): Promise; } +export interface ProtectedResourceMultipartOptions { + /** + * Largest accepted multipart body in bytes, enforced on the declared + * Content-Length and on streamed bytes. Defaults to + * 1 MiB (1048576) and cannot exceed 16 MiB (16777216). + */ + readonly maxBytes?: number; +} + export interface ProtectedResourceAuthenticatorOptions { readonly service: AgentAccessServicePort; readonly configuration: AgentAccessConfiguration; + /** Explicit opt-in for multipart/form-data resource requests; omitted rejects them. */ + readonly multipart?: ProtectedResourceMultipartOptions; +} + +/** Delegated access plus, for an accepted multipart request, its inspected form. */ +export interface ProtectedResourceAccess extends DelegatedAccess { + /** Present only for opted-in multipart requests; parsed from a body clone. */ + readonly form?: FormData; } export interface ProtectedResourceAuthenticator { @@ -61,9 +78,14 @@ export interface ProtectedResourceAuthenticator { authenticate( request: Request, requiredScopes?: readonly string[], - ): Promise; + ): Promise; } +/** Conservative default multipart body bound (1 MiB). */ +const DEFAULT_MULTIPART_MAX_BYTES = 1_048_576; +/** Hard multipart body ceiling (16 MiB); larger uploads need a separate host transport. */ +const MAX_MULTIPART_BYTES = 16_777_216; + const DEVICE_GRANT = "urn:ietf:params:oauth:grant-type:device_code"; const MAX_BODY_BYTES = 16_384; const CONTROL = /[\u0000-\u001F\u007F-\u009F]/; @@ -646,16 +668,209 @@ function resourceError( }); } -/** Header-only bearer authentication. The host retains resource routing and body handling. */ +/** Field names that carry OAuth credentials in any body transport. */ +const CREDENTIAL_FIELDS = new Set([ + "access_token", + "refresh_token", + "id_token", + "client_secret", + "client_assertion", + "client_assertion_type", + "device_code", + "code_verifier", +]); +/** Any issued credential shape, wherever it appears in a text field. */ +const ISSUED_CREDENTIAL = /pg[adrt]1\.[A-Za-z0-9_-]{43}\.[A-Za-z0-9_-]{43}/; +const MULTIPART = /^multipart\/form-data(?:\s*;|\s*$)/i; +const BOUNDARY = /^[0-9A-Za-z'()+_,\-./:=? ]{0,69}[0-9A-Za-z'()+_,\-./:=?]$/; + +const TOKEN_CHARACTER = /[!#$%&'*+.^_`|~0-9A-Za-z-]/; + +function multipartMaximum(multipart: unknown): number | undefined { + if (multipart === undefined) return undefined; + if ( + multipart === null || + typeof multipart !== "object" || + Array.isArray(multipart) || + (Object.getPrototypeOf(multipart) !== Object.prototype && + Object.getPrototypeOf(multipart) !== null) || + Object.keys(multipart).some((key) => key !== "maxBytes") + ) + invalidRequest(); + // Only an omitted bound selects the default; null and other values must validate. + const supplied = (multipart as { readonly maxBytes?: unknown }).maxBytes; + const maximum = + supplied === undefined ? DEFAULT_MULTIPART_MAX_BYTES : supplied; + if ( + typeof maximum !== "number" || + !Number.isSafeInteger(maximum) || + maximum < 1 || + maximum > MAX_MULTIPART_BYTES + ) + invalidRequest(); + return maximum; +} + +/** + * RFC 9110 media-type parameters: `*( OWS ";" OWS [ token "=" ( token / + * quoted-string ) ] )`. Quoted values may contain semicolons and escapes. + */ +function mediaParameters(contentType: string): readonly { + readonly name: string; + readonly value: string; + readonly quoted: boolean; +}[] { + const start = contentType.indexOf(";"); + if (start < 0) return []; + const result: { name: string; value: string; quoted: boolean }[] = []; + let index = start; + const whitespace = () => { + while (contentType[index] === " " || contentType[index] === "\t") + index += 1; + }; + while (index < contentType.length) { + if (contentType[index] !== ";") invalidRequest(); + index += 1; + whitespace(); + if (index >= contentType.length) break; + if (contentType[index] === ";") continue; + const nameStart = index; + while ( + index < contentType.length && + TOKEN_CHARACTER.test(contentType[index] as string) + ) + index += 1; + if (index === nameStart || contentType[index] !== "=") invalidRequest(); + const name = contentType.slice(nameStart, index).toLowerCase(); + index += 1; + let value = ""; + let quoted = false; + if (contentType[index] === '"') { + quoted = true; + index += 1; + while (true) { + const character = contentType[index]; + if (character === undefined) return invalidRequest(); + index += 1; + if (character === '"') break; + if (character === "\\") { + const escaped = contentType[index]; + if (escaped === undefined) return invalidRequest(); + value += escaped; + index += 1; + } else value += character; + } + } else { + const valueStart = index; + while ( + index < contentType.length && + TOKEN_CHARACTER.test(contentType[index] as string) + ) + index += 1; + if (index === valueStart) invalidRequest(); + value = contentType.slice(valueStart, index); + } + if (CONTROL.test(value)) invalidRequest(); + result.push({ name, value, quoted }); + whitespace(); + } + return result; +} + +/** Header-only checks that run before the bearer is validated or any byte is read. */ +function assertMultipartHeaders( + request: Request, + contentType: string, + maximum: number, +): void { + const boundaries = mediaParameters(contentType).filter( + (parameter) => parameter.name === "boundary", + ); + if (boundaries.length !== 1) invalidRequest(); + const boundary = boundaries[0] as { value: string; quoted: boolean }; + // An unquoted boundary is a token; a quoted one may also use RFC 2046 spaces and punctuation. + if ( + !BOUNDARY.test(boundary.value) || + (!boundary.quoted && + ![...boundary.value].every((character) => + TOKEN_CHARACTER.test(character), + )) + ) + invalidRequest(); + const declared = request.headers.get("Content-Length"); + if (declared !== null) { + if (!/^(?:0|[1-9][0-9]*)$/.test(declared)) invalidRequest(); + // Reject a declared oversize body before reading or buffering any byte. + if (Number(declared) > maximum) invalidRequest(413); + } + if (request.body === null || request.bodyUsed) invalidRequest(); +} + +/** + * Parses a clone of the body through a byte counter, so the host's original + * request stays unread and an oversized stream is cancelled at the bound. + */ +async function multipartForm( + request: Request, + contentType: string, + maximum: number, +): Promise { + let copy: Request; + try { + copy = request.clone(); + } catch { + return invalidRequest(); + } + if (copy.body === null) invalidRequest(); + let total = 0; + let exceeded = false; + const counted = copy.body.pipeThrough( + new TransformStream({ + transform(chunk, controller) { + if (!(chunk instanceof Uint8Array)) { + controller.error(new OAuthError("invalid_request")); + return; + } + total += chunk.byteLength; + if (total > maximum) { + exceeded = true; + controller.error(new OAuthError("invalid_request", 413)); + return; + } + controller.enqueue(chunk); + }, + }), + ); + let form: FormData; + try { + form = await new Response(counted, { + headers: { "Content-Type": contentType }, + }).formData(); + } catch { + return invalidRequest(exceeded ? 413 : 400); + } + if (exceeded) invalidRequest(413); + for (const [name, value] of form.entries()) { + if (CREDENTIAL_FIELDS.has(name.toLowerCase())) invalidRequest(); + // Part names, text values, and filenames are all scanned for issued credentials. + const text = typeof value === "string" ? value : value.name; + if (ISSUED_CREDENTIAL.test(name) || ISSUED_CREDENTIAL.test(text)) + invalidRequest(); + } + return form; +} + +/** Header bearer authentication. The host retains resource routing and body handling. */ export function createProtectedResourceAuthenticator( options: ProtectedResourceAuthenticatorOptions, ): ProtectedResourceAuthenticator { const configuration = normalizeConfiguration(options.configuration); + const multipartBytes = multipartMaximum(options.multipart); return Object.freeze({ async authenticate( request: Request, requiredScopes: readonly string[] = [], - ): Promise { + ): Promise { let selected: readonly string[] = []; try { if ( @@ -679,14 +894,25 @@ export function createProtectedResourceAuthenticator( const url = new URL(request.url); assertByteBound(url.search, MAX_BODY_BYTES); if (url.searchParams.has("access_token")) invalidRequest(); - // Do not read/clone the host's body. Form transports must reject token fields themselves. + // Never read the host's body by default. Opted-in multipart reads only a clone. const contentType = request.headers.get("Content-Type") ?? ""; + const multipart = MULTIPART.test(contentType); if ( - /^(?:application\/x-www-form-urlencoded|multipart\/form-data)(?:\s*;|\s*$)/i.test( + /^application\/x-www-form-urlencoded(?:\s*;|\s*$)/i.test( contentType, - ) + ) || + (multipart && multipartBytes === undefined) ) invalidRequest(); + if (multipart && multipartBytes !== undefined) { + try { + assertMultipartHeaders(request, contentType, multipartBytes); + } catch (error) { + // A rejected upload never leaves its source stream open. + await cancelBody(request); + throw error; + } + } const authorization = request.headers.get("Authorization"); if (authorization === null) return resourceError( @@ -701,11 +927,29 @@ export function createProtectedResourceAuthenticator( ); const match = /^Bearer ([A-Za-z0-9\-._~+/]+=*)$/i.exec(authorization); if (match === null || match[1] === undefined) invalidRequest(); - return await options.service.authenticate({ + const input = { token: match[1], resource: configuration.resource, requiredScopes: selected, - }); + }; + const delegated = await options.service.authenticate(input); + // The body is inspected only after the bearer header is accepted. + if (!multipart || multipartBytes === undefined) return delegated; + try { + const form = await multipartForm( + request, + contentType, + multipartBytes, + ); + // An upload can take arbitrarily long; revocation, expiry, and + // authority changes during it must still fail closed. + const current = await options.service.authenticate(input); + return { ...current, form }; + } catch (error) { + // Cancel the unread original tee branch so the source closes too. + await cancelBody(request); + throw error; + } } catch (error) { return resourceError(error, configuration, selected); } diff --git a/packages/agent-access/src/records.ts b/packages/agent-access/src/records.ts index e82abba..192efee 100644 --- a/packages/agent-access/src/records.ts +++ b/packages/agent-access/src/records.ts @@ -188,3 +188,116 @@ export const agentAccessRecords = defineCollection({ key: (record) => ({ partition: record.partition, id: record.id }), codec: { encode, decode }, }); + +/** + * Owner index: one partition per (issuer, resource, owner) hash. Entries only + * locate grant heads; the grant head stays authoritative for ownership and + * status, so a stale or dangling entry can never reveal another owner's grant. + */ +export type OwnerIndexRecord = + | { + readonly partition: string; + readonly id: "head"; + readonly kind: "owner-head"; + readonly data: { readonly next: number }; + } + | { + readonly partition: string; + readonly id: string; + readonly kind: "member" | "entry"; + readonly data: { readonly locator: string; readonly sequence: number }; + }; + +/** Sequences fit twelve decimal digits so entry IDs sort and stay bounded. */ +export const MAX_OWNER_SEQUENCE = 999_999_999_999; + +export function ownerEntryId(sequence: number): string { + return `entry:${String(sequence).padStart(12, "0")}`; +} + +function validSequence(value: unknown): value is number { + return ( + typeof value === "number" && + Number.isSafeInteger(value) && + value >= 1 && + value <= MAX_OWNER_SEQUENCE + ); +} + +function validateOwner(record: OwnerIndexRecord): void { + if (!SEGMENT.test(record.partition)) throw new Error("Invalid owner index"); + if (record.kind === "owner-head") { + if (record.id !== "head" || !validSequence(record.data.next)) + throw new Error("Invalid owner index"); + return; + } + if ( + (record.kind !== "member" && record.kind !== "entry") || + !SEGMENT.test(record.data.locator) || + !validSequence(record.data.sequence) || + record.id !== + (record.kind === "member" + ? `grant:${record.data.locator}` + : ownerEntryId(record.data.sequence)) + ) + throw new Error("Invalid owner index"); +} + +function encodeOwner(record: OwnerIndexRecord): StoredRecord { + validateOwner(record); + return record.kind === "owner-head" + ? { + schemaVersion: 1, + recordPartition: record.partition, + recordId: record.id, + kind: record.kind, + next: record.data.next, + } + : { + schemaVersion: 1, + recordPartition: record.partition, + recordId: record.id, + kind: record.kind, + locator: record.data.locator, + sequence: record.data.sequence, + }; +} + +function decodeOwner(stored: StoredRecord): OwnerIndexRecord { + const base = ["schemaVersion", "recordPartition", "recordId", "kind"]; + const fields = + stored.kind === "owner-head" + ? [...base, "next"] + : [...base, "locator", "sequence"]; + if ( + stored.schemaVersion !== 1 || + typeof stored.recordPartition !== "string" || + typeof stored.recordId !== "string" || + Object.keys(stored).length !== fields.length || + Object.keys(stored).some((key) => !fields.includes(key)) + ) + throw new Error("Invalid owner index"); + const record = ( + stored.kind === "owner-head" + ? { + partition: stored.recordPartition, + id: stored.recordId, + kind: stored.kind, + data: { next: stored.next }, + } + : { + partition: stored.recordPartition, + id: stored.recordId, + kind: stored.kind, + data: { locator: stored.locator, sequence: stored.sequence }, + } + ) as OwnerIndexRecord; + validateOwner(record); + return record; +} + +export const ownerIndexRecords = defineCollection({ + name: "agent-access.owner-index.v1", + key: (record) => ({ partition: record.partition, id: record.id }), + codec: { encode: encodeOwner, decode: decodeOwner }, +}); diff --git a/packages/agent-access/src/service.ts b/packages/agent-access/src/service.ts index 8bfd3fa..65ab6e6 100644 --- a/packages/agent-access/src/service.ts +++ b/packages/agent-access/src/service.ts @@ -1,13 +1,19 @@ import { auditRecordId, defineAudit, type AuditActor } from "@pegma/audit"; import { hasPermission, type AccessContext } from "@pegma/authorization-core"; -import type { VersionedRecord } from "@pegma/storage-core"; +import { + MAX_SCAN_PAGE_SIZE, + type TransactionAction, + type VersionedRecord, +} from "@pegma/storage-core"; import { createCredential, deviceLocator, generateLocator, generateUserCode, + grantCursorCheck, hashCredential, normalizeUserCode, + ownerIndexPartition, parseCredential, scopeFingerprint, verifyPkce, @@ -15,20 +21,29 @@ import { import { OAuthError, type OAuthErrorCode } from "./errors.js"; import { agentAccessRecords, + MAX_OWNER_SEQUENCE, + ownerEntryId, + ownerIndexRecords, type AgentAccessRecord, type GrantHead, + type OwnerIndexRecord, } from "./records.js"; import type { AgentAccessOptions, AgentAccessServicePort, ApprovalView, ApprovalResult, + BackfillGrantIndexInput, + BackfillGrantIndexResult, BeginAuthorizationInput, BeginDeviceAuthorizationInput, BrowserApprovalContext, DeviceAuthorizationResult, ExchangeAuthorizationCodeInput, + GrantPage, + GrantStatus, GrantView, + ListGrantsInput, PollDeviceTokenInput, RefreshInput, TokenResult, @@ -64,6 +79,46 @@ interface Decision { readonly expiryError?: OAuthErrorCode; } +const DEFAULT_GRANT_PAGE_SIZE = 20; +const MAX_GRANT_PAGE_SIZE = 100; +const DEFAULT_BACKFILL_PAGE_SIZE = 100; +/** Statuses a listed (approved) grant can hold; denied requests are never listed. */ +const GRANT_STATUSES: readonly GrantStatus[] = [ + "pending", + "active", + "revoked", + "expired", +]; +const GRANT_CURSOR = + /^pgc1\.([A-Za-z0-9_-]{43})\.([1-9][0-9]{0,11})\.([A-Za-z0-9_-]{22})$/; +const PRINCIPAL_CONTROL = /[\u0000-\u001F\u007F-\u009F]/; + +function plainObject(value: unknown): Record { + if (value === null || typeof value !== "object" || Array.isArray(value)) + throw new OAuthError("invalid_request"); + return value as Record; +} + +function onlyKeys( + value: Record, + keys: readonly string[], +): void { + if (Object.keys(value).some((key) => !keys.includes(key))) + throw new OAuthError("invalid_request"); +} + +function pageSize(value: unknown, fallback: number, maximum: number): number { + if (value === undefined) return fallback; + if ( + typeof value !== "number" || + !Number.isSafeInteger(value) || + value < 1 || + value > maximum + ) + throw new OAuthError("invalid_request"); + return value; +} + function locator(value: string): string { if (typeof value !== "string" || !/^[A-Za-z0-9_-]{43}$/.test(value)) throw new OAuthError("invalid_grant"); @@ -89,12 +144,14 @@ function copyScopes( class AgentAccessService implements AgentAccessServicePort { private readonly configuration: NormalizedAgentAccessConfiguration; private readonly records; + private readonly owners; private readonly clock; private readonly resolvePrincipal; constructor(options: AgentAccessOptions) { this.configuration = normalizeConfiguration(options.configuration); this.records = options.store.collection(agentAccessRecords); + this.owners = options.store.collection(ownerIndexRecords); this.clock = options.clock; this.resolvePrincipal = options.resolvePrincipal; } @@ -227,8 +284,7 @@ class AgentAccessService implements AgentAccessServicePort { version: row.version, }, ]; - const extra: import("@pegma/storage-core").TransactionAction[] = - []; + const extra: TransactionAction[] = []; if (decision.consumed !== undefined) extra.push({ action: "insert", @@ -339,6 +395,130 @@ class AgentAccessService implements AgentAccessServicePort { throw new OAuthError("access_denied"); } + private ownerPartition(ownerId: string): Promise { + return ownerIndexPartition( + this.configuration.issuer, + this.configuration.resource, + ownerId, + ); + } + + /** + * Write-ahead owner index. It commits in the owner's partition before the + * grant approval commits in the grant's partition; the two are never claimed + * to be atomic. A dangling entry (approval later refused or lost) is harmless + * because listing re-reads the authoritative grant head and its owner. + * Returns true when this call added the entry. + */ + private async indexGrant(ownerId: string, grantId: string): Promise { + const partition = await this.ownerPartition(ownerId); + for ( + let attempt = 0; + attempt < this.configuration.limits.maxConflictAttempts; + attempt += 1 + ) { + const member = await this.owners.get({ + partition, + id: `grant:${grantId}`, + }); + if (member !== null) { + if (member.kind !== "member" || member.data.locator !== grantId) + throw new OAuthError("server_error"); + return false; + } + const head = await this.owners.getVersioned({ partition, id: "head" }); + if (head !== null && head.value.kind !== "owner-head") + throw new OAuthError("server_error"); + const previous = + head === null || head.value.kind !== "owner-head" + ? 0 + : head.value.data.next; + const sequence = previous + 1; + if (sequence > MAX_OWNER_SEQUENCE) throw new OAuthError("server_error"); + const ownerHead: OwnerIndexRecord = { + partition, + id: "head", + kind: "owner-head", + data: { next: sequence }, + }; + // One owner-partition transaction: the head, membership, and entry agree. + const outcome = await this.owners.transact(partition, [ + head === null + ? { action: "insert", value: ownerHead } + : { + action: "putIfUnchanged", + value: ownerHead, + version: head.version, + }, + { + action: "insert", + value: { + partition, + id: `grant:${grantId}`, + kind: "member", + data: { locator: grantId, sequence }, + }, + }, + { + action: "insert", + value: { + partition, + id: ownerEntryId(sequence), + kind: "entry", + data: { locator: grantId, sequence }, + }, + }, + ]); + if (outcome.committed) return true; + } + throw new OAuthError("server_error"); + } + + /** The single safe public projection of a grant head; never credential hashes. */ + private grantView(head: GrantHead, instant: Instant): GrantView { + const expired = instant.milliseconds >= Date.parse(head.expiresAt); + return { + grantId: head.locator, + clientId: head.clientId, + ownerId: head.ownerId as string, + resource: head.resource, + scopes: copyScopes( + head.requestedScopes.filter((scope) => + head.approvedScopes?.includes(scope.name), + ), + ), + status: + head.status === "revoked" || + head.status === "denied" || + head.status === "expired" + ? head.status + : expired + ? "expired" + : head.status === "active" + ? "active" + : "pending", + createdAt: head.createdAt, + expiresAt: head.expiresAt, + }; + } + + private async cursor(partition: string, position: number): Promise { + return `pgc1.${partition}.${position}.${await grantCursorCheck(partition, position)}`; + } + + private async position(partition: string, value: unknown): Promise { + if (typeof value !== "string" || value.length > 128) + throw new OAuthError("invalid_request"); + const match = GRANT_CURSOR.exec(value); + if ( + match === null || + match[1] !== partition || + match[3] !== (await grantCursorCheck(partition, Number(match[2]))) + ) + throw new OAuthError("invalid_request"); + return Number(match[2]); + } + private currentlyPermitted( scopes: readonly ScopeDefinition[], current: AccessContext, @@ -645,6 +825,8 @@ class AgentAccessService implements AgentAccessServicePort { approvedScopes: names(approved), consentFingerprint: await scopeFingerprint(approved), }; + // Index first: a committed approval always has its owner entry. + await this.indexGrant(access.principalId, id); if (head.flow === "device_code") return { head: next, @@ -1082,29 +1264,149 @@ class AgentAccessService implements AgentAccessServicePort { const access = await this.browser(browser); const head = (await this.read(id)).value.data; this.owner(head, access); - const expired = this.instant().milliseconds >= Date.parse(head.expiresAt); - return { - grantId: id, - clientId: head.clientId, - ownerId: head.ownerId as string, - resource: head.resource, - scopes: copyScopes( - head.requestedScopes.filter((scope) => - head.approvedScopes?.includes(scope.name), + return this.grantView(head, this.instant()); + }); + } + + listGrants( + context: BrowserApprovalContext, + input: ListGrantsInput, + ): Promise { + return this.guarded(async () => { + const browser = this.input(context); + const request = plainObject(this.input(input)); + onlyKeys(request, ["ownerPrincipal", "cursor", "limit", "statuses"]); + const ownerId = request.ownerPrincipal; + if ( + typeof ownerId !== "string" || + ownerId.length === 0 || + ownerId.length > 512 || + PRINCIPAL_CONTROL.test(ownerId) + ) + throw new OAuthError("invalid_request"); + const limit = pageSize( + request.limit, + DEFAULT_GRANT_PAGE_SIZE, + MAX_GRANT_PAGE_SIZE, + ); + let statuses: ReadonlySet | undefined; + if (request.statuses !== undefined) { + const selected: unknown = request.statuses; + if ( + !Array.isArray(selected) || + selected.length === 0 || + selected.length > GRANT_STATUSES.length || + new Set(selected).size !== selected.length || + selected.some((status) => !GRANT_STATUSES.includes(status)) + ) + throw new OAuthError("invalid_request"); + statuses = new Set(selected as GrantStatus[]); + } + const access = await this.browser(browser); + // Strictly owner-scoped: the trusted session must be the listed owner. + if (access.principalId !== ownerId) throw new OAuthError("access_denied"); + const partition = await this.ownerPartition(ownerId); + const requested = + request.cursor === undefined + ? undefined + : await this.position(partition, request.cursor); + const head = await this.owners.get({ partition, id: "head" }); + if (head === null) return { grants: [], nextCursor: null }; + if (head.kind !== "owner-head") throw new OAuthError("server_error"); + // Newest first; a cursor never reaches past the current owner head. + const upper = Math.min(requested ?? head.data.next, head.data.next); + const lowest = Math.max(1, upper - limit + 1); + const sequences: number[] = []; + for (let sequence = upper; sequence >= lowest; sequence -= 1) + sequences.push(sequence); + const entries = await Promise.all( + sequences.map((sequence) => + this.owners.get({ partition, id: ownerEntryId(sequence) }), + ), + ); + const located = [ + ...new Set( + entries.flatMap((entry) => + entry?.kind === "entry" ? [entry.data.locator] : [], ), ), - status: - head.status === "revoked" || - head.status === "denied" || - head.status === "expired" - ? head.status - : expired - ? "expired" - : head.status === "active" - ? "active" - : "pending", - createdAt: head.createdAt, - expiresAt: head.expiresAt, + ]; + const heads = await Promise.all( + located.map((grantId) => + this.records.get({ partition: grantId, id: "head" }), + ), + ); + const instant = this.instant(); + const grants: GrantView[] = []; + for (const [index, record] of heads.entries()) { + const grantId = located[index]; + // Missing (removed by retention) or foreign heads are skipped, never surfaced. + if ( + record === null || + record.kind !== "head" || + record.partition !== grantId || + record.data.locator !== grantId || + record.data.issuer !== this.configuration.issuer || + record.data.resource !== this.configuration.resource || + record.data.ownerId !== ownerId || + record.data.approvedScopes === undefined + ) + continue; + const view = this.grantView(record.data, instant); + if (statuses === undefined || statuses.has(view.status)) + grants.push(view); + } + return { + grants, + nextCursor: + lowest > 1 ? await this.cursor(partition, lowest - 1) : null, + }; + }); + } + + backfillGrantIndex( + input: BackfillGrantIndexInput = {}, + ): Promise { + return this.guarded(async () => { + const request = plainObject(this.input(input)); + onlyKeys(request, ["cursor", "limit"]); + const limit = pageSize( + request.limit, + DEFAULT_BACKFILL_PAGE_SIZE, + MAX_SCAN_PAGE_SIZE, + ); + const cursor = request.cursor; + // Adapter continuations are opaque; captureInput already bounds their size. + if ( + cursor !== undefined && + (typeof cursor !== "string" || cursor.length === 0) + ) + throw new OAuthError("invalid_request"); + const page = await this.records.scan({ + limit, + ...(cursor === undefined ? {} : { cursor }), + }); + let indexed = 0; + for (const { key, value } of page.records) { + if ( + value.kind !== "head" || + key.id !== "head" || + key.partition !== value.partition || + value.data.locator !== value.partition || + value.data.issuer !== this.configuration.issuer || + value.data.resource !== this.configuration.resource || + value.data.ownerId === undefined || + value.data.approvedScopes === undefined + ) + continue; + // Sequential and idempotent: reruns and concurrent approvals never duplicate. + if (await this.indexGrant(value.data.ownerId, value.partition)) + indexed += 1; + } + return { + scanned: page.records.length, + indexed, + nextCursor: page.nextCursor, }; }); } diff --git a/packages/agent-access/src/types.ts b/packages/agent-access/src/types.ts index 4748f38..4863db6 100644 --- a/packages/agent-access/src/types.ts +++ b/packages/agent-access/src/types.ts @@ -176,17 +176,51 @@ export interface RevokeTokenInput { readonly tokenTypeHint?: "access_token" | "refresh_token"; } +export type GrantStatus = + "pending" | "active" | "denied" | "revoked" | "expired"; + export interface GrantView { readonly grantId: string; readonly clientId: string; readonly ownerId: PrincipalId; readonly resource: string; readonly scopes: readonly ScopeDefinition[]; - readonly status: "pending" | "active" | "denied" | "revoked" | "expired"; + readonly status: GrantStatus; readonly createdAt: IsoTimestamp; readonly expiresAt: IsoTimestamp; } +export interface ListGrantsInput { + /** Must equal the trusted browser session's principal; listing is owner-only. */ + readonly ownerPrincipal: PrincipalId; + /** Opaque, owner-bound continuation returned as `nextCursor` by the previous page. */ + readonly cursor?: string; + /** Index entries examined for this page: default 20, maximum 100. */ + readonly limit?: number; + /** Optional status filter applied after reading; omitted returns every status. */ + readonly statuses?: readonly GrantStatus[]; +} + +export interface GrantPage { + /** Newest indexed first. A page may hold fewer than `limit` grants. */ + readonly grants: readonly GrantView[]; + /** Null when no older index entries remain. */ + readonly nextCursor: string | null; +} + +export interface BackfillGrantIndexInput { + /** Storage-adapter scan continuation from the previous call's `nextCursor`. */ + readonly cursor?: string; + /** Physical rows scanned this call: default 100, maximum 1000. */ + readonly limit?: number; +} + +export interface BackfillGrantIndexResult { + readonly scanned: number; + readonly indexed: number; + readonly nextCursor: string | null; +} + export interface AgentAccessServicePort { beginDeviceAuthorization( input: BeginDeviceAuthorizationInput, @@ -219,4 +253,12 @@ export interface AgentAccessServicePort { grantId: string, ): Promise; revokeGrant(context: BrowserApprovalContext, grantId: string): Promise; + listGrants( + context: BrowserApprovalContext, + input: ListGrantsInput, + ): Promise; + /** Host maintenance: indexes approved grants stored before owner listing existed. */ + backfillGrantIndex( + input?: BackfillGrantIndexInput, + ): Promise; } diff --git a/tests/listing.test.ts b/tests/listing.test.ts new file mode 100644 index 0000000..576a302 --- /dev/null +++ b/tests/listing.test.ts @@ -0,0 +1,625 @@ +import { + OAuthError, + type BrowserApprovalContext, + type GrantView, +} from "@pegma/agent-access"; +import type { AccessContext } from "@pegma/authorization-core"; +import { + createMemoryStore, + defineCollection, + type StoredRecord, +} from "@pegma/storage-core"; +import { describe, expect, it } from "vitest"; +import { + access, + admin, + browser, + CLIENT, + fixture, + OTHER_CLIENT, + pkce, + READ, + REDIRECT, + RESOURCE, + SCOPES, + WRITE, +} from "../test/fixtures.js"; +import { storeFactories } from "../test/stores.js"; +import { traceStore } from "../test/trace-store.js"; + +const OWNER_INDEX = "agent-access.owner-index.v1"; +/** Documented listing bounds. */ +const DEFAULT_GRANT_PAGE_SIZE = 20; +const MAX_GRANT_PAGE_SIZE = 100; +const VIEW_KEYS = [ + "clientId", + "createdAt", + "expiresAt", + "grantId", + "ownerId", + "resource", + "scopes", + "status", +].sort(); + +const other = access(undefined, "staff/second-admin"); +const otherBrowser: BrowserApprovalContext = { + authentication: "browser-session", + access: other, +}; + +async function rejected(work: Promise): Promise { + try { + await work; + } catch (error) { + if (error instanceof OAuthError) return error; + throw error; + } + throw new Error("Expected an OAuth error"); +} + +/** Approve one device grant as a specific administrator. */ +async function approveDeviceAs( + world: ReturnType, + context: BrowserApprovalContext, + current: AccessContext, + clientId = CLIENT, +) { + const previous = world.authority.current; + world.authority.current = current; + try { + const device = await world.service.beginDeviceAuthorization({ + clientId, + resource: RESOURCE, + scopes: [READ], + }); + const approval = await world.service.getDeviceApproval( + context, + device.user_code, + ); + await world.service.approve(context, { + requestId: approval.requestId, + decision: "approve", + userCode: device.user_code, + }); + return { device, grantId: approval.requestId }; + } finally { + world.authority.current = previous; + } +} + +async function everyPage( + world: ReturnType, + limit: number, + context = browser, + ownerPrincipal = admin.principalId, +) { + const pages: (readonly GrantView[])[] = []; + let cursor: string | undefined; + for (let index = 0; index < 50; index += 1) { + const page = await world.service.listGrants(context, { + ownerPrincipal, + limit, + ...(cursor === undefined ? {} : { cursor }), + }); + pages.push(page.grants); + if (page.nextCursor === null) return pages; + cursor = page.nextCursor; + } + throw new Error("Listing did not terminate"); +} + +for (const [backend, makeStore] of storeFactories) { + describe(`${backend}: owner-scoped grant listing`, () => { + it("pages approved grants newest first with bounded keyed reads", async () => { + const traced = traceStore(await makeStore()); + const world = fixture(traced.store); + const created: string[] = []; + for (let index = 0; index < 3; index += 1) + created.push((await world.completeDevice([READ])).approval.requestId); + for (let index = 0; index < 2; index += 1) + created.push( + (await world.completeAuthorization([READ, WRITE])).approval.requestId, + ); + traced.reads.length = 0; + traced.transactions.length = 0; + const pages = await everyPage(world, 2); + // Each page: one owner head plus at most two keyed reads per examined entry. + expect(traced.reads.length).toBeLessThanOrEqual(3 * (1 + 2 * 2)); + expect(traced.enumerations).toEqual([]); + expect(traced.transactions).toEqual([]); + expect(pages.map((page) => page.length)).toEqual([2, 2, 1]); + expect(pages.flat().map((grant) => grant.grantId)).toEqual( + [...created].reverse(), + ); + for (const grant of pages.flat()) { + expect(Object.keys(grant).sort()).toEqual(VIEW_KEYS); + expect(grant.ownerId).toBe(admin.principalId); + expect(grant.status).toBe("active"); + expect(grant).toEqual( + await world.service.getGrant(browser, grant.grantId), + ); + } + }); + + it("lists, revokes through the listed ID, and reflects the new status", async () => { + const world = fixture(await makeStore()); + const first = await world.completeDevice([READ]); + await world.completeAuthorization([READ]); + const listed = await world.service.listGrants(browser, { + ownerPrincipal: admin.principalId, + }); + expect(listed.grants).toHaveLength(2); + const target = listed.grants.find( + (grant) => grant.grantId === first.approval.requestId, + ); + if (target === undefined) throw new Error("Expected listed grant"); + await world.service.revokeGrant(browser, target.grantId); + const after = await world.service.listGrants(browser, { + ownerPrincipal: admin.principalId, + }); + expect( + after.grants.find((grant) => grant.grantId === target.grantId)?.status, + ).toBe("revoked"); + const active = await world.service.listGrants(browser, { + ownerPrincipal: admin.principalId, + statuses: ["active"], + }); + expect(active.grants.map((grant) => grant.grantId)).not.toContain( + target.grantId, + ); + expect(active.grants).toHaveLength(1); + expect( + ( + await rejected( + world.service.authenticate({ + token: first.tokens.access_token, + resource: RESOURCE, + }), + ) + ).code, + ).toBe("invalid_token"); + }); + + it("indexes grants stored before listing existed with a bounded idempotent backfill", async () => { + const store = await makeStore(); + const world = fixture(store); + const created: string[] = []; + for (let index = 0; index < 4; index += 1) + created.push((await world.completeDevice([READ])).approval.requestId); + await world.service.beginDeviceAuthorization({ + clientId: CLIENT, + resource: RESOURCE, + scopes: [READ], + }); + // Remove the owner index to reproduce records written by an earlier release. + const raw = store.collection( + defineCollection({ + name: OWNER_INDEX, + key: (record) => ({ + partition: String(record.recordPartition), + id: String(record.recordId), + }), + codec: { encode: (record) => record, decode: (record) => record }, + }), + ); + const indexRows = await raw.scan({ limit: 1_000 }); + expect(indexRows.records).toHaveLength(9); + for (const row of indexRows.records) await raw.delete(row.key); + + expect( + await world.service.listGrants(browser, { + ownerPrincipal: admin.principalId, + }), + ).toEqual({ grants: [], nextCursor: null }); + // Keyed inspection and revocation never depended on the index. + expect( + (await world.service.getGrant(browser, created[0] as string)).status, + ).toBe("active"); + + let indexed = 0; + let scanned = 0; + let cursor: string | undefined; + let terminated = false; + for (let index = 0; index < 100; index += 1) { + const result = await world.service.backfillGrantIndex({ + limit: 3, + ...(cursor === undefined ? {} : { cursor }), + }); + expect(result.scanned).toBeLessThanOrEqual(3); + indexed += result.indexed; + scanned += result.scanned; + if (result.nextCursor === null) { + terminated = true; + break; + } + cursor = result.nextCursor; + } + // The documented maintenance loop must reach a null continuation. + expect(terminated).toBe(true); + expect(indexed).toBe(4); + expect(scanned).toBeGreaterThan(4); + const rerun = await world.service.backfillGrantIndex({ limit: 1_000 }); + expect(rerun.indexed).toBe(0); + const listed = await world.service.listGrants(browser, { + ownerPrincipal: admin.principalId, + }); + expect(listed.grants.map((grant) => grant.grantId).sort()).toEqual( + [...created].sort(), + ); + await world.service.revokeGrant(browser, created[1] as string); + expect( + ( + await world.service.listGrants(browser, { + ownerPrincipal: admin.principalId, + statuses: ["revoked"], + }) + ).grants.map((grant) => grant.grantId), + ).toEqual([created[1]]); + for (const input of [ + { limit: 0 }, + { limit: 1_001 }, + { cursor: "" }, + { other: 1 }, + ]) + expect( + ( + await rejected( + world.service.backfillGrantIndex( + input as Parameters[0], + ), + ) + ).code, + ).toBe("invalid_request"); + }); + + it("tolerates index entries whose grant was removed by host retention", async () => { + const store = await makeStore(); + const world = fixture(store); + const kept = await world.completeDevice([READ]); + const removed = await world.completeDevice([READ]); + const raw = store.collection( + defineCollection({ + name: "agent-access.records.v1", + key: (record) => ({ + partition: String(record.recordPartition), + id: String(record.recordId), + }), + codec: { encode: (record) => record, decode: (record) => record }, + }), + ); + for (const row of await raw.list(removed.approval.requestId)) + await raw.delete({ + partition: removed.approval.requestId, + id: String(row.recordId), + }); + const listed = await world.service.listGrants(browser, { + ownerPrincipal: admin.principalId, + }); + expect(listed.grants.map((grant) => grant.grantId)).toEqual([ + kept.approval.requestId, + ]); + const serialized = JSON.stringify(listed); + for (const secret of [ + kept.tokens.access_token, + kept.tokens.refresh_token, + kept.device.device_code, + ]) + expect(serialized).not.toContain(secret); + expect(serialized).not.toMatch(/Hash|consentFingerprint|codeChallenge/); + }); + }); +} + +describe("grant listing bounds and isolation", () => { + it("applies a conservative default and a hard maximum page size", async () => { + const world = fixture(createMemoryStore()); + for (let index = 0; index < DEFAULT_GRANT_PAGE_SIZE + 1; index += 1) + await world.completeDevice([READ]); + const first = await world.service.listGrants(browser, { + ownerPrincipal: admin.principalId, + }); + expect(first.grants).toHaveLength(DEFAULT_GRANT_PAGE_SIZE); + expect(first.nextCursor).not.toBeNull(); + const all = await world.service.listGrants(browser, { + ownerPrincipal: admin.principalId, + limit: MAX_GRANT_PAGE_SIZE, + }); + expect(all.grants).toHaveLength(DEFAULT_GRANT_PAGE_SIZE + 1); + expect(all.nextCursor).toBeNull(); + for (const limit of [0, -1, 1.5, MAX_GRANT_PAGE_SIZE + 1, Number.NaN, "2"]) + expect( + ( + await rejected( + world.service.listGrants(browser, { + ownerPrincipal: admin.principalId, + limit: limit as number, + }), + ) + ).code, + ).toBe("invalid_request"); + }); + + it("never returns another owner's grants or accepts another owner's cursor", async () => { + const traced = traceStore(createMemoryStore()); + const world = fixture(traced.store); + const mine: string[] = []; + for (let index = 0; index < 3; index += 1) + mine.push((await world.completeDevice([READ])).approval.requestId); + const theirs: string[] = []; + for (let index = 0; index < 2; index += 1) + theirs.push( + (await approveDeviceAs(world, otherBrowser, other, OTHER_CLIENT)) + .grantId, + ); + + // An approval that fails after its write-ahead index entry leaves a dangling entry. + const contested = await world.service.beginDeviceAuthorization({ + clientId: CLIENT, + resource: RESOURCE, + scopes: [READ], + }); + const approval = await world.service.getDeviceApproval( + browser, + contested.user_code, + ); + traced.intercept(async (trace, commit) => + trace.collection === "agent-access.records.v1" && + trace.partition === approval.requestId + ? { committed: false, reason: "changed" } + : commit(), + ); + expect( + ( + await rejected( + world.service.approve(browser, { + requestId: approval.requestId, + decision: "approve", + userCode: contested.user_code, + }), + ) + ).code, + ).toBe("server_error"); + traced.intercept(undefined); + world.authority.current = other; + await world.service.approve(otherBrowser, { + requestId: approval.requestId, + decision: "approve", + userCode: contested.user_code, + }); + theirs.push(approval.requestId); + world.authority.current = admin; + + const minePages = (await everyPage(world, 2, browser)).flat(); + world.authority.current = other; + const theirPages = ( + await everyPage(world, 2, otherBrowser, other.principalId) + ).flat(); + world.authority.current = admin; + // The dangling first-owner entry is filtered by the authoritative head owner. + expect(minePages.map((grant) => grant.grantId).sort()).toEqual( + [...mine].sort(), + ); + expect(theirPages.map((grant) => grant.grantId).sort()).toEqual( + [...theirs].sort(), + ); + expect( + minePages.every((grant) => grant.ownerId === admin.principalId), + ).toBe(true); + + // A trusted session cannot list a different owner. + expect( + ( + await rejected( + world.service.listGrants(browser, { + ownerPrincipal: other.principalId, + }), + ) + ).code, + ).toBe("access_denied"); + + const myCursor = ( + await world.service.listGrants(browser, { + ownerPrincipal: admin.principalId, + limit: 1, + }) + ).nextCursor; + if (myCursor === null) throw new Error("Expected a continuation"); + world.authority.current = other; + expect( + ( + await rejected( + world.service.listGrants(otherBrowser, { + ownerPrincipal: other.principalId, + cursor: myCursor, + }), + ) + ).code, + ).toBe("invalid_request"); + }); + + it("rejects malformed and tampered cursors cleanly", async () => { + const world = fixture(createMemoryStore()); + for (let index = 0; index < 3; index += 1) + await world.completeDevice([READ]); + const page = await world.service.listGrants(browser, { + ownerPrincipal: admin.principalId, + limit: 1, + }); + const cursor = page.nextCursor; + if (cursor === null) throw new Error("Expected a continuation"); + const [prefix, partition, position, check] = cursor.split("."); + const tampered = [ + "", + "garbage", + `${prefix}.${partition}.${Number(position) + 1}.${check}`, + `${prefix}.${partition}.${position}.${"A".repeat(22)}`, + `${prefix}.${"A".repeat(43)}.${position}.${check}`, + `pgc2.${partition}.${position}.${check}`, + `${prefix}.${partition}.0${position}.${check}`, + `${cursor} `, + cursor + "x".repeat(200), + 42, + null, + ]; + for (const value of tampered) { + const error = await rejected( + world.service.listGrants(browser, { + ownerPrincipal: admin.principalId, + cursor: value as string, + }), + ); + expect(error.code).toBe("invalid_request"); + expect(JSON.stringify(error.toJSON())).not.toContain(partition); + } + const next = await world.service.listGrants(browser, { + ownerPrincipal: admin.principalId, + cursor, + }); + expect(next.grants).toHaveLength(2); + expect(next.nextCursor).toBeNull(); + }); + + it("validates the owner principal, input shape, filter, and browser authority", async () => { + const world = fixture(createMemoryStore()); + await world.completeDevice([READ]); + for (const input of [ + { ownerPrincipal: "" }, + { ownerPrincipal: "staff/\u0000admin" }, + { ownerPrincipal: "x".repeat(513) }, + { ownerPrincipal: 7 }, + { ownerPrincipal: admin.principalId, unknown: true }, + { ownerPrincipal: admin.principalId, statuses: [] }, + { ownerPrincipal: admin.principalId, statuses: ["active", "active"] }, + { ownerPrincipal: admin.principalId, statuses: ["approved"] }, + // Denied requests are never listed, so filtering for them is rejected. + { ownerPrincipal: admin.principalId, statuses: ["denied"] }, + { ownerPrincipal: admin.principalId, statuses: "active" }, + null, + [], + ]) + expect( + ( + await rejected( + world.service.listGrants( + browser, + input as Parameters[1], + ), + ) + ).code, + ).toBe("invalid_request"); + const unprivileged = access([...SCOPES]); + expect( + ( + await rejected( + world.service.listGrants( + { authentication: "browser-session", access: unprivileged }, + { ownerPrincipal: admin.principalId }, + ), + ) + ).code, + ).toBe("access_denied"); + world.authority.unavailable = true; + expect( + ( + await rejected( + world.service.listGrants(browser, { + ownerPrincipal: admin.principalId, + }), + ) + ).code, + ).toBe("server_error"); + }); + + it("lists an approved but unredeemed grant as pending, then active once redeemed", async () => { + const world = fixture(createMemoryStore()); + const device = await world.service.beginDeviceAuthorization({ + clientId: CLIENT, + resource: RESOURCE, + scopes: [READ], + }); + const approval = await world.service.getDeviceApproval( + browser, + device.user_code, + ); + await world.service.approve(browser, { + requestId: approval.requestId, + decision: "approve", + userCode: device.user_code, + }); + const before = await world.service.listGrants(browser, { + ownerPrincipal: admin.principalId, + statuses: ["pending"], + }); + expect(before.grants.map((grant) => [grant.grantId, grant.status])).toEqual( + [[approval.requestId, "pending"]], + ); + expect(before.grants[0]?.scopes.map((scope) => scope.name)).toEqual([READ]); + world.advance(device.interval); + await world.service.pollDeviceToken({ + clientId: CLIENT, + resource: RESOURCE, + deviceCode: device.device_code, + }); + const after = await world.service.listGrants(browser, { + ownerPrincipal: admin.principalId, + }); + expect(after.grants.map((grant) => grant.status)).toEqual(["active"]); + }); + + it("reports revoked and expired grants with status and omits unapproved or denied requests", async () => { + const world = fixture(createMemoryStore()); + const revoked = await world.completeDevice([READ]); + await world.service.revokeGrant(browser, revoked.approval.requestId); + const active = await world.completeDevice([READ]); + // An authorization request that was never approved is owned but not linked. + const proof = await pkce(); + await world.service.beginAuthorization(browser, { + clientId: CLIENT, + resource: RESOURCE, + scopes: [READ], + redirectUri: REDIRECT, + codeChallenge: proof.challenge, + codeChallengeMethod: "S256", + }); + const denied = await world.service.beginDeviceAuthorization({ + clientId: CLIENT, + resource: RESOURCE, + scopes: [READ], + }); + const deniedView = await world.service.getDeviceApproval( + browser, + denied.user_code, + ); + await world.service.approve(browser, { + requestId: deniedView.requestId, + decision: "deny", + userCode: denied.user_code, + }); + const listed = await world.service.listGrants(browser, { + ownerPrincipal: admin.principalId, + }); + expect(listed.grants.map((grant) => [grant.grantId, grant.status])).toEqual( + [ + [active.approval.requestId, "active"], + [revoked.approval.requestId, "revoked"], + ], + ); + world.advance(604_800); + const later = await world.service.listGrants(browser, { + ownerPrincipal: admin.principalId, + }); + expect(later.grants.map((grant) => grant.status)).toEqual([ + "expired", + "revoked", + ]); + expect( + ( + await world.service.listGrants(browser, { + ownerPrincipal: admin.principalId, + statuses: ["active"], + }) + ).grants, + ).toEqual([]); + }); +}); diff --git a/tests/multipart.test.ts b/tests/multipart.test.ts new file mode 100644 index 0000000..5e40b76 --- /dev/null +++ b/tests/multipart.test.ts @@ -0,0 +1,453 @@ +import { + createProtectedResourceAuthenticator, + OAuthError, +} from "@pegma/agent-access"; +import { createMemoryStore } from "@pegma/storage-core"; +import { describe, expect, it } from "vitest"; +import { READ, RESOURCE, WRITE, fixture } from "../test/fixtures.js"; + +const BOUNDARY = "synthetic-upload-boundary"; +/** Documented multipart bounds: 1 MiB default, 16 MiB ceiling. */ +const DEFAULT_MULTIPART_MAX_BYTES = 1_048_576; +const MAX_MULTIPART_BYTES = 16_777_216; +const UPLOAD = `${RESOURCE}/uploads`; + +function multipartBody( + parts: readonly { name: string; value: string; filename?: string }[], +): string { + return ( + parts + .map( + (part) => + `--${BOUNDARY}\r\nContent-Disposition: form-data; name="${part.name}"` + + (part.filename === undefined + ? "" + : `; filename="${part.filename}"\r\nContent-Type: text/plain`) + + `\r\n\r\n${part.value}\r\n`, + ) + .join("") + `--${BOUNDARY}--\r\n` + ); +} + +function upload( + token: string | undefined, + body: BodyInit | null, + headers: Record = {}, +): Request { + return new Request(UPLOAD, { + method: "POST", + headers: { + "content-type": `multipart/form-data; boundary=${BOUNDARY}`, + ...(token === undefined ? {} : { authorization: `Bearer ${token}` }), + ...headers, + }, + body, + ...(body instanceof ReadableStream ? { duplex: "half" } : {}), + } as RequestInit); +} + +/** A body that records how many chunks the authenticator actually pulled. */ +function countingStream(chunks: number, chunkBytes: number) { + const state = { pulled: 0, cancelled: false }; + const prefix = new TextEncoder().encode( + `--${BOUNDARY}\r\nContent-Disposition: form-data; name="file"; filename="a.txt"\r\n\r\n`, + ); + const stream = new ReadableStream({ + pull(controller) { + state.pulled += 1; + if (state.pulled === 1) controller.enqueue(prefix); + else if (state.pulled <= chunks) + controller.enqueue(new Uint8Array(chunkBytes).fill(0x61)); + else controller.close(); + }, + cancel() { + state.cancelled = true; + }, + }); + return { stream, state }; +} + +async function setup(maxBytes?: number) { + const world = fixture(createMemoryStore()); + const { tokens, approval } = await world.completeDevice([READ]); + const optedIn = createProtectedResourceAuthenticator({ + service: world.service, + configuration: world.options.configuration, + multipart: maxBytes === undefined ? {} : { maxBytes }, + }); + const standard = createProtectedResourceAuthenticator({ + service: world.service, + configuration: world.options.configuration, + }); + return { world, tokens, grantId: approval.requestId, optedIn, standard }; +} + +async function errorOf(result: unknown) { + if (!(result instanceof Response)) throw new Error("Expected a rejection"); + expect(result.headers.get("cache-control")).toContain("no-store"); + return { + status: result.status, + body: (await result.json()) as { error: string }, + challenge: result.headers.get("www-authenticate"), + }; +} + +describe("opt-in bounded multipart bearer transport", () => { + it("keeps rejecting multipart bodies when the host has not opted in", async () => { + const { tokens, standard } = await setup(); + const request = upload( + tokens.access_token, + multipartBody([{ name: "file", value: "hello", filename: "a.txt" }]), + ); + const rejected = await errorOf( + await standard.authenticate(request, [READ]), + ); + expect(rejected.status).toBe(400); + expect(rejected.body.error).toBe("invalid_request"); + expect(request.bodyUsed).toBe(false); + }); + + it("accepts a header-bearer upload, returns its parsed form, and leaves the request readable", async () => { + const { tokens, optedIn } = await setup(); + const form = new FormData(); + form.set("title", "Synthetic notes"); + form.set( + "file", + new Blob(["synthetic file body"], { type: "text/plain" }), + "notes.txt", + ); + const request = new Request(UPLOAD, { + method: "POST", + headers: { authorization: `Bearer ${tokens.access_token}` }, + body: form, + }); + expect(request.headers.get("content-type")).toMatch( + /^multipart\/form-data; boundary=/, + ); + const result = await optedIn.authenticate(request, [READ]); + if (result instanceof Response) throw new Error("Expected access"); + expect(result.scopes).toEqual([READ]); + expect(result.access.roles).toEqual([]); + expect(result.form?.get("title")).toBe("Synthetic notes"); + const file = result.form?.get("file"); + if (!(file instanceof Blob)) throw new Error("Expected parsed file"); + expect(await file.text()).toBe("synthetic file body"); + // The host may still read its own request instead of the handed-back form. + expect(request.bodyUsed).toBe(false); + const again = await request.formData(); + expect(again.get("title")).toBe("Synthetic notes"); + }); + + it("does not attach a form to non-multipart requests and still enforces scope", async () => { + const { tokens, optedIn } = await setup(); + const json = await optedIn.authenticate( + new Request(UPLOAD, { + method: "POST", + headers: { + authorization: `Bearer ${tokens.access_token}`, + "content-type": "application/json", + }, + body: "{}", + }), + [READ], + ); + if (json instanceof Response) throw new Error("Expected access"); + expect(json.form).toBeUndefined(); + const insufficient = await errorOf( + await optedIn.authenticate( + upload( + tokens.access_token, + multipartBody([{ name: "title", value: "x" }]), + ), + [WRITE], + ), + ); + expect(insufficient.status).toBe(403); + expect(insufficient.body.error).toBe("insufficient_scope"); + }); + + it("rejects a declared oversized body before reading it", async () => { + const { tokens, optedIn } = await setup(1_024); + const { stream, state } = countingStream(4, 512); + const request = upload(tokens.access_token, stream, { + "content-length": "4096", + }); + const rejected = await errorOf(await optedIn.authenticate(request, [READ])); + expect(rejected.status).toBe(413); + expect(rejected.body.error).toBe("invalid_request"); + expect(state.pulled).toBeLessThanOrEqual(1); + // The rejected upload source is cancelled rather than left open. + expect(state.cancelled).toBe(true); + for (const declared of ["-1", "1e3", "01", "abc"]) { + // A never-pulled stream proves the header itself was rejected. + const pending = countingStream(2, 16); + const malformed = await errorOf( + await optedIn.authenticate( + upload(tokens.access_token, pending.stream, { + "content-length": declared, + }), + [READ], + ), + ); + expect(malformed.status).toBe(400); + expect(pending.state.pulled).toBeLessThanOrEqual(1); + expect(pending.state.cancelled).toBe(true); + } + }); + + it("cancels a streamed body once it exceeds the bound", async () => { + const { tokens, optedIn } = await setup(2_048); + const { stream, state } = countingStream(1_000, 512); + const request = upload(tokens.access_token, stream); + const rejected = await errorOf(await optedIn.authenticate(request, [READ])); + expect(rejected.status).toBe(413); + expect(rejected.body.error).toBe("invalid_request"); + // Only a few chunks past the bound are ever pulled, never the whole stream, + // and both tee branches are cancelled so the source itself closes. + expect(state.pulled).toBeLessThan(20); + expect(state.cancelled).toBe(true); + }); + + it("enforces the 1 MiB default bound exactly", async () => { + const { tokens, optedIn } = await setup(); + const head = `--${BOUNDARY}\r\nContent-Disposition: form-data; name="file"; filename="a.bin"\r\n\r\n`; + const tail = `\r\n--${BOUNDARY}--\r\n`; + const sized = (total: number) => + head + "a".repeat(total - head.length - tail.length) + tail; + const exact = await optedIn.authenticate( + upload(tokens.access_token, sized(DEFAULT_MULTIPART_MAX_BYTES)), + [READ], + ); + if (exact instanceof Response) + throw new Error(`Expected access at the bound: ${exact.status}`); + const file = exact.form?.get("file"); + if (!(file instanceof Blob)) throw new Error("Expected parsed file"); + expect(file.size).toBe( + DEFAULT_MULTIPART_MAX_BYTES - head.length - tail.length, + ); + const over = await errorOf( + await optedIn.authenticate( + upload(tokens.access_token, sized(DEFAULT_MULTIPART_MAX_BYTES + 1)), + [READ], + ), + ); + expect(over.status).toBe(413); + }); + + it("authenticates again after a slow upload so revocation during it fails closed", async () => { + const { world, tokens, grantId, optedIn } = await setup(); + const body = new TextEncoder().encode( + multipartBody([{ name: "title", value: "slow" }]), + ); + let release = () => {}; + const gate = new Promise((resolve) => { + release = resolve; + }); + let reached = () => {}; + const midway = new Promise((resolve) => { + reached = resolve; + }); + let pulls = 0; + const stream = new ReadableStream({ + async pull(controller) { + pulls += 1; + if (pulls === 1) controller.enqueue(body.slice(0, 10)); + else if (pulls === 2) { + reached(); + await gate; + controller.enqueue(body.slice(10)); + } else controller.close(); + }, + }); + const pending = optedIn.authenticate(upload(tokens.access_token, stream), [ + READ, + ]); + await midway; + await world.service.revokeGrant(world.browser, grantId); + release(); + const rejected = await errorOf(await pending); + expect(rejected.status).toBe(401); + expect(rejected.challenge).toContain('error="invalid_token"'); + }); + + it("rejects credential-bearing form parts and query credentials", async () => { + const { tokens, optedIn } = await setup(); + const forbidden = [ + [{ name: "access_token", value: "sentinel-secret" }], + [{ name: "Refresh_Token", value: "sentinel-secret" }], + [{ name: "client_secret", value: "sentinel-secret" }], + [{ name: "code_verifier", value: "sentinel-secret" }], + [ + { name: "title", value: "ok" }, + { name: "notes", value: `prefix ${tokens.refresh_token} suffix` }, + ], + [ + { + name: "file", + value: "content", + filename: `${tokens.access_token}.txt`, + }, + ], + [{ name: tokens.access_token, value: "content" }], + ]; + for (const parts of forbidden) { + const request = upload(tokens.access_token, multipartBody(parts)); + const result = await optedIn.authenticate(request, [READ]); + if (!(result instanceof Response)) + throw new Error("Expected credential rejection"); + const text = await result.clone().text(); + expect(text).not.toContain("sentinel-secret"); + expect(text).not.toContain(tokens.refresh_token); + const rejected = await errorOf(result); + expect(rejected.status).toBe(400); + expect(rejected.body.error).toBe("invalid_request"); + } + const query = await errorOf( + await optedIn.authenticate( + new Request(`${UPLOAD}?access_token=sentinel-secret`, { + method: "POST", + headers: { + authorization: `Bearer ${tokens.access_token}`, + "content-type": `multipart/form-data; boundary=${BOUNDARY}`, + }, + body: multipartBody([{ name: "title", value: "x" }]), + }), + [READ], + ), + ); + expect(query.status).toBe(400); + const form = await errorOf( + await optedIn.authenticate( + new Request(UPLOAD, { + method: "POST", + headers: { + authorization: `Bearer ${tokens.access_token}`, + "content-type": "application/x-www-form-urlencoded", + }, + body: "title=x", + }), + [READ], + ), + ); + expect(form.status).toBe(400); + }); + + it("rejects malformed multipart and missing or ambiguous boundaries predictably", async () => { + const { tokens, optedIn } = await setup(); + for (const contentType of [ + "multipart/form-data", + "multipart/form-data;", + "multipart/form-data; charset=utf-8", + `multipart/form-data; boundary=${BOUNDARY}; boundary=other`, + 'multipart/form-data; boundary=""', + `multipart/form-data; boundary=${"b".repeat(71)}`, + "multipart/form-data; boundary=bad\\boundary", + `multipart/form-data; boundary=${BOUNDARY}; note="unterminated`, + `multipart/form-data; boundary=${BOUNDARY}; =value`, + `multipart/form-data; boundary=${BOUNDARY} trailing`, + ]) { + const request = upload( + tokens.access_token, + multipartBody([{ name: "title", value: "x" }]), + { "content-type": contentType }, + ); + const rejected = await errorOf( + await optedIn.authenticate(request, [READ]), + ); + expect(rejected.status).toBe(400); + expect(rejected.body.error).toBe("invalid_request"); + expect(rejected.challenge).toContain('error="invalid_request"'); + } + for (const body of [ + "not a multipart body", + `--${BOUNDARY}\r\nContent-Disposition: form-data\r\n\r\nx\r\n`, + ]) { + const rejected = await errorOf( + await optedIn.authenticate(upload(tokens.access_token, body), [READ]), + ); + expect(rejected.status).toBe(400); + expect(rejected.body.error).toBe("invalid_request"); + } + const empty = await errorOf( + await optedIn.authenticate(upload(tokens.access_token, null), [READ]), + ); + expect(empty.status).toBe(400); + }); + + it("checks the bearer header before reading any multipart bytes", async () => { + const { optedIn } = await setup(); + for (const token of [undefined, "sentinel-secret"]) { + const { stream, state } = countingStream(4, 16); + const request = upload(token, stream); + const rejected = await errorOf( + await optedIn.authenticate(request, [READ]), + ); + expect(rejected.status).toBe(401); + expect(rejected.challenge).toContain("resource_metadata="); + expect(state.pulled).toBeLessThanOrEqual(1); + expect(request.bodyUsed).toBe(false); + } + }); + + it("accepts quoted boundaries and quoted extension parameters containing separators", async () => { + const { tokens, optedIn } = await setup(); + for (const contentType of [ + `multipart/form-data; boundary="${BOUNDARY}"`, + `multipart/form-data; boundary=${BOUNDARY}; note="a;b"`, + String.raw`multipart/form-data; note="x\"; boundary=y"; boundary=` + + BOUNDARY, + `Multipart/Form-Data ; charset=utf-8;; Boundary=${BOUNDARY}`, + ]) { + const result = await optedIn.authenticate( + upload( + tokens.access_token, + multipartBody([{ name: "title", value: "quoted" }]), + { "content-type": contentType }, + ), + [READ], + ); + if (result instanceof Response) + throw new Error(`Expected access for ${contentType}`); + expect(result.form?.get("title")).toBe("quoted"); + } + }); + + it("validates the opt-in bound at construction", async () => { + const world = fixture(createMemoryStore()); + for (const maxBytes of [0, -1, 1.5, MAX_MULTIPART_BYTES + 1, Number.NaN]) + expect(() => + createProtectedResourceAuthenticator({ + service: world.service, + configuration: world.options.configuration, + multipart: { maxBytes }, + }), + ).toThrow(OAuthError); + // Null never silently selects the default; unknown keys and exotic objects fail. + for (const multipart of [ + { maxBytes: null }, + { maxBytes: "1024" }, + { maxsize: 1_024 }, + [], + new Date(), + null, + 1_024, + ]) + expect(() => + createProtectedResourceAuthenticator({ + service: world.service, + configuration: world.options.configuration, + multipart: multipart as { maxBytes?: number }, + }), + ).toThrow(OAuthError); + expect(DEFAULT_MULTIPART_MAX_BYTES).toBeLessThanOrEqual( + MAX_MULTIPART_BYTES, + ); + expect(() => + createProtectedResourceAuthenticator({ + service: world.service, + configuration: world.options.configuration, + multipart: { maxBytes: MAX_MULTIPART_BYTES }, + }), + ).not.toThrow(); + }); +}); diff --git a/tests/storage.test.ts b/tests/storage.test.ts index 626593b..ab89875 100644 --- a/tests/storage.test.ts +++ b/tests/storage.test.ts @@ -60,16 +60,50 @@ for (const [backend, makeStore] of storeFactories) { expect(serialized).not.toContain(secret); expect(JSON.stringify(traced.transactions)).not.toContain(secret); } - expect(snapshot).toHaveLength(1); + expect(snapshot.map(({ collection }) => collection).sort()).toEqual([ + "agent-access.owner-index.v1", + "agent-access.records.v1", + ]); + const grants = snapshot.find( + ({ collection }) => collection === "agent-access.records.v1", + ); + const owners = snapshot.find( + ({ collection }) => collection === "agent-access.owner-index.v1", + ); expect( - snapshot[0]?.rows.some(({ record }) => record.kind === "consumed"), + grants?.rows.some(({ record }) => record.kind === "consumed"), ).toBe(true); expect( - snapshot[0]?.rows.filter(({ record }) => record.kind === "audit") - .length, + grants?.rows.filter(({ record }) => record.kind === "audit").length, ).toBeGreaterThanOrEqual(8); - expect(traced.transactions.length).toBeGreaterThanOrEqual(8); - for (const transaction of traced.transactions) { + // One owner partition: its head plus a membership and an entry per approved grant. + expect(new Set(owners?.rows.map(({ key }) => key.partition)).size).toBe( + 1, + ); + expect(owners?.rows.map(({ record }) => record.kind).sort()).toEqual([ + "entry", + "entry", + "member", + "member", + "owner-head", + ]); + const indexTransactions = traced.transactions.filter( + ({ collection }) => collection === "agent-access.owner-index.v1", + ); + expect(indexTransactions).toHaveLength(2); + for (const transaction of indexTransactions) { + expect( + new Set(transaction.actions.map(({ key }) => key.partition)), + ).toEqual(new Set([transaction.partition])); + expect( + transaction.actions.map(({ record }) => record?.kind).sort(), + ).toEqual(["entry", "member", "owner-head"]); + } + const grantTransactions = traced.transactions.filter( + ({ collection }) => collection === "agent-access.records.v1", + ); + expect(grantTransactions.length).toBeGreaterThanOrEqual(8); + for (const transaction of grantTransactions) { expect( new Set(transaction.actions.map(({ key }) => key.partition)), ).toEqual(new Set([transaction.partition]));