diff --git a/clients/typescript/tests/breg-access-reason.test.ts b/clients/typescript/tests/breg-access-reason.test.ts new file mode 100644 index 0000000000..a9b2f5b989 --- /dev/null +++ b/clients/typescript/tests/breg-access-reason.test.ts @@ -0,0 +1,128 @@ +import test from 'node:test' +import assert from 'node:assert/strict' +import { mkdtempSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { fileURLToPath } from 'node:url' +import { generate } from '../generate.ts' +import { Transport } from '../core.ts' + +test('BReg generated inputs carry the Batch and ingestion reason in the request header', async t => { + const batchPath = '/v1/records/entries:batch' + const listPath = '/v1/records/entries/ingestion-runs' + const run = '00000000-0000-4000-8000-000000000001' + const runPath = listPath + '/{run_id}' + const chunkPath = runPath + '/chunks' + const receiptPath = chunkPath + '/{chunk_index}/receipt' + const cancelPath = runPath + '/cancel' + const reason = { + in: 'header', name: 'Registry-Access-Reason', required: false, + schema: { type: 'string', minLength: 1, maxLength: 684, pattern: '^[A-Za-z0-9_-]+$' }, + } + const responses = { + 200: { description: 'Accepted', content: { 'application/json': { schema: { type: 'string' } } } }, + } + const bodySchema = { required: true, content: { + 'application/json': { schema: { type: 'object', properties: { + items: { type: 'array', items: { type: 'string' } }, + }, required: ['items'] } }, + } } + const requiredReason = { ...reason, required: true } + const runParameter = { in: 'path', name: 'run_id', required: true, schema: { type: 'string', format: 'uuid' } } + const chunkParameter = { in: 'path', name: 'chunk_index', required: true, schema: { type: 'integer', minimum: 0 } } + const document = { + openapi: '3.1.0', + info: { title: 'Reason fixture' }, + paths: { + [batchPath]: { post: { + operationId: 'batchEntries', + 'x-registry-operation': 'batch', + parameters: [reason, { + in: 'header', name: 'Idempotency-Key', required: true, + schema: { type: 'string', minLength: 1, maxLength: 256 }, + }], + requestBody: { + required: true, + content: { 'application/json': { schema: { + type: 'object', required: ['items'], + properties: { items: { type: 'array', items: { type: 'string' } } }, + } } }, + }, + responses, + } }, + [listPath]: { + get: { operationId: 'listEntryRuns', parameters: [requiredReason], responses }, + post: { operationId: 'createEntryRun', parameters: [requiredReason], requestBody: bodySchema, responses }, + }, + [runPath]: { get: { + operationId: 'readEntryRun', parameters: [runParameter, requiredReason], responses, + } }, + [chunkPath]: { post: { + operationId: 'submitEntryChunk', parameters: [runParameter, requiredReason], requestBody: bodySchema, responses, + } }, + [receiptPath]: { get: { + operationId: 'readEntryReceipt', parameters: [runParameter, chunkParameter, requiredReason], responses, + } }, + [cancelPath]: { post: { + operationId: 'cancelEntryRun', parameters: [runParameter, requiredReason], responses, + } }, + }, + } + const output = generate(JSON.stringify(document), { + breg: true, + coreImport: fileURLToPath(new URL('../core.ts', import.meta.url)), + schemaImport: fileURLToPath(new URL('../schema.ts', import.meta.url)), + }) + assert.match(output, /"batchEntries": \{ input:.*headers\?: \{ "Registry-Access-Reason"\?: \(string\)/u) + const ingestion = [ + 'listEntryRuns', 'createEntryRun', 'readEntryRun', + 'submitEntryChunk', 'readEntryReceipt', 'cancelEntryRun', + ] as const + for (const operation of ingestion) { + const declaration = output.split('\n').find(line => line.includes(`"${operation}": { input:`)) + assert.match(declaration ?? '', /headers: \{ "Registry-Access-Reason": \(string\)/u) + } + + const dir = mkdtempSync(join(tmpdir(), 'breg-access-reason-')) + t.after(() => rmSync(dir, { recursive: true, force: true })) + const file = join(dir, 'client.ts') + writeFileSync(file, output) + const { Client } = await import(file) + const seen: Array<{ url: string; headers: Headers; body: BodyInit | null | undefined }> = [] + const client = new Client(new Transport({ + baseUrl: 'https://registry.example/tenant', + token: () => 'fixture', + fetch: async (url, init) => { + seen.push({ url: String(url), headers: new Headers(init?.headers), body: init?.body }) + return Response.json('accepted') + }, + })) + const header = 'Registry-Access-Reason' + const encoded = Buffer.from('Review 🧭', 'utf8').toString('base64url') + const body = { items: ['entry'] } + await client.call('batchEntries', { body, idempotencyKey: 'fixture-first', headers: { [header]: encoded } }) + await client.call('batchEntries', { body, idempotencyKey: 'fixture-second' }) + const headers = { [header]: encoded } + const path = { run_id: run } + await client.call('listEntryRuns', { headers }) + await client.call('createEntryRun', { headers, body }) + await client.call('readEntryRun', { headers, path }) + await client.call('submitEntryChunk', { headers, path, body }) + await client.call('readEntryReceipt', { headers, path: { ...path, chunk_index: 0 } }) + await client.call('cancelEntryRun', { headers, path }) + + assert.deepEqual(seen.map(request => request.headers.get(header)), [ + encoded, null, encoded, encoded, encoded, encoded, encoded, encoded, + ]) + assert.deepEqual(seen.map(request => new URL(request.url).pathname), [ + '/tenant' + batchPath, '/tenant' + batchPath, '/tenant' + listPath, '/tenant' + listPath, + '/tenant' + runPath.replace('{run_id}', run), + '/tenant' + chunkPath.replace('{run_id}', run), + '/tenant' + receiptPath.replace('{run_id}', run).replace('{chunk_index}', '0'), + '/tenant' + cancelPath.replace('{run_id}', run), + ]) + assert.ok(seen.every(request => new URL(request.url).search === '')) + for (const request of seen.filter(request => request.body !== undefined)) { + assert.deepEqual(JSON.parse(String(request.body)), body) + } +}) diff --git a/crates/registry-breg-client-node/__test__/exact-json.test.js b/crates/registry-breg-client-node/__test__/exact-json.test.js index 3f260482b3..f61f518c00 100644 --- a/crates/registry-breg-client-node/__test__/exact-json.test.js +++ b/crates/registry-breg-client-node/__test__/exact-json.test.js @@ -205,13 +205,15 @@ test('native JSON methods preserve values, metadata, cursors and mutation precon assert.equal(batchDescriptor.request.allowPatch,true); assert.equal(contract.operations.find(op=>op.kind === 'tombstone').request.allowCreate,null); const batchResult = await client.batchRecords(batch,{items:[{operation:'create',data:{wide:1}}], - changeContext:{kind:'correction',reasonCode:'verified-source',reasonText:'Correct source',sourceReferences:['case:1']}},'batch-one'); + changeContext:{kind:'correction',reasonCode:'verified-source',reasonText:'Correct source',sourceReferences:['case:1']}},'batch-one','Review é'); + assert.equal(requests.at(-1).headers['registry-access-reason'], 'UmV2aWV3IMOp'); assert.equal(batchResult.value.results[0].recordId,id); assert.equal(batchResult.value.results[0].revisionIdentifier,'2'); assert.equal(batchResult.value.results[0].domainData.wide,9007199254740992); assert.match(requests.at(-1).body,/"reasonCode":"verified-source"/); const batchPatch = await client.batchRecords(batch,{items:[{operation:'patch',recordId:id, ifMatch:'"breg-record-000000000001"',patch:[{op:'replace',field:'wide',value:2}]}]},'batch-patch'); + assert.equal(requests.at(-1).headers['registry-access-reason'], undefined); assert.equal(batchPatch.value.results[0].operation,'patch'); assert.deepEqual(JSON.parse(requests.at(-1).body),{items:[{operation:'patch',recordId:id, ifMatch:'"breg-record-000000000001"',patch:[{op:'replace',path:'/data/wide',value:2}]}]}); @@ -221,7 +223,8 @@ test('native JSON methods preserve values, metadata, cursors and mutation precon await assert.rejects(client.batchRecords(batch,{items:[{operation:'patch',recordIdentifier:id, ifMatch:'"breg-record-000000000001"',patch:[{op:'replace',field:'wide',value:2}]}]},'legacy-record-identifier'), error=>error.kind === 'invalid-request'); - const exactBatch = await client.batchRecordsJson(batch,'{"items":[{"operation":"create","data":{"wide":9007199254740992}}]}','exact-batch'); + const exactBatch = await client.batchRecordsJson(batch,'{"items":[{"operation":"create","data":{"wide":9007199254740992}}]}','exact-batch','Review é'); + assert.equal(requests.at(-1).headers['registry-access-reason'], 'UmV2aWV3IMOp'); assert.match(exactBatch.valueJson,/"revisionIdentifier":"9007199254740992"/); assert.match(requests.at(-1).body,/"wide":9007199254740992/); const tombstone = contract.selectTombstone('item',profile); diff --git a/crates/registry-breg-client-node/__test__/ingestion.test.js b/crates/registry-breg-client-node/__test__/ingestion.test.js index f2f66c22c5..b607dbcc0d 100644 --- a/crates/registry-breg-client-node/__test__/ingestion.test.js +++ b/crates/registry-breg-client-node/__test__/ingestion.test.js @@ -75,7 +75,7 @@ before(async () => { const body = Buffer.concat(chunks).toString(); // The fixture mounts the API under a /tenant base path; recorded URLs // are relative to that base, like the assertions that read them. - seen.push({ url: request.url.replace(/^\/tenant/, ''), method: request.method, contentType: request.headers['content-type'], body }); + seen.push({ url: request.url.replace(/^\/tenant/, ''), method: request.method, contentType: request.headers['content-type'], accessReasons: request.headersDistinct['registry-access-reason'], body }); const path = request.url.split('?')[0]; const answer = (status, document) => { response.setHeader('traceparent', TRACEPARENT); @@ -342,3 +342,53 @@ test('ingestionChunkReceipt reads one retained receipt and reports an erased one && error.status === 410 )); }); + +test('each ingestion exchange sends only its explicit reason header', async () => { + const client = new BaseRegistryClient({ baseUrl }); + const reason = ' Synthetic review é 🧭 '; + const encoded = Buffer.from(reason, 'utf8').toString('base64url'); + const announcement = { + operation: 'create', + profileId: 'importer.v1', + packageRevision: 'revision-1', + schemaFingerprint: 'fingerprint-1', + inputDigest: INPUT_DIGEST, + inputLength: 4321, + itemCount: 10, + chunkCount: 3, + chunkAlgorithmVersion: 'greedy-canonical-http-batch-v1', + }; + const chunk = encodeIngestionChunk(0, ITEMS, PREFIX_DIGEST); + await client.createIngestionRun('people', announcement, reason); + await client.listIngestionRuns('people', null, reason); + await client.readIngestionRun('people', RUN_ID, null, reason); + await client.submitIngestionChunk('people', RUN_ID, chunk, 'importer.v1', reason); + await client.ingestionChunkReceipt('people', RUN_ID, 0, 'importer.v1', reason); + await client.cancelIngestionRun('people', RUN_ID, null, reason); + for (const request of seen.slice(-6)) { + assert.deepEqual(request.accessReasons, [encoded]); + for (const canary of [reason, encoded]) { + assert.ok(!request.url.includes(canary)); + assert.ok(!request.body.includes(canary)); + } + } + await client.listIngestionRuns('people'); + assert.equal(seen.at(-1).accessReasons, undefined); + + const before = seen.length; + const invalid = 'synthetic\nprivate'; + await assert.rejects(client.listIngestionRuns('people', null, invalid), (error) => ( + error instanceof BaseRegistryClientError + && error.kind === 'invalid-request' + && !error.message.includes('private') + && !error.message.includes(Buffer.from(invalid).toString('base64url')) + )); + for (const malformed of ['canary\uD800', '\uDC00canary']) { + await assert.rejects(async () => client.listIngestionRuns('people', null, malformed), (error) => ( + error instanceof BaseRegistryClientError + && error.kind === 'invalid-request' + && !error.message.includes('canary') + )); + } + assert.equal(seen.length, before); +}); diff --git a/crates/registry-breg-client-node/client.d.ts b/crates/registry-breg-client-node/client.d.ts index 95b4efadfd..776356f349 100644 --- a/crates/registry-breg-client-node/client.d.ts +++ b/crates/registry-breg-client-node/client.d.ts @@ -1046,14 +1046,14 @@ export declare class BaseRegistryClient { executeRecoveredCreate(binding: BRegCreateBinding, recovered: BRegRecoveredCreate): Promise> executeRecoveredCreateJson(binding: BRegCreateBinding, recovered: BRegRecoveredCreate): Promise patchRecord(binding: BRegPatchBinding, recordId: string, etag: string, operations: ReadonlyArray, idempotencyKey: string, format?: RecordFormat | null): Promise> - batchRecords(binding: BRegBatchBinding, request: BRegBatchInput, idempotencyKey: string): Promise> - batchRecordsJson(binding: BRegBatchBinding, requestJson: string, idempotencyKey: string): Promise - createIngestionRun(recordRoute: string, request: BRegIngestionRunInput): Promise> - listIngestionRuns(recordRoute: string, query?: BRegIngestionRunListInput | null): Promise> - readIngestionRun(recordRoute: string, runId: string, accessProfile?: string | null): Promise> - submitIngestionChunk(recordRoute: string, runId: string, chunk: BRegIngestionChunk, profileId: string): Promise> - cancelIngestionRun(recordRoute: string, runId: string, accessProfile?: string | null): Promise> - ingestionChunkReceipt(recordRoute: string, runId: string, chunkIndex: SafeInteger, profileId: string): Promise> + batchRecords(binding: BRegBatchBinding, request: BRegBatchInput, idempotencyKey: string, accessReason?: string | null): Promise> + batchRecordsJson(binding: BRegBatchBinding, requestJson: string, idempotencyKey: string, accessReason?: string | null): Promise + createIngestionRun(recordRoute: string, request: BRegIngestionRunInput, accessReason?: string | null): Promise> + listIngestionRuns(recordRoute: string, query?: BRegIngestionRunListInput | null, accessReason?: string | null): Promise> + readIngestionRun(recordRoute: string, runId: string, accessProfile?: string | null, accessReason?: string | null): Promise> + submitIngestionChunk(recordRoute: string, runId: string, chunk: BRegIngestionChunk, profileId: string, accessReason?: string | null): Promise> + cancelIngestionRun(recordRoute: string, runId: string, accessProfile?: string | null, accessReason?: string | null): Promise> + ingestionChunkReceipt(recordRoute: string, runId: string, chunkIndex: SafeInteger, profileId: string, accessReason?: string | null): Promise> tombstoneRecord(binding: BRegTombstoneBinding, recordId: string, etag: string, idempotencyKey: string, format?: RecordFormat | null): Promise> tombstoneRecordJson(binding: BRegTombstoneBinding, recordId: string, etag: string, idempotencyKey: string, format?: RecordFormat | null): Promise getRecordJson(recordRoute: string, recordId: string, options?: RecordOptions | null, request?: ReadRequestOptions): Promise diff --git a/crates/registry-breg-client-node/index.d.ts b/crates/registry-breg-client-node/index.d.ts index e08d7793cd..07bed6e3fb 100644 --- a/crates/registry-breg-client-node/index.d.ts +++ b/crates/registry-breg-client-node/index.d.ts @@ -122,31 +122,31 @@ export declare class BaseRegistryClient { * unknown is resent identically under the same key, at most * `maximumMutationRetries` times. */ - batchRecords(binding: BRegBatchBinding, request: any, idempotencyKey: string): Promise + batchRecords(binding: BRegBatchBinding, request: any, idempotencyKey: string, accessReason?: string | undefined | null): Promise /** * Announce one whole input and open a durable ingestion run for it. The * run request names the access profile, which the client selects for the * exchange. */ - createIngestionRun(recordRoute: string, request: any): Promise + createIngestionRun(recordRoute: string, request: any, accessReason?: string | undefined | null): Promise /** Read one bounded page of ingestion runs for one record route. */ - listIngestionRuns(recordRoute: string, query?: any | undefined | null): Promise + listIngestionRuns(recordRoute: string, query?: any | undefined | null, accessReason?: string | undefined | null): Promise /** Read the current durable state of one ingestion run. */ - readIngestionRun(recordRoute: string, runId: string, accessProfile?: string | undefined | null): Promise + readIngestionRun(recordRoute: string, runId: string, accessProfile?: string | undefined | null, accessReason?: string | undefined | null): Promise /** * Submit one bounded chunk of an open ingestion run under the run's * access profile. A resubmitted chunk replays its retained receipt * instead of executing twice. */ - submitIngestionChunk(recordRoute: string, runId: string, chunk: BRegIngestionChunk, profileId: string): Promise + submitIngestionChunk(recordRoute: string, runId: string, chunk: BRegIngestionChunk, profileId: string, accessReason?: string | undefined | null): Promise /** Cancel an open ingestion run. Committed chunks stay committed. */ - cancelIngestionRun(recordRoute: string, runId: string, accessProfile?: string | undefined | null): Promise + cancelIngestionRun(recordRoute: string, runId: string, accessProfile?: string | undefined | null, accessReason?: string | undefined | null): Promise /** * Read the retained receipt of one committed chunk under the run's * access profile. An erased receipt answers with the * `ingestion.receipt-erased` problem instead. */ - ingestionChunkReceipt(recordRoute: string, runId: string, chunkIndex: number, profileId: string): Promise + ingestionChunkReceipt(recordRoute: string, runId: string, chunkIndex: number, profileId: string, accessReason?: string | undefined | null): Promise /** Tombstone one record against its current strong ETag. */ tombstoneRecord(binding: BRegTombstoneBinding, recordId: string, etag: string, idempotencyKey: string, formatValue?: string | undefined | null): Promise getRecordJson(recordRoute: string, recordId: string, options?: any | undefined | null, cancellation?: ReadCancellation | undefined | null): Promise @@ -183,7 +183,7 @@ export declare class BaseRegistryClient { executeRecoveredCreateJson(binding: BRegCreateBinding, recovered: BRegRecoveredCreate): Promise patchRecordJson(binding: BRegPatchBinding, recordId: string, etag: string, operationsJson: string, idempotencyKey: string, formatValue?: string | undefined | null): Promise /** Execute one metadata-selected atomic batch from exact JSON. */ - batchRecordsJson(binding: BRegBatchBinding, requestJson: string, idempotencyKey: string): Promise + batchRecordsJson(binding: BRegBatchBinding, requestJson: string, idempotencyKey: string, accessReason?: string | undefined | null): Promise /** Tombstone one record and preserve exact response values. */ tombstoneRecordJson(binding: BRegTombstoneBinding, recordId: string, etag: string, idempotencyKey: string, formatValue?: string | undefined | null): Promise } diff --git a/crates/registry-breg-client-node/src/lib.rs b/crates/registry-breg-client-node/src/lib.rs index 59ab389c49..1dd8acf6e1 100644 --- a/crates/registry-breg-client-node/src/lib.rs +++ b/crates/registry-breg-client-node/src/lib.rs @@ -9,26 +9,26 @@ use read_cancellation::ReadCancellation; use std::{collections::BTreeMap, sync::Arc, time::Duration}; use napi::{ - bindgen_prelude::{Buffer, Either, Null}, + bindgen_prelude::{Buffer, Either, Null, Utf16String}, Error as NapiError, Result, }; use napi_derive::napi; use registry_breg_client::{ event_record_view_from_json, verify_hook_delivery as verify_core_hook_delivery, - BRegActionAvailabilityRequest, BRegActionBinding, BRegActionInvocationRequest, - BRegActionTargetConditions as CoreActionTargetConditions, BRegActionTargetConditionsRequest, - BRegAsOfContinuation, BRegAsOfContinuationProjection, BRegAsOfListRequest, BRegBatchBinding, - BRegBatchBuilder, BRegBatchRequest, BRegBoundingBox, BRegChangeContext, BRegComplete, - BRegContinuation, BRegContinuationProjection, BRegCreateBinding, BRegCreateRequest, - BRegCurrentContinuation, BRegCurrentContinuationProjection, BRegCurrentListRequest, - BRegDirectWrite, BRegEtag, BRegEventRecordError, BRegGeoJsonContinuation, - BRegGeoJsonContinuationProjection, BRegGeoJsonListRequest, BRegGeoJsonOptions, - BRegHookDelivery as CoreHookDelivery, BRegHookFreshness, BRegHookVerificationError, - BRegIngestionChunk as CoreIngestionChunk, BRegIngestionError, - BRegIngestionPrefixDigest as CoreIngestionPrefixDigest, BRegIngestionRunListQuery, - BRegIngestionRunRequest, BRegListRequest, BRegLookupRequest, BRegMetadata as CoreMetadata, - BRegMetadataSelectionError, BRegMetadataSelectionErrorKind, BRegPage, BRegPatchBinding, - BRegPatchRequest, BRegPreparedAction as CorePreparedAction, + BRegAccessReason, BRegActionAvailabilityRequest, BRegActionBinding, + BRegActionInvocationRequest, BRegActionTargetConditions as CoreActionTargetConditions, + BRegActionTargetConditionsRequest, BRegAsOfContinuation, BRegAsOfContinuationProjection, + BRegAsOfListRequest, BRegBatchBinding, BRegBatchBuilder, BRegBatchRequest, BRegBoundingBox, + BRegChangeContext, BRegComplete, BRegContinuation, BRegContinuationProjection, + BRegCreateBinding, BRegCreateRequest, BRegCurrentContinuation, + BRegCurrentContinuationProjection, BRegCurrentListRequest, BRegDirectWrite, BRegEtag, + BRegEventRecordError, BRegGeoJsonContinuation, BRegGeoJsonContinuationProjection, + BRegGeoJsonListRequest, BRegGeoJsonOptions, BRegHookDelivery as CoreHookDelivery, + BRegHookFreshness, BRegHookVerificationError, BRegIngestionChunk as CoreIngestionChunk, + BRegIngestionError, BRegIngestionPrefixDigest as CoreIngestionPrefixDigest, + BRegIngestionRunListQuery, BRegIngestionRunRequest, BRegListRequest, BRegLookupRequest, + BRegMetadata as CoreMetadata, BRegMetadataSelectionError, BRegMetadataSelectionErrorKind, + BRegPage, BRegPatchBinding, BRegPatchRequest, BRegPreparedAction as CorePreparedAction, BRegPreparedCreate as CorePreparedCreate, BRegProtocolFailure, BRegRawDocument, BRegRecordFormat, BRegRecordOptions, BRegRelationshipContinuation, BRegRelationshipContinuationProjection, BRegRelationshipListRequest, BRegReleaseSelection, @@ -2077,6 +2077,17 @@ fn batch_request(binding: &BRegBatchBinding, value: Value) -> Result) -> Result> { + value + .map(|code_units| { + let reason = String::from_utf16(code_units).map_err(|_| { + binding_error("invalid-request", "the access reason must be valid Unicode") + })?; + BRegAccessReason::new(&reason).map_err(client_error) + }) + .transpose() +} + fn ingestion_error(error: BRegIngestionError) -> NapiError { binding_error("invalid-request", error.to_string()) } @@ -4240,13 +4251,20 @@ impl BaseRegistryClient { binding: &BatchBinding, request: Value, idempotency_key: String, + access_reason: Option, ) -> Result { + let access_reason = parse_access_reason(access_reason.as_deref())?; let request = batch_request(&binding.inner, request)?; let key = registry_breg_client::BRegIdempotencyKey::parse(idempotency_key) .map_err(|error| binding_error("invalid-request", error.to_string()))?; let BRegComplete { value, metadata } = self .inner - .batch_records(&binding.inner, &request, &key) + .batch_records_with_access_reason( + &binding.inner, + &request, + &key, + access_reason.as_ref(), + ) .await .map_err(client_error)?; complete_value(value, metadata) @@ -4260,11 +4278,17 @@ impl BaseRegistryClient { &self, record_route: String, request: Value, + access_reason: Option, ) -> Result { + let access_reason = parse_access_reason(access_reason.as_deref())?; let request = ingestion_run_request(request)?; let BRegComplete { value, metadata } = self .inner - .create_ingestion_run(&record_route, &request) + .create_ingestion_run_with_access_reason( + &record_route, + &request, + access_reason.as_ref(), + ) .await .map_err(client_error)?; complete_value(value, metadata) @@ -4276,11 +4300,13 @@ impl BaseRegistryClient { &self, record_route: String, query: Option, + access_reason: Option, ) -> Result { + let access_reason = parse_access_reason(access_reason.as_deref())?; let query = ingestion_run_list_query(query.as_ref())?; let BRegComplete { value, metadata } = self .inner - .list_ingestion_runs(&record_route, &query) + .list_ingestion_runs_with_access_reason(&record_route, &query, access_reason.as_ref()) .await .map_err(client_error)?; complete_value(value, metadata) @@ -4293,11 +4319,18 @@ impl BaseRegistryClient { record_route: String, run_id: String, access_profile: Option, + access_reason: Option, ) -> Result { + let access_reason = parse_access_reason(access_reason.as_deref())?; let run_id = ingestion_run_identifier(run_id)?; let BRegComplete { value, metadata } = self .inner - .read_ingestion_run(&record_route, run_id, access_profile.as_deref()) + .read_ingestion_run_with_access_reason( + &record_route, + run_id, + access_profile.as_deref(), + access_reason.as_ref(), + ) .await .map_err(client_error)?; complete_value(value, metadata) @@ -4313,12 +4346,20 @@ impl BaseRegistryClient { run_id: String, chunk: &IngestionChunk, profile_id: String, + access_reason: Option, ) -> Result { + let access_reason = parse_access_reason(access_reason.as_deref())?; let run_id = ingestion_run_identifier(run_id)?; let chunk = Arc::clone(&chunk.inner); let BRegComplete { value, metadata } = self .inner - .submit_ingestion_chunk(&record_route, run_id, chunk.as_ref(), &profile_id) + .submit_ingestion_chunk_with_access_reason( + &record_route, + run_id, + chunk.as_ref(), + &profile_id, + access_reason.as_ref(), + ) .await .map_err(client_error)?; complete_value(value, metadata) @@ -4331,11 +4372,18 @@ impl BaseRegistryClient { record_route: String, run_id: String, access_profile: Option, + access_reason: Option, ) -> Result { + let access_reason = parse_access_reason(access_reason.as_deref())?; let run_id = ingestion_run_identifier(run_id)?; let BRegComplete { value, metadata } = self .inner - .cancel_ingestion_run(&record_route, run_id, access_profile.as_deref()) + .cancel_ingestion_run_with_access_reason( + &record_route, + run_id, + access_profile.as_deref(), + access_reason.as_ref(), + ) .await .map_err(client_error)?; complete_value(value, metadata) @@ -4351,7 +4399,9 @@ impl BaseRegistryClient { run_id: String, chunk_index: i64, profile_id: String, + access_reason: Option, ) -> Result { + let access_reason = parse_access_reason(access_reason.as_deref())?; let run_id = ingestion_run_identifier(run_id)?; let chunk_index = ingestion_chunk_index( chunk_index, @@ -4359,7 +4409,13 @@ impl BaseRegistryClient { )?; let BRegComplete { value, metadata } = self .inner - .ingestion_chunk_receipt(&record_route, run_id, chunk_index, &profile_id) + .ingestion_chunk_receipt_with_access_reason( + &record_route, + run_id, + chunk_index, + &profile_id, + access_reason.as_ref(), + ) .await .map_err(client_error)?; complete_value(value, metadata) @@ -4920,13 +4976,20 @@ impl BaseRegistryClient { binding: &BatchBinding, request_json: String, idempotency_key: String, + access_reason: Option, ) -> Result { + let access_reason = parse_access_reason(access_reason.as_deref())?; let request = batch_request(&binding.inner, exact_input(&request_json)?)?; let key = registry_breg_client::BRegIdempotencyKey::parse(idempotency_key) .map_err(|error| binding_error("invalid-request", error.to_string()))?; let BRegComplete { value, metadata } = self .inner - .batch_records(&binding.inner, &request, &key) + .batch_records_with_access_reason( + &binding.inner, + &request, + &key, + access_reason.as_ref(), + ) .await .map_err(client_error)?; complete_json_value(value, metadata) diff --git a/crates/registry-breg-client-py/python/registry_breg_client/__init__.pyi b/crates/registry-breg-client-py/python/registry_breg_client/__init__.pyi index ec0f1b4e6b..f5e12932e8 100644 --- a/crates/registry-breg-client-py/python/registry_breg_client/__init__.pyi +++ b/crates/registry-breg-client-py/python/registry_breg_client/__init__.pyi @@ -742,11 +742,14 @@ class BaseRegistryClient: idempotency_key: str, *, change_context: dict[str, JsonValue] | None = None, + access_reason: str | None = None, ) -> dict[str, Any]: ... def create_ingestion_run( self, record_route: str, request: dict[str, JsonValue], + *, + access_reason: str | None = None, ) -> dict[str, Any]: ... def list_ingestion_runs( self, @@ -757,12 +760,15 @@ class BaseRegistryClient: status: IngestionRunStatus | None = None, input_digest: str | None = None, access_profile: str | None = None, + access_reason: str | None = None, ) -> dict[str, Any]: ... def read_ingestion_run( self, record_route: str, run_id: str, access_profile: str | None = None, + *, + access_reason: str | None = None, ) -> dict[str, Any]: ... def submit_ingestion_chunk( self, @@ -770,12 +776,16 @@ class BaseRegistryClient: run_id: str, chunk: BRegIngestionChunk, profile_id: str, + *, + access_reason: str | None = None, ) -> dict[str, Any]: ... def cancel_ingestion_run( self, record_route: str, run_id: str, access_profile: str | None = None, + *, + access_reason: str | None = None, ) -> dict[str, Any]: ... def ingestion_chunk_receipt( self, @@ -783,6 +793,8 @@ class BaseRegistryClient: run_id: str, chunk_index: int, profile_id: str, + *, + access_reason: str | None = None, ) -> dict[str, Any]: ... __version__: str diff --git a/crates/registry-breg-client-py/src/lib.rs b/crates/registry-breg-client-py/src/lib.rs index d52d0dd701..19291f70b9 100644 --- a/crates/registry-breg-client-py/src/lib.rs +++ b/crates/registry-breg-client-py/src/lib.rs @@ -7,11 +7,11 @@ use std::{sync::Arc, time::Duration}; use breg_client_sdk::{ event_record_view_from_json, verify_hook_delivery as verify_core_hook_delivery, - BRegActionAvailabilityRequest, BRegActionBinding, BRegActionInvocationRequest, - BRegActionTargetConditions, BRegActionTargetConditionsRequest, BRegAsOfContinuation, - BRegAsOfContinuationProjection, BRegAsOfListRequest, BRegBatchBinding, BRegBatchBuilder, - BRegBoundingBox, BRegChangeContext, BRegComplete, BRegContinuation, BRegContinuationProjection, - BRegCreateBinding, BRegCreateRequest, BRegCurrentContinuation, + BRegAccessReason, BRegActionAvailabilityRequest, BRegActionBinding, + BRegActionInvocationRequest, BRegActionTargetConditions, BRegActionTargetConditionsRequest, + BRegAsOfContinuation, BRegAsOfContinuationProjection, BRegAsOfListRequest, BRegBatchBinding, + BRegBatchBuilder, BRegBoundingBox, BRegChangeContext, BRegComplete, BRegContinuation, + BRegContinuationProjection, BRegCreateBinding, BRegCreateRequest, BRegCurrentContinuation, BRegCurrentContinuationProjection, BRegCurrentListRequest, BRegDirectWrite, BRegEtag, BRegEventRecordError, BRegGeoJsonContinuation, BRegGeoJsonContinuationProjection, BRegGeoJsonListRequest, BRegGeoJsonOptions, BRegHookDelivery as CoreHookDelivery, @@ -793,6 +793,20 @@ fn batch_request( .map_err(|error| invalid(py, error.to_string())) } +fn parse_access_reason( + py: Python<'_>, + value: Option<&Bound<'_, PyAny>>, +) -> PyResult> { + value + .map(|value| { + let invalid_text = || invalid(py, "the access reason must be a valid Unicode string"); + let text = value.cast::().map_err(|_| invalid_text())?; + let reason = text.to_str().map_err(|_| invalid_text())?; + BRegAccessReason::new(reason).map_err(|error| sdk_error(py, error)) + }) + .transpose() +} + fn ingestion_error(py: Python<'_>, error: BRegIngestionError) -> PyErr { invalid(py, error.to_string()) } @@ -3641,7 +3655,8 @@ impl BaseRegistryClient { complete_value(py, &value.value, &value.metadata) } - #[pyo3(signature = (binding, items, idempotency_key, *, change_context=None))] + #[pyo3(signature = (binding, items, idempotency_key, *, change_context=None, access_reason=None))] + #[allow(clippy::too_many_arguments)] fn batch_records<'py>( &self, py: Python<'py>, @@ -3649,7 +3664,9 @@ impl BaseRegistryClient { items: &Bound<'_, PyAny>, idempotency_key: &str, change_context: Option<&Bound<'_, PyAny>>, + access_reason: Option<&Bound<'_, PyAny>>, ) -> PyResult> { + let access_reason = parse_access_reason(py, access_reason)?; let request = batch_request(py, &binding.inner, items, change_context)?; let key = BRegIdempotencyKey::parse(idempotency_key) .map_err(|error| invalid(py, error.to_string()))?; @@ -3658,7 +3675,12 @@ impl BaseRegistryClient { let value = py .detach(|| { self.runtime - .block_on(self.inner.batch_records(&binding, request.as_ref(), &key)) + .block_on(self.inner.batch_records_with_access_reason( + &binding, + request.as_ref(), + &key, + access_reason.as_ref(), + )) }) .map_err(|error| sdk_error(py, error))?; complete_value(py, &value.value, &value.metadata) @@ -3667,26 +3689,31 @@ impl BaseRegistryClient { /// Announce one whole input and open a durable ingestion run for it. The /// run request names the access profile, which the client selects for the /// exchange. + #[pyo3(signature = (record_route, request, *, access_reason=None))] fn create_ingestion_run<'py>( &self, py: Python<'py>, record_route: &str, request: &Bound<'_, PyAny>, + access_reason: Option<&Bound<'_, PyAny>>, ) -> PyResult> { + let access_reason = parse_access_reason(py, access_reason)?; let request = Arc::new(ingestion_run_request(py, request)?); let value = py .detach(|| { - self.runtime.block_on( - self.inner - .create_ingestion_run(record_route, request.as_ref()), - ) + self.runtime + .block_on(self.inner.create_ingestion_run_with_access_reason( + record_route, + request.as_ref(), + access_reason.as_ref(), + )) }) .map_err(|error| sdk_error(py, error))?; complete_value(py, &value.value, &value.metadata) } /// Read one bounded page of ingestion runs for one record route. - #[pyo3(signature = (record_route, *, limit=None, cursor=None, status=None, input_digest=None, access_profile=None))] + #[pyo3(signature = (record_route, *, limit=None, cursor=None, status=None, input_digest=None, access_profile=None, access_reason=None))] #[allow(clippy::too_many_arguments)] fn list_ingestion_runs<'py>( &self, @@ -3697,35 +3724,45 @@ impl BaseRegistryClient { status: Option, input_digest: Option, access_profile: Option, + access_reason: Option<&Bound<'_, PyAny>>, ) -> PyResult> { + let access_reason = parse_access_reason(py, access_reason)?; let query = ingestion_run_list_query(py, limit, cursor, status, input_digest, access_profile)?; let value = py .detach(|| { self.runtime - .block_on(self.inner.list_ingestion_runs(record_route, &query)) + .block_on(self.inner.list_ingestion_runs_with_access_reason( + record_route, + &query, + access_reason.as_ref(), + )) }) .map_err(|error| sdk_error(py, error))?; complete_value(py, &value.value, &value.metadata) } /// Read the current durable state of one ingestion run. - #[pyo3(signature = (record_route, run_id, access_profile=None))] + #[pyo3(signature = (record_route, run_id, access_profile=None, *, access_reason=None))] fn read_ingestion_run<'py>( &self, py: Python<'py>, record_route: &str, run_id: &str, access_profile: Option<&str>, + access_reason: Option<&Bound<'_, PyAny>>, ) -> PyResult> { + let access_reason = parse_access_reason(py, access_reason)?; let run_id = ingestion_run_identifier(py, run_id)?; let value = py .detach(|| { - self.runtime.block_on(self.inner.read_ingestion_run( - record_route, - run_id, - access_profile, - )) + self.runtime + .block_on(self.inner.read_ingestion_run_with_access_reason( + record_route, + run_id, + access_profile, + access_reason.as_ref(), + )) }) .map_err(|error| sdk_error(py, error))?; complete_value(py, &value.value, &value.metadata) @@ -3734,6 +3771,8 @@ impl BaseRegistryClient { /// Submit one bounded chunk of an open ingestion run under the run's /// access profile. A resubmitted chunk replays its retained receipt /// instead of executing twice. + #[pyo3(signature = (record_route, run_id, chunk, profile_id, *, access_reason=None))] + #[allow(clippy::too_many_arguments)] fn submit_ingestion_chunk<'py>( &self, py: Python<'py>, @@ -3741,39 +3780,47 @@ impl BaseRegistryClient { run_id: &str, chunk: PyRef<'_, IngestionChunk>, profile_id: &str, + access_reason: Option<&Bound<'_, PyAny>>, ) -> PyResult> { + let access_reason = parse_access_reason(py, access_reason)?; let run_id = ingestion_run_identifier(py, run_id)?; let chunk = Arc::clone(&chunk.inner); let value = py .detach(|| { - self.runtime.block_on(self.inner.submit_ingestion_chunk( - record_route, - run_id, - chunk.as_ref(), - profile_id, - )) + self.runtime + .block_on(self.inner.submit_ingestion_chunk_with_access_reason( + record_route, + run_id, + chunk.as_ref(), + profile_id, + access_reason.as_ref(), + )) }) .map_err(|error| sdk_error(py, error))?; complete_value(py, &value.value, &value.metadata) } /// Cancel an open ingestion run. Committed chunks stay committed. - #[pyo3(signature = (record_route, run_id, access_profile=None))] + #[pyo3(signature = (record_route, run_id, access_profile=None, *, access_reason=None))] fn cancel_ingestion_run<'py>( &self, py: Python<'py>, record_route: &str, run_id: &str, access_profile: Option<&str>, + access_reason: Option<&Bound<'_, PyAny>>, ) -> PyResult> { + let access_reason = parse_access_reason(py, access_reason)?; let run_id = ingestion_run_identifier(py, run_id)?; let value = py .detach(|| { - self.runtime.block_on(self.inner.cancel_ingestion_run( - record_route, - run_id, - access_profile, - )) + self.runtime + .block_on(self.inner.cancel_ingestion_run_with_access_reason( + record_route, + run_id, + access_profile, + access_reason.as_ref(), + )) }) .map_err(|error| sdk_error(py, error))?; complete_value(py, &value.value, &value.metadata) @@ -3782,7 +3829,8 @@ impl BaseRegistryClient { /// Read the retained receipt of one committed chunk under the run's /// access profile. An erased receipt answers with the /// `ingestion.receipt-erased` problem instead. - #[pyo3(signature = (record_route, run_id, chunk_index, profile_id))] + #[pyo3(signature = (record_route, run_id, chunk_index, profile_id, *, access_reason=None))] + #[allow(clippy::too_many_arguments)] fn ingestion_chunk_receipt<'py>( &self, py: Python<'py>, @@ -3790,16 +3838,20 @@ impl BaseRegistryClient { run_id: &str, chunk_index: u64, profile_id: &str, + access_reason: Option<&Bound<'_, PyAny>>, ) -> PyResult> { + let access_reason = parse_access_reason(py, access_reason)?; let run_id = ingestion_run_identifier(py, run_id)?; let value = py .detach(|| { - self.runtime.block_on(self.inner.ingestion_chunk_receipt( - record_route, - run_id, - chunk_index, - profile_id, - )) + self.runtime + .block_on(self.inner.ingestion_chunk_receipt_with_access_reason( + record_route, + run_id, + chunk_index, + profile_id, + access_reason.as_ref(), + )) }) .map_err(|error| sdk_error(py, error))?; complete_value(py, &value.value, &value.metadata) diff --git a/crates/registry-breg-client-py/tests/python/test_ingestion_runs.py b/crates/registry-breg-client-py/tests/python/test_ingestion_runs.py index 923d585a27..1f2c7a7d5d 100644 --- a/crates/registry-breg-client-py/tests/python/test_ingestion_runs.py +++ b/crates/registry-breg-client-py/tests/python/test_ingestion_runs.py @@ -1,5 +1,6 @@ """Exercise the durable ingestion-run surface through the Python binding.""" +import base64 import hashlib import json import re @@ -95,6 +96,8 @@ def receipt_wire() -> dict: class IngestionRunTests(unittest.TestCase): def setUp(self) -> None: self.requests = [] + self.access_reasons = [] + access_reasons = self.access_reasons requests = self.requests class Handler(BaseHTTPRequestHandler): @@ -150,6 +153,7 @@ def do_POST(self) -> None: # noqa: N802 self.answer(404, {}) def record(self, body: bytes) -> None: + access_reasons.append(self.headers.get_all("registry-access-reason")) requests.append( (self.command, self.path, self.headers.get("content-type"), body) ) @@ -387,6 +391,44 @@ def test_chunk_receipt_reads_one_retained_and_reports_one_erased(self) -> None: self.assertEqual(raised.exception.code, "ingestion.receipt-erased") self.assertEqual(raised.exception.status, 410) + def test_ingestion_access_reason_is_per_exchange(self) -> None: + reason = " Synthetic review é 🧭 " + encoded = base64.urlsafe_b64encode(reason.encode()).decode().rstrip("=") + chunk = encode_ingestion_chunk(0, ITEMS, PREFIX_DIGEST) + self.client.create_ingestion_run("people", REQUEST, access_reason=reason) + self.client.list_ingestion_runs("people", access_reason=reason) + self.client.read_ingestion_run("people", RUN_ID, access_reason=reason) + self.client.submit_ingestion_chunk( + "people", RUN_ID, chunk, "importer.v1", access_reason=reason + ) + self.client.ingestion_chunk_receipt( + "people", RUN_ID, 0, "importer.v1", access_reason=reason + ) + self.client.cancel_ingestion_run("people", RUN_ID, access_reason=reason) + self.assertEqual(self.access_reasons, [[encoded]] * 6) + for _, path, _, body in self.requests: + for canary in (reason, encoded): + self.assertNotIn(canary, path) + self.assertNotIn(canary.encode(), body) + + self.client.list_ingestion_runs("people") + self.assertIsNone(self.access_reasons[-1]) + invalid = "synthetic\nprivate" + with self.assertRaises(BaseRegistryClientError) as raised: + self.client.list_ingestion_runs("people", access_reason=invalid) + self.assertEqual(raised.exception.kind, "invalid-request") + self.assertNotIn("private", str(raised.exception)) + self.assertNotIn( + base64.urlsafe_b64encode(invalid.encode()).decode().rstrip("="), + str(raised.exception), + ) + for malformed in ("canary\ud800", "\udc00canary"): + with self.assertRaises(BaseRegistryClientError) as raised: + self.client.list_ingestion_runs("people", access_reason=malformed) + self.assertEqual(raised.exception.kind, "invalid-request") + self.assertNotIn("canary", str(raised.exception)) + self.assertEqual(len(self.requests), 7) + if __name__ == "__main__": unittest.main() diff --git a/crates/registry-breg-client-py/tests/python/test_mutation_parity.py b/crates/registry-breg-client-py/tests/python/test_mutation_parity.py index c53612bc15..e4fa67749b 100644 --- a/crates/registry-breg-client-py/tests/python/test_mutation_parity.py +++ b/crates/registry-breg-client-py/tests/python/test_mutation_parity.py @@ -691,6 +691,7 @@ def test_tombstone_and_batch_use_exact_conditions_and_context(self) -> None: batch, [{"operation": "create", "data": {"legalName": "Batch Ltd"}}], "batch-1", + access_reason="Review é", change_context={ "kind": "correction", "reason_code": "verified-source", @@ -712,6 +713,7 @@ def test_tombstone_and_batch_use_exact_conditions_and_context(self) -> None: method, path, headers, body = self.requests[-1] self.assertEqual((method, path), ("POST", "/v1/records/companies:batch?accessProfile=company-writer")) self.assertEqual(headers["idempotency-key"], "batch-1") + self.assertEqual(headers["registry-access-reason"], "UmV2aWV3IMOp") self.assertEqual( json.loads(body), { @@ -731,6 +733,7 @@ def test_tombstone_and_batch_use_exact_conditions_and_context(self) -> None: "batch-patch-1", ) self.assertEqual(receipt["value"]["results"][0]["operation"], "patch") + self.assertNotIn("registry-access-reason", self.requests[-1][2]) self.assertEqual( json.loads(self.requests[-1][3]), { diff --git a/crates/registry-breg-client/src/actions.rs b/crates/registry-breg-client/src/actions.rs index 4b3d91b690..9c7606df34 100644 --- a/crates/registry-breg-client/src/actions.rs +++ b/crates/registry-breg-client/src/actions.rs @@ -589,6 +589,7 @@ impl BaseRegistryClient { let restored = BRegActionInvocationRequest::new(action, original_inputs.clone(), conditions.as_ref()) .map_err(|_| action_recovery_refusal())?; + // Recovery requires the exact canonical body, including closed condition objects. if restored.body.as_slice() != saved.body.as_bytes() { return Err(action_recovery_refusal()); } @@ -832,28 +833,11 @@ fn decode_availability( ) -> Result { let value = crate::strict_json::from_slice(bytes).map_err(|_| BRegActionError::InvalidResponse)?; - let outer = value - .as_object() - .filter(|object| object.len() == 1) - .ok_or(BRegActionError::InvalidResponse)?; + let outer = value.as_object().ok_or(BRegActionError::InvalidResponse)?; let availability = outer .get("availability") .and_then(Value::as_object) .ok_or(BRegActionError::InvalidResponse)?; - if availability.keys().any(|key| { - !matches!( - key.as_str(), - "available" - | "observedRevision" - | "reason" - | "recovery" - | "missingInputs" - | "guardReason" - | "guardLabel" - ) - }) { - return Err(BRegActionError::InvalidResponse); - } let available = match availability.get("available") { Some(Value::Bool(value)) => Some(*value), Some(Value::Null) => None, @@ -944,10 +928,7 @@ fn decode_conditions( ) -> Result { let value = crate::strict_json::from_slice(bytes).map_err(|_| BRegActionError::InvalidResponse)?; - let object = value - .as_object() - .filter(|object| object.len() == 1) - .ok_or(BRegActionError::InvalidResponse)?; + let object = value.as_object().ok_or(BRegActionError::InvalidResponse)?; let conditions = object .get("preconditions") .and_then(Value::as_object) @@ -962,10 +943,7 @@ fn decode_conditions( let preconditions = conditions .iter() .map(|(name, value)| { - let condition = value - .as_object() - .filter(|condition| condition.len() == 1) - .ok_or(BRegActionError::InvalidResponse)?; + let condition = value.as_object().ok_or(BRegActionError::InvalidResponse)?; let if_match = condition .get("ifMatch") .and_then(Value::as_str) @@ -992,10 +970,7 @@ fn decode_receipt( ) -> Result { let value = crate::strict_json::from_slice(bytes).map_err(|_| BRegActionError::InvalidResponse)?; - let object = value - .as_object() - .filter(|object| object.len() == 3) - .ok_or(BRegActionError::InvalidResponse)?; + let object = value.as_object().ok_or(BRegActionError::InvalidResponse)?; if object.get("action").and_then(Value::as_str) != Some(action.action_identifier()) { return Err(BRegActionError::InvalidResponse); } @@ -1020,10 +995,7 @@ fn decode_receipt( let results = values .iter() .map(|(effect, value)| { - let result = value - .as_object() - .filter(|result| result.len() == 3) - .ok_or(BRegActionError::InvalidResponse)?; + let result = value.as_object().ok_or(BRegActionError::InvalidResponse)?; let entity = result .get("recordType") .and_then(Value::as_str) diff --git a/crates/registry-breg-client/src/batch.rs b/crates/registry-breg-client/src/batch.rs index 8cf7168b98..f012298437 100644 --- a/crates/registry-breg-client/src/batch.rs +++ b/crates/registry-breg-client/src/batch.rs @@ -11,8 +11,8 @@ use uuid::Uuid; use zeroize::Zeroizing; use crate::{ - BRegBatchBinding, BRegComplete, BRegCreateRequest, BRegEtag, BRegIdempotencyKey, - BRegPatchRequest, BaseRegistryClient, BaseRegistryClientError, + BRegAccessReason, BRegBatchBinding, BRegComplete, BRegCreateRequest, BRegEtag, + BRegIdempotencyKey, BRegPatchRequest, BaseRegistryClient, BaseRegistryClientError, }; const MAXIMUM_CHANGE_CONTEXT_BYTES: usize = 16 * 1024; @@ -412,6 +412,18 @@ impl BaseRegistryClient { operation: &BRegBatchBinding, request: &BRegBatchRequest, idempotency_key: &BRegIdempotencyKey, + ) -> Result, BaseRegistryClientError> { + self.batch_records_with_access_reason(operation, request, idempotency_key, None) + .await + } + + /// Like [Self::batch_records], with an optional access reason for this request. + pub async fn batch_records_with_access_reason( + &self, + operation: &BRegBatchBinding, + request: &BRegBatchRequest, + idempotency_key: &BRegIdempotencyKey, + access_reason: Option<&BRegAccessReason>, ) -> Result, BaseRegistryClientError> { if !operation.matches_source(&self.source_binding()) || request.binding.source_binding() != self.source_binding() @@ -422,11 +434,12 @@ impl BaseRegistryClient { )); } let raw = self - .execute_bound_json( + .execute_bound_json_with_access_reason( &operation.path(), operation.access_profile(), request.body().to_vec(), Some(idempotency_key), + access_reason, ) .await?; let receipt = decode_receipt(raw.value.as_bytes(), request).map_err(|_| { diff --git a/crates/registry-breg-client/src/client.rs b/crates/registry-breg-client/src/client.rs index d2479c5d4d..1016449ac8 100644 --- a/crates/registry-breg-client/src/client.rs +++ b/crates/registry-breg-client/src/client.rs @@ -7,15 +7,18 @@ use std::fmt; use async_trait::async_trait; -use base64::{engine::general_purpose::STANDARD, Engine as _}; +use base64::{ + engine::general_purpose::{STANDARD, URL_SAFE_NO_PAD}, + Engine as _, +}; use registry_platform_httpsec::{response_trace_id, ProblemDocument, TraceId}; use registry_platform_httputil::client::{ classify_keyed_attempt, retry_keyed_mutation, BearerToken, KeyedMutationAttempt, RetryAfter, TokenError, TokenProvider, }; use reqwest::header::{ - ACCEPT, AUTHORIZATION, CACHE_CONTROL, CONTENT_DISPOSITION, CONTENT_TYPE, ETAG, IF_MATCH, LINK, - LOCATION, VARY, + HeaderValue, ACCEPT, AUTHORIZATION, CACHE_CONTROL, CONTENT_DISPOSITION, CONTENT_TYPE, ETAG, + IF_MATCH, LINK, LOCATION, VARY, }; use reqwest::{Method, Response, StatusCode}; use serde_json::Value; @@ -37,6 +40,44 @@ const MAXIMUM_ENGINE_VERSION_BYTES: usize = 64; const X_CONTENT_TYPE_OPTIONS: reqwest::header::HeaderName = reqwest::header::HeaderName::from_static("x-content-type-options"); +/// A validated, per-request reason for BReg Batch and ingestion exchanges. +/// +/// The header carries the original UTF-8 bytes as unpadded base64url. Supply +/// this value only on the operation for which the caller stated the reason. +#[derive(Clone, Debug)] +pub struct BRegAccessReason(HeaderValue); + +impl BRegAccessReason { + /// Maximum size of the reason in UTF-8 bytes. + pub const MAX_BYTES: usize = 512; + + /// Validate a caller-stated reason before acquiring a token or sending it. + pub fn new(value: &str) -> Result { + const INVALID_REASON: &str = + "access reasons require nonblank UTF-8 of up to 512 bytes without control characters"; + if value.len() > Self::MAX_BYTES + || value.trim().is_empty() + || value.chars().any(char::is_control) + { + return Err(BaseRegistryClientError::invalid_request(INVALID_REASON)); + } + let mut header = HeaderValue::from_str(&URL_SAFE_NO_PAD.encode(value)) + .map_err(|_| BaseRegistryClientError::invalid_request(INVALID_REASON))?; + header.set_sensitive(true); + Ok(Self(header)) + } +} + +fn with_access_reason( + builder: reqwest::RequestBuilder, + access_reason: Option<&BRegAccessReason>, +) -> reqwest::RequestBuilder { + match access_reason { + Some(reason) => builder.header("registry-access-reason", reason.0.clone()), + None => builder, + } +} + /// One explicitly initiated exchange with one Base Registry Engine deployment. pub struct BaseRegistryClient { config: BaseRegistryClientConfig, @@ -1329,6 +1370,24 @@ impl BaseRegistryClient { access_profile: &str, body: Vec, idempotency_key: Option<&BRegIdempotencyKey>, + ) -> Result, BaseRegistryClientError> { + self.execute_bound_json_with_access_reason( + path, + access_profile, + body, + idempotency_key, + None, + ) + .await + } + + pub(crate) async fn execute_bound_json_with_access_reason( + &self, + path: &str, + access_profile: &str, + body: Vec, + idempotency_key: Option<&BRegIdempotencyKey>, + access_reason: Option<&BRegAccessReason>, ) -> Result, BaseRegistryClientError> { let segments = bound_json_operation_segments(path)?; let pairs = access_profile_query(Some(access_profile))?; @@ -1340,6 +1399,7 @@ impl BaseRegistryClient { .header(ACCEPT, APPLICATION_JSON) .header(CONTENT_TYPE, APPLICATION_JSON) .body(body); + builder = with_access_reason(builder, access_reason); let decode = move |response| async move { let wire = self.bound_json_wire(response, StatusCode::OK).await?; crate::strict_json::from_slice(&wire.body) @@ -1643,15 +1703,19 @@ impl BaseRegistryClient { &self, segments: &[&str], pairs: &[(String, String)], + access_reason: Option<&BRegAccessReason>, ) -> Result, BaseRegistryClientError> { + let url = self.url_with_query(segments, pairs)?; + let builder = self + .transport + .http + .get(url) + .header(ACCEPT, APPLICATION_JSON); + let builder = with_access_reason(builder, access_reason); + let builder = self.authorize(builder, Credential::Optional).await?; + let response = self.transport.send(builder).await?; let wire = self - .get( - segments, - pairs, - APPLICATION_JSON, - Credential::Optional, - EntityTagExpectation::Forbidden, - ) + .wire(response, APPLICATION_JSON, EntityTagExpectation::Forbidden) .await?; Ok(BRegComplete { value: BRegRawDocument::new(wire.media_type, wire.body), @@ -1859,6 +1923,7 @@ impl BaseRegistryClient { body: Vec, content_type: Option<&'static str>, expected_status: StatusCode, + access_reason: Option<&BRegAccessReason>, ) -> Result, BaseRegistryClientError> { let url = self.url_with_query(segments, pairs)?; let mut builder = self @@ -1869,7 +1934,7 @@ impl BaseRegistryClient { if let Some(media_type) = content_type { builder = builder.header(CONTENT_TYPE, media_type); } - let builder = builder.body(body); + let builder = with_access_reason(builder.body(body), access_reason); let builder = self.authorize(builder, Credential::Optional).await?; let response = self.transport.send(builder).await?; let wire = self.bound_json_wire(response, expected_status).await?; diff --git a/crates/registry-breg-client/src/geojson.rs b/crates/registry-breg-client/src/geojson.rs index cbce43fb39..06afc7c01d 100644 --- a/crates/registry-breg-client/src/geojson.rs +++ b/crates/registry-breg-client/src/geojson.rs @@ -227,7 +227,6 @@ pub struct BRegGeoJsonPage { #[serde(deny_unknown_fields, rename_all = "camelCase")] pub struct BRegGeoJsonContinuationProjection { pub route: String, - #[serde(alias = "skiptoken")] pub cursor: String, #[serde(skip_serializing_if = "Option::is_none")] pub access_profile: Option, @@ -581,6 +580,20 @@ mod tests { use super::*; use serde_json::json; + #[test] + fn retired_saved_geojson_cursor_name_is_refused() { + let saved = json!({"route": "assets", "cursor": "opaque", "accessProfile": "reader"}); + let continuation = + serde_json::from_value::(saved.clone()).unwrap(); + assert_eq!(serde_json::to_value(continuation).unwrap(), saved); + for retired in [ + json!({"route": "assets", "skiptoken": "opaque"}), + json!({"route": "assets", "cursor": "opaque", "skiptoken": "opaque"}), + ] { + assert!(serde_json::from_value::(retired).is_err()); + } + } + #[test] fn feature_preserves_null_geometry_and_has_no_mutation_metadata() { let feature = decode_feature(json!({ diff --git a/crates/registry-breg-client/src/ingestion.rs b/crates/registry-breg-client/src/ingestion.rs index 03cc2838ee..45746477d7 100644 --- a/crates/registry-breg-client/src/ingestion.rs +++ b/crates/registry-breg-client/src/ingestion.rs @@ -26,7 +26,8 @@ use crate::mutation::{ validate_json_values, MAXIMUM_BREG_MUTATION_BODY_BYTES, MAXIMUM_BREG_PATCH_OPERATIONS, }; use crate::{ - BRegBatchOperation, BRegComplete, BRegRawDocument, BaseRegistryClient, BaseRegistryClientError, + BRegAccessReason, BRegBatchOperation, BRegComplete, BRegRawDocument, BaseRegistryClient, + BaseRegistryClientError, }; /// The chunk-planning algorithm this client derives chunk digests for. A run @@ -1498,6 +1499,17 @@ impl BaseRegistryClient { &self, record_route: &str, request: &BRegIngestionRunRequest, + ) -> Result, BaseRegistryClientError> { + self.create_ingestion_run_with_access_reason(record_route, request, None) + .await + } + + /// Like [Self::create_ingestion_run], with an optional access reason for this request. + pub async fn create_ingestion_run_with_access_reason( + &self, + record_route: &str, + request: &BRegIngestionRunRequest, + access_reason: Option<&BRegAccessReason>, ) -> Result, BaseRegistryClientError> { validate_record_route(record_route)?; let pairs = access_profile_query(Some(request.profile_id()))?; @@ -1508,6 +1520,7 @@ impl BaseRegistryClient { request.body().to_vec(), Some(crate::client::APPLICATION_JSON), reqwest::StatusCode::CREATED, + access_reason, ) .await?; decode_envelope( @@ -1528,12 +1541,24 @@ impl BaseRegistryClient { &self, record_route: &str, query: &BRegIngestionRunListQuery, + ) -> Result, BaseRegistryClientError> { + self.list_ingestion_runs_with_access_reason(record_route, query, None) + .await + } + + /// Like [Self::list_ingestion_runs], with an optional access reason for this request. + pub async fn list_ingestion_runs_with_access_reason( + &self, + record_route: &str, + query: &BRegIngestionRunListQuery, + access_reason: Option<&BRegAccessReason>, ) -> Result, BaseRegistryClientError> { validate_record_route(record_route)?; let raw = self .ingestion_get_json( &["v1", "records", record_route, "ingestion-runs"], &query.query_pairs(), + access_reason, ) .await?; decode_envelope( @@ -1552,6 +1577,18 @@ impl BaseRegistryClient { record_route: &str, run_id: Uuid, access_profile: Option<&str>, + ) -> Result, BaseRegistryClientError> { + self.read_ingestion_run_with_access_reason(record_route, run_id, access_profile, None) + .await + } + + /// Like [Self::read_ingestion_run], with an optional access reason for this request. + pub async fn read_ingestion_run_with_access_reason( + &self, + record_route: &str, + run_id: Uuid, + access_profile: Option<&str>, + access_reason: Option<&BRegAccessReason>, ) -> Result, BaseRegistryClientError> { validate_record_route(record_route)?; let run_identifier = run_id.to_string(); @@ -1566,6 +1603,7 @@ impl BaseRegistryClient { &run_identifier, ], &pairs, + access_reason, ) .await?; decode_envelope(raw, reqwest::StatusCode::OK.as_u16(), &["run"], |object| { @@ -1586,6 +1624,25 @@ impl BaseRegistryClient { run_id: Uuid, chunk: &BRegIngestionChunk, profile_id: &str, + ) -> Result, BaseRegistryClientError> { + self.submit_ingestion_chunk_with_access_reason( + record_route, + run_id, + chunk, + profile_id, + None, + ) + .await + } + + /// Like [Self::submit_ingestion_chunk], with an optional access reason for this request. + pub async fn submit_ingestion_chunk_with_access_reason( + &self, + record_route: &str, + run_id: Uuid, + chunk: &BRegIngestionChunk, + profile_id: &str, + access_reason: Option<&BRegAccessReason>, ) -> Result, BaseRegistryClientError> { validate_record_route(record_route)?; let run_identifier = run_id.to_string(); @@ -1604,6 +1661,7 @@ impl BaseRegistryClient { chunk.body().to_vec(), Some(crate::client::APPLICATION_JSON), reqwest::StatusCode::OK, + access_reason, ) .await?; decode_envelope( @@ -1630,6 +1688,18 @@ impl BaseRegistryClient { record_route: &str, run_id: Uuid, access_profile: Option<&str>, + ) -> Result, BaseRegistryClientError> { + self.cancel_ingestion_run_with_access_reason(record_route, run_id, access_profile, None) + .await + } + + /// Like [Self::cancel_ingestion_run], with an optional access reason for this request. + pub async fn cancel_ingestion_run_with_access_reason( + &self, + record_route: &str, + run_id: Uuid, + access_profile: Option<&str>, + access_reason: Option<&BRegAccessReason>, ) -> Result, BaseRegistryClientError> { validate_record_route(record_route)?; let run_identifier = run_id.to_string(); @@ -1648,6 +1718,7 @@ impl BaseRegistryClient { Vec::new(), None, reqwest::StatusCode::OK, + access_reason, ) .await?; decode_envelope(raw, reqwest::StatusCode::OK.as_u16(), &["run"], |object| { @@ -1667,6 +1738,25 @@ impl BaseRegistryClient { run_id: Uuid, chunk_index: u64, profile_id: &str, + ) -> Result, BaseRegistryClientError> { + self.ingestion_chunk_receipt_with_access_reason( + record_route, + run_id, + chunk_index, + profile_id, + None, + ) + .await + } + + /// Like [Self::ingestion_chunk_receipt], with an optional access reason for this request. + pub async fn ingestion_chunk_receipt_with_access_reason( + &self, + record_route: &str, + run_id: Uuid, + chunk_index: u64, + profile_id: &str, + access_reason: Option<&BRegAccessReason>, ) -> Result, BaseRegistryClientError> { validate_record_route(record_route)?; let run_identifier = run_id.to_string(); @@ -1685,6 +1775,7 @@ impl BaseRegistryClient { "receipt", ], &pairs, + access_reason, ) .await?; decode_envelope( diff --git a/crates/registry-breg-client/src/lib.rs b/crates/registry-breg-client/src/lib.rs index f87c1c0a3d..535a05b47e 100644 --- a/crates/registry-breg-client/src/lib.rs +++ b/crates/registry-breg-client/src/lib.rs @@ -41,7 +41,7 @@ mod transport; pub use actions::*; pub use attachment::*; pub use batch::*; -pub use client::BaseRegistryClient; +pub use client::{BRegAccessReason, BaseRegistryClient}; pub use config::BaseRegistryClientConfig; pub use error::{ BRegConstraintViolation, BRegProblemCode, BRegProblemFieldPath, BRegProtocolFailure, diff --git a/crates/registry-breg-client/src/query.rs b/crates/registry-breg-client/src/query.rs index ca392aaede..477e7bd2b2 100644 --- a/crates/registry-breg-client/src/query.rs +++ b/crates/registry-breg-client/src/query.rs @@ -454,7 +454,6 @@ pub struct BRegContinuationProjection { /// Logical Base Registry Engine record route segment. pub route: String, /// Opaque Base Registry Engine `cursor`. - #[serde(alias = "skiptoken")] pub cursor: String, /// Representation selected for the original page. pub format: BRegRecordFormat, @@ -1222,10 +1221,7 @@ mod tests { let fields = legacy.as_object_mut().unwrap(); let cursor = fields.remove("cursor").unwrap(); fields.insert("skiptoken".to_owned(), cursor.clone()); - assert_eq!( - serde_json::from_value::(legacy.clone()).unwrap(), - continuation - ); + assert!(serde_json::from_value::(legacy.clone()).is_err()); legacy["cursor"] = cursor; assert!(serde_json::from_value::(legacy).is_err()); } diff --git a/crates/registry-breg-client/tests/action_recovery_registry_revision.rs b/crates/registry-breg-client/tests/action_recovery_registry_revision.rs index f3115f8689..a65fb67376 100644 --- a/crates/registry-breg-client/tests/action_recovery_registry_revision.rs +++ b/crates/registry-breg-client/tests/action_recovery_registry_revision.rs @@ -16,8 +16,9 @@ use axum::http::{Request, Response, StatusCode}; use axum::routing::any; use axum::Router; use registry_breg_client::{ - BRegActionInvocationRequest, BRegIdempotencyKey, BaseRegistryClient, BaseRegistryClientConfig, - BaseRegistryClientError, + BRegActionAvailabilityRequest, BRegActionInvocationRequest, BRegActionTargetConditionsRequest, + BRegIdempotencyKey, BRegPreparedAction, BRegProtocolFailure, BaseRegistryClient, + BaseRegistryClientConfig, BaseRegistryClientError, }; use registry_platform_httputil::client::{BearerToken, TokenError, TokenProvider}; use serde_json::{json, Map, Value}; @@ -72,23 +73,31 @@ impl TokenProvider for StaticToken { #[derive(Clone)] struct MockState { - responses: Arc>>, + responses: Arc>>, served: Arc, } -async fn handler(State(state): State, _request: Request) -> Response { +async fn handler(State(state): State, request: Request) -> Response { state.served.fetch_add(1, Ordering::SeqCst); let body = state .responses .lock() .expect("response queue lock") .pop_front() - .expect("a queued metadata response"); - let mut response = Response::new(Body::from(serde_json::to_vec(&body).expect("body"))); + .expect("a queued response"); + let mut response = Response::new(Body::from(body)); *response.status_mut() = StatusCode::OK; response .headers_mut() .insert("content-type", "application/json".parse().expect("header")); + if request.method() == axum::http::Method::POST { + response + .headers_mut() + .insert("cache-control", "no-store".parse().expect("header")); + response + .headers_mut() + .insert("vary", "authorization, accept".parse().expect("header")); + } response .headers_mut() .insert("traceparent", TRACEPARENT.parse().expect("header")); @@ -107,7 +116,7 @@ async fn caller_metadata_vocabulary_codes_prepare_and_recover_exactly() { }); let served = Arc::new(AtomicUsize::new(0)); let state = MockState { - responses: Arc::new(Mutex::new(VecDeque::from([metadata]))), + responses: Arc::new(Mutex::new(VecDeque::from([metadata.to_string()]))), served: served.clone(), }; let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); @@ -174,8 +183,8 @@ async fn saved_command_refuses_after_registry_revision_change() { let served = Arc::new(AtomicUsize::new(0)); let state = MockState { responses: Arc::new(Mutex::new(VecDeque::from([ - action_metadata(REVISION_A), - action_metadata(REVISION_B), + action_metadata(REVISION_A).to_string(), + action_metadata(REVISION_B).to_string(), ]))), served: served.clone(), }; @@ -255,3 +264,197 @@ async fn saved_command_refuses_after_registry_revision_change() { "prepare and recover perform no exchange" ); } + +#[tokio::test] +async fn action_responses_admit_additions_with_exact_bindings() { + let mut metadata = action_metadata(REVISION_A); + let action = &mut metadata["actions"][0]; + action["inputs"][0]["schema"] = json!({"type":"string","format":"uuid"}); + action["inputs"][0]["fieldType"] = + json!({"type":"reference","target":"incorporation","onDelete":"restrict"}); + action["referenceInputs"] = + json!([{"input":"reference","apiName":"reference","targetRecordType":"incorporation"}]); + action["requiredConditionKeys"] = json!(["reference"]); + for route in ["target-conditions", "availability"] { + let path = format!("/v1/actions/incorporate-company/{route}"); + let key = if route == "availability" { + "availability" + } else { + action["conditionRoute"] = json!(path); + "targetConditions" + }; + action["routes"][key] = json!({ + "method": "POST", "path": path, + "operationId": format!("actions.incorporate-company.{route}"), + "requiresIdempotencyKey": false, + "inputSchema": format!("action-incorporate-company-{route}-input"), + "responseSchema": format!("action-incorporate-company-{route}-response") + }); + } + + let invalid_availability = [ + r#"{"availability":{"available":true}}"#, + r#"{"availability":{"available":true,"observedRevision":3,"reason":"not-disclosed"}}"#, + r#"{"availability":{"available":true,"observedRevision":3,"extra":{"x":1,"x":2}}}"#, + ]; + let invalid_conditions = [ + r#"{"preconditions":{"reference":{"extra":true}}}"#, + r#"{"preconditions":{"reference":{"ifMatch":"W/\"r3\""}}}"#, + r#"{"preconditions":{"reference":{"ifMatch":"\"r3\""},"extra":{"ifMatch":"\"r3\""}}}"#, + r#"{"preconditions":{"reference":{"ifMatch":"\"r3\"","ifMatch":"\"r3\""}}}"#, + ]; + let invalid_receipts = [ + r#"{"action":"incorporate-company","applicationId":"00000000-0000-4000-8000-000000000010","results":{"record-incorporation":{"recordType":"incorporation","recordId":"00000000-0000-4000-8000-000000000001"}}}"#, + r#"{"action":"incorporate-company","applicationId":"00000000-0000-4000-8000-000000000010","results":{"record-incorporation":{"recordType":"other","recordId":"00000000-0000-4000-8000-000000000001","revision":4}}}"#, + r#"{"action":"incorporate-company","applicationId":"00000000-0000-4000-8000-000000000010","results":{"extra":{"recordType":"incorporation","recordId":"00000000-0000-4000-8000-000000000001","revision":4}}}"#, + r#"{"action":"incorporate-company","applicationId":"00000000-0000-4000-8000-000000000010","results":{"record-incorporation":{"recordType":"incorporation","recordId":"00000000-0000-4000-8000-000000000001","revision":4,"revision":4}}}"#, + ]; + let availability = + r#"{"availability":{"available":true,"observedRevision":3,"extra":true},"extra":{}}"#; + let conditions = + r#"{"preconditions":{"reference":{"ifMatch":"\"r3\"","extra":true}},"extra":{}}"#; + let receipt = r#"{"action":"incorporate-company","applicationId":"00000000-0000-4000-8000-000000000010","results":{"record-incorporation":{"recordType":"incorporation","recordId":"00000000-0000-4000-8000-000000000001","revision":4,"extra":true}},"extra":{}}"#; + let responses = [metadata.to_string()] + .into_iter() + .chain( + invalid_availability + .into_iter() + .chain([availability]) + .chain(invalid_conditions) + .chain([conditions]) + .chain(invalid_receipts) + .chain([receipt]) + .map(str::to_owned), + ) + .collect(); + let state = MockState { + responses: Arc::new(Mutex::new(responses)), + served: Arc::new(AtomicUsize::new(0)), + }; + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = listener.local_addr().unwrap(); + let router = Router::new() + .fallback(any(handler)) + .with_state(state.clone()); + let server = tokio::spawn(async move { axum::serve(listener, router).await.unwrap() }); + let client = BaseRegistryClient::new( + BaseRegistryClientConfig::new_without_peer_policy( + format!("http://{address}/").parse().unwrap(), + ) + .with_token_provider(Arc::new(StaticToken(AtomicUsize::new(0)))) + .with_maximum_mutation_retries(0), + ) + .unwrap(); + let action = client + .registry_contract(Some("preparer")) + .await + .unwrap() + .value + .select_action("incorporate-company", "preparer") + .unwrap(); + let inputs = Map::from_iter([( + "reference".to_owned(), + json!("00000000-0000-4000-8000-000000000001"), + )]); + + let request = BRegActionAvailabilityRequest::new(&action, "reference", inputs.clone()).unwrap(); + for _ in invalid_availability { + let error = client + .action_availability(&action, &request) + .await + .err() + .unwrap(); + assert_action_body_error(error); + } + let availability = client + .action_availability(&action, &request) + .await + .expect("additive availability") + .value; + assert_eq!(availability.available(), Some(true)); + assert_eq!(availability.observed_revision(), Some(3)); + + let request = BRegActionTargetConditionsRequest::new(&action, inputs.clone()).unwrap(); + for _ in invalid_conditions { + let error = client + .action_target_conditions(&action, &request) + .await + .err() + .unwrap(); + assert_action_body_error(error); + } + let conditions = client + .action_target_conditions(&action, &request) + .await + .expect("additive target conditions") + .value; + assert_eq!( + serde_json::to_value(&conditions).unwrap(), + json!({"preconditions":{"reference":{"ifMatch":"\"r3\""}}}) + ); + let other_inputs = Map::from_iter([( + "reference".to_owned(), + json!("00000000-0000-4000-8000-000000000002"), + )]); + assert!(BRegActionInvocationRequest::new(&action, other_inputs, Some(&conditions)).is_err()); + + let request = + BRegActionInvocationRequest::new(&action, inputs.clone(), Some(&conditions)).unwrap(); + let key = BRegIdempotencyKey::parse("incorporate-1").unwrap(); + + // A caller-held prepared command still requires the exact canonical body. + let prepared = client.prepare_action(&action, &request, &key).unwrap(); + let mut saved: Value = serde_json::from_slice(prepared.as_bytes()).unwrap(); + let body = saved["body"].as_str().unwrap(); + let extended = body.replace( + r#"{"ifMatch":"\"r3\""}"#, + r#"{"ifMatch":"\"r3\"","extra":true}"#, + ); + assert_ne!(extended, body); + saved["body"] = json!(extended); + let saved = BRegPreparedAction::from_slice(&serde_json::to_vec(&saved).unwrap()).unwrap(); + assert!(client + .recover_action(&action, &saved, &inputs, &key) + .is_err()); + + for _ in invalid_receipts { + let error = client + .invoke_action(&action, &request, &key) + .await + .err() + .unwrap(); + assert!(error.is_outcome_unknown()); + assert_action_body_error(error); + } + let receipt = client + .invoke_action(&action, &request, &key) + .await + .expect("additive receipt") + .value; + let result = &receipt.results()["record-incorporation"]; + assert_eq!(result.revision(), 4); + assert_eq!( + result.record_identifier().to_string(), + inputs["reference"].as_str().unwrap() + ); + assert_eq!( + receipt.application_identifier().to_string(), + "00000000-0000-4000-8000-000000000010" + ); + assert!(state.responses.lock().unwrap().is_empty()); + server.abort(); +} + +fn assert_action_body_error(error: BaseRegistryClientError) { + assert!( + matches!( + error, + BaseRegistryClientError::Protocol { + status: 200, + failure: BRegProtocolFailure::Body, + .. + } + ), + "{error}" + ); +} diff --git a/crates/registry-breg-client/tests/write_http_boundary.rs b/crates/registry-breg-client/tests/write_http_boundary.rs index 2371d821b2..5407677c45 100644 --- a/crates/registry-breg-client/tests/write_http_boundary.rs +++ b/crates/registry-breg-client/tests/write_http_boundary.rs @@ -10,14 +10,15 @@ use axum::extract::State; use axum::http::{HeaderName, HeaderValue, Request, Response, StatusCode}; use axum::routing::any; use axum::Router; +use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _}; use registry_breg_client::{ - ingestion_chunk_digest, ingestion_prefix_digest, BRegActionAvailabilityRequest, - BRegActionError, BRegActionInvocationRequest, BRegBatchBuilder, BRegBatchError, - BRegBatchOperation, BRegCreateRequest, BRegDirectWrite, BRegEtag, BRegIdempotencyKey, - BRegIngestionChunk, BRegIngestionRunListQuery, BRegIngestionRunRequest, BRegIngestionRunStatus, - BRegMetadataErrorKind, BRegMetadataSelectionErrorKind, BRegPatchRequest, BRegProblemCode, - BRegProblemFieldPath, BRegProtocolFailure, BRegRecordFormat, BRegRefusalCode, - BaseRegistryClient, BaseRegistryClientConfig, BaseRegistryClientError, + ingestion_chunk_digest, ingestion_prefix_digest, BRegAccessReason, + BRegActionAvailabilityRequest, BRegActionError, BRegActionInvocationRequest, BRegBatchBuilder, + BRegBatchError, BRegBatchOperation, BRegCreateRequest, BRegDirectWrite, BRegEtag, + BRegIdempotencyKey, BRegIngestionChunk, BRegIngestionRunListQuery, BRegIngestionRunRequest, + BRegIngestionRunStatus, BRegMetadataErrorKind, BRegMetadataSelectionErrorKind, + BRegPatchRequest, BRegProblemCode, BRegProblemFieldPath, BRegProtocolFailure, BRegRecordFormat, + BRegRefusalCode, BaseRegistryClient, BaseRegistryClientConfig, BaseRegistryClientError, BREG_INGESTION_CHUNK_ALGORITHM_VERSION, REGISTRY_RECORD_CONTEXT_IDENTIFIER, }; use registry_platform_httputil::client::{ @@ -52,6 +53,7 @@ struct CapturedRequest { content_type: Option, idempotency_key: Option, if_match: Option, + access_reasons: Vec, body: Vec, } @@ -101,6 +103,12 @@ async fn handler(State(state): State, request: Request) -> Resp content_type: header(&request, "content-type"), idempotency_key: header(&request, "idempotency-key"), if_match: header(&request, "if-match"), + access_reasons: request + .headers() + .get_all("registry-access-reason") + .iter() + .map(|value| value.to_str().unwrap().to_owned()) + .collect(), body: to_bytes(request.into_body(), 3 * 1024 * 1024) .await .expect("bounded request body") @@ -2461,6 +2469,7 @@ async fn a_batch_with_an_unknown_outcome_is_resent_byte_identically_under_the_sa metadata_fixture_with_create_batch(), )) .chain(unavailable_sends()) + .chain(unavailable_sends()) .collect(), ) .await; @@ -2478,20 +2487,39 @@ async fn a_batch_with_an_unknown_outcome_is_resent_byte_identically_under_the_sa .expect("a permitted Create item") .build() .expect("a bounded batch"); + let reason = BRegAccessReason::new("Synthetic Batch review é").unwrap(); + let encoded = URL_SAFE_NO_PAD.encode("Synthetic Batch review é"); let error = fixture .client - .batch_records(&binding, &request, &key("batch-resend-1")) + .batch_records_with_access_reason(&binding, &request, &key("batch-resend-1"), Some(&reason)) .await .expect_err("no send settles the batch"); assert!(error.is_outcome_unknown()); + let error = fixture + .client + .batch_records(&binding, &request, &key("batch-resend-2")) + .await + .expect_err("the later call also has an unknown outcome"); + assert!(error.is_outcome_unknown()); + let requests = fixture.requests.lock().unwrap(); assert_eq!(requests[1].method, "POST"); assert_eq!( requests[1].uri, "/tenant/base/v1/records/companies:batch?accessProfile=company-writer" ); - assert_resent_identically(&requests[1..], "batch-resend-1"); + let after_explicit = 2 + DEFAULT_MUTATION_RETRIES as usize; + let explicit = &requests[1..after_explicit]; + assert_resent_identically(explicit, "batch-resend-1"); + assert!(explicit + .iter() + .all(|send| send.access_reasons == [encoded.as_str()])); + let absent = &requests[after_explicit..]; + assert_resent_identically(absent, "batch-resend-2"); + assert!(absent.iter().all(|send| send.access_reasons.is_empty())); + assert_eq!(explicit[0].body, absent[0].body); + assert_eq!(explicit[0].uri, absent[0].uri); } #[tokio::test] @@ -3196,6 +3224,31 @@ fn ingestion_announcement(profile: &str) -> BRegIngestionRunRequest { .unwrap() } +#[test] +fn access_reason_validates_decoded_bytes_without_disclosing_the_value() { + for invalid in [ + "", + " ", + "private\ncanary", + "private\u{0085}canary", + &"é".repeat(257), + ] { + let Err(error) = BRegAccessReason::new(invalid) else { + panic!("invalid access reason was accepted"); + }; + assert_eq!(error.kind(), "invalid-request"); + assert!(!format!("{error:?} {error}").contains("private")); + if !invalid.is_empty() { + assert!(!format!("{error:?} {error}").contains(&URL_SAFE_NO_PAD.encode(invalid))); + } + } + let plaintext = "é".repeat(256); + let reason = BRegAccessReason::new(&plaintext).unwrap(); + let debug = format!("{reason:?}"); + assert!(!debug.contains(&plaintext)); + assert!(!debug.contains(&URL_SAFE_NO_PAD.encode(plaintext))); +} + #[tokio::test] async fn ingestion_exchanges_select_the_announced_run_access_profile() { let page = json!({"runs": [], "hasMore": false, "nextCursor": null}); @@ -3220,8 +3273,15 @@ async fn ingestion_exchanges_select_the_announced_run_access_profile() { ]) .await; let client = &fixture.client; + let plaintext = " Synthetic review é "; + let encoded = URL_SAFE_NO_PAD.encode(plaintext); + let reason = BRegAccessReason::new(plaintext).unwrap(); let run_id = client - .create_ingestion_run("company", &ingestion_announcement(INGESTION_PROFILE)) + .create_ingestion_run_with_access_reason( + "company", + &ingestion_announcement(INGESTION_PROFILE), + Some(&reason), + ) .await .unwrap() .value @@ -3233,15 +3293,32 @@ async fn ingestion_exchanges_select_the_announced_run_access_profile() { ) .unwrap(); client - .submit_ingestion_chunk("company", run_id, &chunk, INGESTION_PROFILE) + .submit_ingestion_chunk_with_access_reason( + "company", + run_id, + &chunk, + INGESTION_PROFILE, + Some(&reason), + ) .await .unwrap(); client - .ingestion_chunk_receipt("company", run_id, 0, INGESTION_PROFILE) + .ingestion_chunk_receipt_with_access_reason( + "company", + run_id, + 0, + INGESTION_PROFILE, + Some(&reason), + ) .await .unwrap(); client - .read_ingestion_run("company", run_id, Some(INGESTION_PROFILE)) + .read_ingestion_run_with_access_reason( + "company", + run_id, + Some(INGESTION_PROFILE), + Some(&reason), + ) .await .unwrap(); client @@ -3249,7 +3326,12 @@ async fn ingestion_exchanges_select_the_announced_run_access_profile() { .await .unwrap(); client - .cancel_ingestion_run("company", run_id, Some(INGESTION_PROFILE)) + .cancel_ingestion_run_with_access_reason( + "company", + run_id, + Some(INGESTION_PROFILE), + Some(&reason), + ) .await .unwrap(); let queried = BRegIngestionRunListQuery::default() @@ -3259,7 +3341,7 @@ async fn ingestion_exchanges_select_the_announced_run_access_profile() { .unwrap() .status(BRegIngestionRunStatus::Open); client - .list_ingestion_runs("company", &queried) + .list_ingestion_runs_with_access_reason("company", &queried, Some(&reason)) .await .unwrap(); client @@ -3281,7 +3363,16 @@ async fn ingestion_exchanges_select_the_announced_run_access_profile() { "/tenant/base/v1/records/company/ingestion-runs?accessProfile=importer.v1&limit=25&status=open".to_owned(), "/tenant/base/v1/records/company/ingestion-runs".to_owned(), ]; - for (request, uri) in requests.iter().zip(expected) { + for (index, (request, uri)) in requests.iter().zip(expected).enumerate() { + let expected_reasons = if [4, 7].contains(&index) { + Vec::new() + } else { + vec![encoded.clone()] + }; + assert_eq!(request.access_reasons, expected_reasons); + for canary in [plaintext, &encoded] { + assert!(!String::from_utf8_lossy(&request.body).contains(canary)); + } assert_eq!(request.uri, uri); } assert_eq!(requests[0].method, "POST"); diff --git a/crates/registry-breg-mcp/clippy.toml b/crates/registry-breg-mcp/clippy.toml index bc14afcc6b..72e2b4cb8f 100644 --- a/crates/registry-breg-mcp/clippy.toml +++ b/crates/registry-breg-mcp/clippy.toml @@ -47,13 +47,17 @@ disallowed-methods = [ { path = "registry_breg_client::BaseRegistryClient::patch_record", reason = "the gateway edits Proposals and offers no Record mutation" }, { path = "registry_breg_client::BaseRegistryClient::tombstone_record", reason = "the gateway offers no tombstone" }, { path = "registry_breg_client::BaseRegistryClient::batch_records", reason = "the gateway offers no batch write" }, + { path = "registry_breg_client::BaseRegistryClient::batch_records_with_access_reason", reason = "the gateway offers no batch write" }, { path = "registry_breg_client::BaseRegistryClient::action_target_conditions", reason = "the gateway offers no governed action" }, { path = "registry_breg_client::BaseRegistryClient::invoke_action", reason = "the gateway offers no governed action" }, { path = "registry_breg_client::BaseRegistryClient::upload_proposal_attachment", reason = "the gateway offers no attachment upload" }, { path = "registry_breg_client::BaseRegistryClient::delete_proposal_attachment", reason = "the gateway offers no attachment removal" }, { path = "registry_breg_client::BaseRegistryClient::create_ingestion_run", reason = "the gateway offers no ingestion" }, + { path = "registry_breg_client::BaseRegistryClient::create_ingestion_run_with_access_reason", reason = "the gateway offers no ingestion" }, { path = "registry_breg_client::BaseRegistryClient::submit_ingestion_chunk", reason = "the gateway offers no ingestion" }, + { path = "registry_breg_client::BaseRegistryClient::submit_ingestion_chunk_with_access_reason", reason = "the gateway offers no ingestion" }, { path = "registry_breg_client::BaseRegistryClient::cancel_ingestion_run", reason = "the gateway offers no ingestion" }, + { path = "registry_breg_client::BaseRegistryClient::cancel_ingestion_run_with_access_reason", reason = "the gateway offers no ingestion" }, { path = "registry_breg_client::BaseRegistryClient::statistics_publish", reason = "the gateway offers no statistical release publication" }, { path = "registry_breg_client::BaseRegistryClient::statistics_withdraw", reason = "the gateway offers no statistical release withdrawal" }, diff --git a/crates/registry-breg/src/api/external_views.rs b/crates/registry-breg/src/api/external_views.rs index 05b4610a7d..0ae6a6409e 100644 --- a/crates/registry-breg/src/api/external_views.rs +++ b/crates/registry-breg/src/api/external_views.rs @@ -564,7 +564,15 @@ async fn handle( } else { Operation::List }; - let profile_selection = admission_profile(raw.as_deref()); + let retired_paging = has_retired_page_parameter(raw.as_deref()); + let profile_selection = if retired_paging { + match retired_page_admission_profile(raw.as_deref()) { + Ok(selection) => selection, + Err(_) => return concealed(FailedCheck::AccessProfile), + } + } else { + admission_profile(raw.as_deref()) + }; let context = match root_context( service, view, @@ -612,6 +620,9 @@ async fn handle( }, None => None, }; + if retired_paging { + return invalid_query_at("query"); + } let options = match QueryOptions::parse(raw.as_deref(), true) { Ok(value) => value, Err(error) => return error.problem(), diff --git a/crates/registry-breg/src/api/gis.rs b/crates/registry-breg/src/api/gis.rs index e8566a4117..663f5bbbea 100644 --- a/crates/registry-breg/src/api/gis.rs +++ b/crates/registry-breg/src/api/gis.rs @@ -19,10 +19,10 @@ use serde_json::{json, Map, Value}; use super::{ audited_read_concealment, audited_read_refusal, authorize_route_with_reason, concealed, - data_field_type, exact_non_record_no_store, invalid_query, percent_decode, - profile_not_authorized, read_query, unavailable, Authenticated, AuthorizedSurface, HttpService, - QueryOptions, QueryParseError, ReadQueryError, RecordReadKind, RecordReadRequest, - VerifiedRequestClaims, MAX_RAW_QUERY_BYTES, + data_field_type, exact_non_record_no_store, has_retired_page_parameter, invalid_query, + percent_decode, profile_not_authorized, read_query, unavailable, Authenticated, + AuthorizedSurface, HttpService, QueryOptions, QueryParseError, ReadQueryError, RecordReadKind, + RecordReadRequest, VerifiedRequestClaims, MAX_RAW_QUERY_BYTES, }; use crate::audit::ReadRefusalReason; use crate::contract::{FieldTypeSource, Operation}; @@ -304,17 +304,16 @@ async fn items( ) .await; } - // The feature surface speaks its own parameter names, so a refusal here - // stays unlocated rather than naming a native query parameter. + // GIS query errors use the feature surface's parameter contract. let query = match parse_items_query(raw_query.as_deref()) { Ok(query) => query, - Err(QueryParseError::Invalid | QueryParseError::InvalidAt(_)) => { + Err(error) => { return audited_read_refusal( &service, authorized.route, &authorized.surface, None, - invalid_query(), + error.problem(), &correlation, ) .await; @@ -760,6 +759,9 @@ fn parse_items_query(raw: Option<&str>) -> Result MAX_RAW_QUERY_BYTES { return Err(QueryParseError::Invalid); } + if has_retired_page_parameter(Some(raw)) { + return Err(QueryParseError::InvalidAt("query")); + } let pairs = decode_query_pairs(raw)?; let mut seen = BTreeSet::new(); let mut query = GisItemsQuery::default(); @@ -947,9 +949,16 @@ mod tests { assert_eq!(query.limit, Some(1000)); assert_eq!(query.cursor, None); - for raw in ["%24top=2", "%24skiptoken=opaque", "limit=2&limit=2"] { - assert_eq!(parse_items_query(Some(raw)), Err(QueryParseError::Invalid)); + for raw in ["%24top=2", "%24skiptoken=opaque"] { + assert_eq!( + parse_items_query(Some(raw)), + Err(QueryParseError::InvalidAt("query")) + ); } + assert_eq!( + parse_items_query(Some("limit=2&limit=2")), + Err(QueryParseError::Invalid) + ); assert_eq!( parse_items_query(Some("cursor=opaque&bbox=100,13,101,14")), Err(QueryParseError::Invalid) diff --git a/crates/registry-breg/src/api/mod.rs b/crates/registry-breg/src/api/mod.rs index 0a793c8d39..704ed7d13f 100644 --- a/crates/registry-breg/src/api/mod.rs +++ b/crates/registry-breg/src/api/mod.rs @@ -1009,8 +1009,26 @@ async fn read_dispatch( headers: HeaderMap, Path(path): Path>, ) -> Response { - let options = match QueryOptions::parse(raw_query.as_deref(), true) { + let retired_paging = has_retired_page_parameter(raw_query.as_deref()); + let parsed = if retired_paging { + QueryOptions::for_admission(raw_query.as_deref()) + } else { + QueryOptions::parse(raw_query.as_deref(), true) + }; + let options = match parsed { Ok(options) => options, + Err(_) if retired_paging => { + return audited_read_concealment( + &service, + &route, + &QueryOptions::default(), + &claims, + path.get("record_id"), + &correlation, + RouteRefusal::admission_check(FailedCheck::AccessProfile), + ) + .await; + } Err(error) => { return audited_known_read_refusal( &service, @@ -1129,6 +1147,17 @@ async fn read_dispatch( ) .await; } + if retired_paging { + return audited_read_refusal( + &service, + &route, + &surface, + Some(record_id), + invalid_query_at("query"), + &correlation, + ) + .await; + } let request = RecordReadRequest { entity_id: route.entity_id.clone(), operation_id: route.id.clone(), @@ -1175,6 +1204,24 @@ async fn read_dispatch( ) .await; } + if retired_paging { + let response = if representation == CursorRepresentation::GeoJson + && !geojson_available(&surface) + { + profile_not_authorized(FailedCheck::Disclosure) + } else { + invalid_query_at("query") + }; + return audited_read_refusal( + &service, + &route, + &surface, + path.get("record_id"), + response, + &correlation, + ) + .await; + } let query = match read_query( &service, &route, @@ -1298,8 +1345,26 @@ async fn lookup_dispatch( headers: HeaderMap, body: Body, ) -> Response { - let options = match QueryOptions::parse(raw_query.as_deref(), true) { + let retired_paging = has_retired_page_parameter(raw_query.as_deref()); + let parsed = if retired_paging { + QueryOptions::for_admission(raw_query.as_deref()) + } else { + QueryOptions::parse(raw_query.as_deref(), true) + }; + let options = match parsed { Ok(options) => options, + Err(_) if retired_paging => { + return audited_read_concealment( + &service, + &route, + &QueryOptions::default(), + &claims, + None, + &correlation, + RouteRefusal::admission_check(FailedCheck::AccessProfile), + ) + .await; + } Err(error) => { return audited_known_read_refusal( &service, @@ -1347,6 +1412,17 @@ async fn lookup_dispatch( if let Some(refusal) = field_encryption_refusal(&service, surface.entity) { return refusal; } + if retired_paging { + return audited_read_refusal( + &service, + &route, + &surface, + None, + invalid_query_at("query"), + &correlation, + ) + .await; + } if surface.read_path.is_some() || options.has_non_projection_query_members() { return audited_read_refusal( &service, @@ -1731,7 +1807,13 @@ async fn snapshot_dispatch( let Some(snapshots) = &service.snapshots else { return concealed(FailedCheck::Visibility); }; - let options = match QueryOptions::parse_snapshot(raw_query.as_deref()) { + let retired_paging = has_retired_page_parameter(raw_query.as_deref()); + let parsed = if retired_paging { + QueryOptions::for_admission(raw_query.as_deref()) + } else { + QueryOptions::parse_snapshot(raw_query.as_deref()) + }; + let options = match parsed { Ok(options) => options, Err(_) => { return audited_known_read_refusal( @@ -1780,6 +1862,17 @@ async fn snapshot_dispatch( if let Some(refusal) = field_encryption_refusal(&service, surface.entity) { return refusal; } + if retired_paging { + return audited_read_refusal( + &service, + &route, + &surface, + None, + invalid_query_at("query"), + &correlation, + ) + .await; + } let query = match read_query( &service, &route, @@ -5267,6 +5360,12 @@ struct HistoricalQueryOptions { } impl QueryOptions { + fn for_admission(raw: Option<&str>) -> Result { + let mut options = Self::default(); + options.parsed.access_profile = retired_page_admission_profile(raw)?; + Ok(options) + } + fn parse(raw: Option<&str>, allow_read_query: bool) -> Result { let Some(raw) = raw else { return Ok(Self::default()); @@ -5478,6 +5577,44 @@ impl ReadQueryError { } } +/// Detect retired page names independently of other query faults. Ignore +/// values here so aliases remain identifiable alongside malformed input. +fn has_retired_page_parameter(raw: Option<&str>) -> bool { + raw.filter(|raw| raw.len() <= MAX_RAW_QUERY_BYTES) + .is_some_and(|raw| { + raw.split('&').any(|pair| { + let name = pair.split_once('=').map_or(pair, |(name, _)| name); + matches!( + percent_decode(name).ok().as_deref(), + Some("$top" | "$skiptoken") + ) + }) + }) +} + +/// Read the explicit selector without allowing a malformed or repeated +/// selector to fall back to default profile selection. +fn retired_page_admission_profile(raw: Option<&str>) -> Result, QueryParseError> { + let Some(raw) = raw else { return Ok(None) }; + if raw.len() > MAX_RAW_QUERY_BYTES { + return Err(QueryParseError::Invalid); + } + let mut selected = None; + for pair in raw.split('&') { + let (name, value) = pair + .split_once('=') + .map_or((pair, None), |(name, value)| (name, Some(value))); + if percent_decode(name).ok().as_deref() != Some("accessProfile") { + continue; + } + let value = percent_decode(value.ok_or(QueryParseError::Invalid)?)?; + if !strict_query::valid_config_identifier(&value) || selected.replace(value).is_some() { + return Err(QueryParseError::Invalid); + } + } + Ok(selected) +} + /// Extract only the selector needed for admission. Full validation follows /// authorization, so malformed options cannot reveal an inaccessible target. fn admission_profile(raw: Option<&str>) -> Option { diff --git a/crates/registry-breg/src/api/proposals.rs b/crates/registry-breg/src/api/proposals.rs index 3bef869d84..e5fb636dd3 100644 --- a/crates/registry-breg/src/api/proposals.rs +++ b/crates/registry-breg/src/api/proposals.rs @@ -2318,7 +2318,7 @@ pub(super) async fn list( let Some(mutations) = &service.mutations else { return concealed(FailedCheck::Visibility); }; - let selected = match proposal_list_admission_profile(raw_query.as_deref()) { + let selected = match proposal_admission_profile(raw_query.as_deref()) { Ok(selected) => selected, Err(()) => { return audited_list_concealment( @@ -2400,7 +2400,7 @@ pub(super) async fn list( Ok(query) => query, Err(QueryParseError::InvalidAt("top")) => { return invalid_query_at_with_detail( - "top", + "query", "The Proposal list takes `limit` for its page size; `top` is not accepted.", ); } @@ -2416,7 +2416,7 @@ pub(super) async fn list( } } -fn proposal_list_admission_profile(raw: Option<&str>) -> Result, ()> { +fn proposal_admission_profile(raw: Option<&str>) -> Result, ()> { let Some(raw) = raw else { return Ok(None) }; if raw.len() > MAX_RAW_QUERY_BYTES { return Err(()); @@ -2454,7 +2454,6 @@ fn proposal_list_parameter(name: &str) -> Option<&'static str> { "target" => Some("target"), "cursor" => Some("cursor"), "limit" => Some("limit"), - "top" => Some("top"), _ => None, } } @@ -2476,6 +2475,9 @@ fn parse_proposal_list_query(raw: Option<&str>) -> Result) -> Result return Err(QueryParseError::InvalidAt("top")), _ if proposal_list_parameter(&name).is_some() => { return Err(proposal_list_error(&name)); } diff --git a/crates/registry-breg/src/api/proposals/answers.rs b/crates/registry-breg/src/api/proposals/answers.rs index b74db5166f..80317f10c1 100644 --- a/crates/registry-breg/src/api/proposals/answers.rs +++ b/crates/registry-breg/src/api/proposals/answers.rs @@ -58,12 +58,21 @@ pub(in crate::api) async fn answer( .await .map_err(|_| invalid_request())?; let value = parse_json_strict(&bytes).map_err(|_| invalid_request())?; - if value.get("text").is_some_and(Value::is_null) { - return Err(proposal_problem(MutationError::InvalidRequestAt( - crate::problem_location::RequestLocation::proposal_answer_text(), - ))); + if value.get("text").is_some_and(|text| !text.is_string()) { + return Err(invalid_request_at( + &crate::problem_location::RequestLocation::proposal_answer_text(), + )); } - let answer: AnswerBody = serde_json::from_value(value).map_err(|_| invalid_request())?; + let answer: AnswerBody = serde_path_to_error::deserialize(value).map_err(|error| { + match error.path().iter().next() { + Some(serde_path_to_error::Segment::Map { key }) if key == "formEntries" => { + invalid_request_at( + &crate::problem_location::RequestLocation::proposal_answer_form_entries(), + ) + } + _ => invalid_request(), + } + })?; Ok((key, etag, answer)) } .await; diff --git a/crates/registry-breg/src/api/proposals/forms.rs b/crates/registry-breg/src/api/proposals/forms.rs index 2edcc7f470..7c0627340f 100644 --- a/crates/registry-breg/src/api/proposals/forms.rs +++ b/crates/registry-breg/src/api/proposals/forms.rs @@ -82,6 +82,11 @@ pub(in crate::api) async fn add_form( .await .map_err(|_| invalid_request())?; let value = parse_json_strict(&bytes).map_err(|_| invalid_request())?; + if !value.get("input").is_some_and(Value::is_object) { + return Err(invalid_request_at( + &crate::problem_location::RequestLocation::input(), + )); + } let body: AddFormBody = serde_json::from_value(value).map_err(|_| invalid_request())?; Ok((key, etag, body.input)) } diff --git a/crates/registry-breg/src/api/proposals/messages.rs b/crates/registry-breg/src/api/proposals/messages.rs index 84e471e037..0fb53208fe 100644 --- a/crates/registry-breg/src/api/proposals/messages.rs +++ b/crates/registry-breg/src/api/proposals/messages.rs @@ -10,7 +10,7 @@ async fn admit( service: &HttpService, id: &str, claims: &VerifiedRequestClaims, - raw: Option<&str>, + selected: Result, ()>, method: HttpMethod, correlation: &RequestCorrelation, ) -> Result<(Uuid, CompiledAction, ProposalAuthority), Response> { @@ -21,7 +21,7 @@ async fn admit( Ok(id) if !id.is_nil() => id, _ => return Err(concealed(FailedCheck::Visibility)), }; - let selected = selected_profile(raw).map_err(|_| concealed(FailedCheck::Visibility))?; + let selected = selected.map_err(|_| concealed(FailedCheck::Visibility))?; let (action, authority) = authorize_target( service, mutations, @@ -109,7 +109,7 @@ pub(in crate::api) async fn write( &service, &id, &claims, - raw_query.as_deref(), + selected_profile(raw_query.as_deref()), HttpMethod::Post, &correlation, ) @@ -136,7 +136,7 @@ pub(in crate::api) async fn write( .map_err(|_| invalid_request())?; let value = parse_json_strict(&bytes).map_err(|_| invalid_request())?; let text = match value.as_object() { - Some(object) if object.len() == 1 => object.get("text"), + Some(object) if object.len() <= 1 => object.get("text"), _ => return Err(invalid_request()), }; let text = text @@ -205,31 +205,11 @@ pub(in crate::api) async fn list( Authenticated(claims): Authenticated, RawQuery(raw_query): RawQuery, ) -> Response { - // `after` and `limit` page the thread; every other parameter selects - // the access profile as on any Proposal read. - let mut after = None; - let mut limit = None; - let mut ordinary = Vec::new(); - for pair in raw_query.as_deref().unwrap_or("").split('&') { - if pair.is_empty() { - continue; - } - let Some((name, value)) = pair.split_once('=') else { - return concealed(FailedCheck::Visibility); - }; - match name { - "after" if after.is_none() => after = Some(value.to_owned()), - "limit" if limit.is_none() => limit = Some(value.to_owned()), - "after" | "limit" => return invalid_request(), - _ => ordinary.push(pair), - } - } - let ordinary = (!ordinary.is_empty()).then(|| ordinary.join("&")); let (id, _, authority) = match admit( &service, &id, &claims, - ordinary.as_deref(), + proposal_admission_profile(raw_query.as_deref()), HttpMethod::Get, &correlation, ) @@ -241,30 +221,15 @@ pub(in crate::api) async fn list( let Some(mutations) = &service.mutations else { return concealed(FailedCheck::Visibility); }; - let before = match after.as_deref().map(str::parse::) { - None => None, - Some(Ok(position)) if position > 0 => Some(position), - Some(_) => { + let (before, limit) = match page_inputs(raw_query.as_deref()) { + Ok(page) => page, + Err(error) => { return admitted_http_refusal( mutations, &authority, HttpMethod::Get, &correlation, - fixed_problem(crate::problem::ProblemCode::QueryCursorInvalid), - ) - .await - } - }; - let limit = match limit.as_deref().map(str::parse::) { - None => crate::proposal_messages::DOCUMENT_ITEMS, - Some(Ok(limit)) if (1..=crate::proposal_messages::MAX_PAGE_ITEMS).contains(&limit) => limit, - Some(_) => { - return admitted_http_refusal( - mutations, - &authority, - HttpMethod::Get, - &correlation, - invalid_request(), + error.problem(), ) .await } @@ -280,6 +245,77 @@ pub(in crate::api) async fn list( } } +/// Parse the page inputs only after the bounded profile selection and visibility check. +fn page_inputs(raw: Option<&str>) -> Result<(Option, i64), PageError> { + let mut cursor = None; + let mut limit = None; + for pair in raw.into_iter().flat_map(|query| query.split('&')) { + let (name, value) = pair.split_once('=').ok_or(PageError::InvalidQuery)?; + let name = percent_decode(name).map_err(|_| PageError::InvalidQuery)?; + let (slot, parameter) = match name.as_str() { + "accessProfile" => continue, + "cursor" => (&mut cursor, "cursor"), + "limit" => (&mut limit, "limit"), + "after" => return Err(PageError::RetiredAfter), + _ => return Err(PageError::InvalidQuery), + }; + if slot.replace(value).is_some() { + return Err(PageError::Parameter(ProblemCode::RequestInvalid, parameter)); + } + } + let position = |value| { + percent_decode(value) + .ok() + .and_then(|value| value.parse::().ok()) + }; + let before = cursor + .map(|value| { + percent_decode(value) + .ok() + .filter(|value| matches!(value.as_bytes().first(), Some(b'1'..=b'9'))) + .and_then(|value| value.parse::().ok()) + .ok_or(PageError::Parameter( + ProblemCode::QueryCursorInvalid, + "cursor", + )) + }) + .transpose()?; + let limit = limit + .map(|value| { + position(value) + .filter(|limit| (1..=crate::proposal_messages::MAX_PAGE_ITEMS).contains(limit)) + .ok_or(PageError::Parameter(ProblemCode::RequestInvalid, "limit")) + }) + .transpose()? + .unwrap_or(crate::proposal_messages::DOCUMENT_ITEMS); + Ok((before, limit)) +} + +enum PageError { + InvalidQuery, + RetiredAfter, + Parameter(ProblemCode, &'static str), +} + +impl PageError { + fn problem(self) -> Response { + match self { + Self::InvalidQuery => invalid_query_at("query"), + Self::RetiredAfter => invalid_query_at_with_detail( + "query", + "The Proposal thread takes `cursor` for its page position; `after` is not accepted.", + ), + Self::Parameter(code, parameter) => crate::correlation::problem_response_with_field_path( + StatusCode::BAD_REQUEST, + code.title(), + code.description(), + code.code(), + parameter, + ), + } + } +} + pub(in crate::api) async fn mark_read( State(service): State>, Path(id): Path, @@ -293,7 +329,7 @@ pub(in crate::api) async fn mark_read( &service, &id, &claims, - raw_query.as_deref(), + selected_profile(raw_query.as_deref()), HttpMethod::Post, &correlation, ) @@ -314,7 +350,7 @@ pub(in crate::api) async fn mark_read( .map_err(|_| invalid_request())?; let value = parse_json_strict(&bytes).map_err(|_| invalid_request())?; match value.as_object() { - Some(object) if object.len() == 1 => object + Some(object) if object.len() <= 1 => object .get("through") .and_then(Value::as_str) .and_then(|id| Uuid::parse_str(id).ok()) diff --git a/crates/registry-breg/src/artifacts.rs b/crates/registry-breg/src/artifacts.rs index 4f882a410b..b45ac6e0ad 100644 --- a/crates/registry-breg/src/artifacts.rs +++ b/crates/registry-breg/src/artifacts.rs @@ -19,10 +19,10 @@ use crate::model::{ CompiledActionInput, CompiledActionInventory, CompiledActionRoute, CompiledEntity, CompiledEventDeliveryInventory, CompiledManifestProjection, CompiledMetadataInventory, CompiledModuleIdentity, CompiledPlanEffect, CompiledPlanMutation, CompiledPlanValue, - CompiledQueryInventory, CompiledQueryKind, CompiledQueryOperation, CompiledQueryTemporalBinding, - CompiledQueryTemporalSemantics, CompiledQueryTemporalValueKind, CompiledRecipients, - CompiledRevisionKind, CompiledRoute, CompiledRouteInventory, CompiledStatisticalDataset, - DisclosureWithhold, HttpMethod, + CompiledQueryInventory, CompiledQueryKind, CompiledQueryOperation, + CompiledQueryTemporalBinding, CompiledQueryTemporalSemantics, CompiledQueryTemporalValueKind, + CompiledRecipients, CompiledRevisionKind, CompiledRoute, CompiledRouteInventory, + CompiledStatisticalDataset, DisclosureWithhold, HttpMethod, }; use crate::physical_names::{hex_prefix, PhysicalNameInventory}; use crate::record_profile::{link_header_value, CONTEXT_IDENTIFIER, PROFILE_IDENTIFIER}; @@ -3418,6 +3418,14 @@ fn operation_parameters( json!({"type": "string", "minLength": 1, "maxLength": 256, "pattern": "^[\\x21-\\x2B\\x2D-\\x3A\\x3C-\\x7E]+$"}), "Idempotency key bound to method, route, caller, target record, package revision, request body, and response field set.", )); + if route.operation == Operation::Batch { + parameters.push(header_parameter( + "Registry-Access-Reason", + false, + json!({"type": "string", "minLength": 1, "maxLength": 684, "pattern": "^[A-Za-z0-9_-]+$"}), + "Access reason as unpadded base64url UTF-8. Supply it when the selected Batch profile requires a reason or a Batch item names a reference whose target grant requires one.", + )); + } if matches!(route.operation, Operation::Patch | Operation::Tombstone) { parameters.push(header_parameter( "If-Match", diff --git a/crates/registry-breg/src/cursor.rs b/crates/registry-breg/src/cursor.rs index 6c836f67d4..ae50cef932 100644 --- a/crates/registry-breg/src/cursor.rs +++ b/crates/registry-breg/src/cursor.rs @@ -707,7 +707,7 @@ mod tests { assert_eq!(token.len(), MAX_TOKEN_BYTES); assert_eq!(token.len(), crate::query::MAX_CURSOR_TOKEN_BYTES); assert!(codec.decode(&token, 1_001).is_ok()); - assert!(crate::query::parse_read_query([("$skiptoken", token.as_str())]).is_ok()); + assert!(crate::query::parse_read_query([("cursor", token.as_str())]).is_ok()); assert!(registry_breg_client::BRegContinuation::try_from_projection( registry_breg_client::BRegContinuationProjection { route: "assets".to_owned(), @@ -909,6 +909,13 @@ mod tests { let wire = URL_SAFE_NO_PAD.decode(token).expect("golden is base64url"); assert_eq!(wire[0], WIRE_VERSION); assert_eq!(wire[1..=NONCE_BYTES], [nonce; NONCE_BYTES]); + let query = crate::query::parse_read_query([("cursor", token)]) + .expect("preexisting cursor can be carried by the canonical parameter"); + assert!(matches!( + query.mode, + crate::query::ParsedReadQueryMode::SkipToken { token: parsed } if parsed == token + )); + assert!(crate::query::parse_read_query([("$skiptoken", token)]).is_err()); assert_eq!(codec.decode(token, 1_001).expect("golden opens"), payload()); } } diff --git a/crates/registry-breg/src/mutation/proposal/forms.rs b/crates/registry-breg/src/mutation/proposal/forms.rs index 0a45a78cbd..7a9400044d 100644 --- a/crates/registry-breg/src/mutation/proposal/forms.rs +++ b/crates/registry-breg/src/mutation/proposal/forms.rs @@ -53,15 +53,12 @@ pub(super) async fn insert( FailedCheck::AccessProfile, )); } - for key in entry.values.keys() { - if !form.inputs.iter().any(|input| &input.api_name == key) { - let path = if crate::logical_names::valid_api_name(key) { - RequestLocation::action_input(key) - } else { - return Err(MutationError::InvalidRequest); - }; - return Err(MutationError::InvalidRequestAt(path)); - } + if entry + .values + .keys() + .any(|key| !form.inputs.iter().any(|input| &input.api_name == key)) + { + return Err(MutationError::InvalidRequestAt(RequestLocation::input())); } for input in &form.inputs { let valid = entry diff --git a/crates/registry-breg/src/postgres/external_runtime.rs b/crates/registry-breg/src/postgres/external_runtime.rs index 738f449715..b36e2beb19 100644 --- a/crates/registry-breg/src/postgres/external_runtime.rs +++ b/crates/registry-breg/src/postgres/external_runtime.rs @@ -3124,12 +3124,71 @@ mod postgres_tests { } } + #[tokio::test] + async fn retired_external_paging_is_disclosed_only_for_admitted_views() { + use axum::http::StatusCode; + + let served = Served::new(Duration::from_secs(2)).await; + served.publish_all().await; + let caller = reader("reader-principal", &["allowed"]); + let (status, page) = served.get("&limit=1", caller.clone()).await; + assert_eq!(status, StatusCode::OK, "{page}"); + let cursor = page["nextCursor"].as_str().unwrap(); + let (status, page) = served + .get(&format!("&cursor={cursor}"), caller.clone()) + .await; + assert_eq!(status, StatusCode::OK, "{page}"); + + for query in [ + "&$top=1".to_owned(), + "&limit=1&%24top=private-canary".to_owned(), + format!("&%24skiptoken={cursor}"), + "&$skiptoken=one&$skiptoken=two".to_owned(), + ] { + let (status, problem) = served.get(&query, caller.clone()).await; + assert_eq!(status, StatusCode::BAD_REQUEST, "{query}"); + assert_eq!(problem["code"], "query.invalid"); + assert_eq!(problem["fieldPath"], "query"); + assert!(!problem.to_string().contains("private-canary")); + let (status, _, problem) = served + .send( + &format!("/v1/external-views/view/link/records?accessProfile=unknown{query}"), + caller.clone(), + ) + .await; + assert_eq!(status, StatusCode::NOT_FOUND, "{problem}"); + assert_ne!(problem["code"], "query.invalid"); + } + for selection in [ + "", + "&accessProfile", + "&%61ccessProfile=%ff", + "&accessProfile=", + "&accessProfile=reader&%61ccessProfile=reader", + ] { + let (status, _, problem) = served + .send( + &format!("/v1/external-views/view/link/records?%24top=1{selection}"), + caller.clone(), + ) + .await; + if selection.is_empty() { + assert_eq!(status, StatusCode::BAD_REQUEST); + assert_eq!(problem["fieldPath"], "query"); + } else { + assert_eq!(status, StatusCode::NOT_FOUND, "{selection}"); + assert_eq!(problem["code"], "resource.not-found"); + } + } + served.fixture.cleanup().await; + } + #[tokio::test] async fn a_scope_lock_timeout_is_unavailable_never_incomplete_or_an_invalid_cursor() { let served = Served::new(Duration::from_millis(300)).await; served.publish_all().await; let caller = reader("reader-principal", &["allowed"]); - let (status, first) = served.get("&$top=1", caller.clone()).await; + let (status, first) = served.get("&limit=1", caller.clone()).await; assert_eq!(status, axum::http::StatusCode::OK, "{first}"); let cursor = first["nextCursor"].as_str().unwrap().to_owned(); @@ -3144,11 +3203,11 @@ mod postgres_tests { ) .await .unwrap(); - let (status, problem) = served.get("&$top=1", caller.clone()).await; + let (status, problem) = served.get("&limit=1", caller.clone()).await; assert_eq!(status, axum::http::StatusCode::SERVICE_UNAVAILABLE); assert_eq!(problem["code"], "source.unavailable", "{problem}"); let (status, problem) = served - .get(&format!("&$skiptoken={cursor}"), caller.clone()) + .get(&format!("&cursor={cursor}"), caller.clone()) .await; assert_eq!(status, axum::http::StatusCode::SERVICE_UNAVAILABLE); assert_eq!(problem["code"], "source.unavailable", "{problem}"); @@ -3160,7 +3219,7 @@ mod postgres_tests { .await .unwrap(); - let (status, next) = served.get(&format!("&$skiptoken={cursor}"), caller).await; + let (status, next) = served.get(&format!("&cursor={cursor}"), caller).await; assert_eq!(status, axum::http::StatusCode::OK, "{next}"); assert_eq!(labels(&next).len(), 1); served.fixture.cleanup().await; @@ -3171,7 +3230,7 @@ mod postgres_tests { let served = Served::new(Duration::from_secs(2)).await; served.publish_all().await; let caller = reader("reader-principal", &["allowed"]); - let ordered = "&$top=1&$orderby=label%20asc&$count=true"; + let ordered = "&limit=1&$orderby=label%20asc&$count=true"; let (status, first) = served.get(ordered, caller.clone()).await; assert_eq!(status, axum::http::StatusCode::OK, "{first}"); assert_eq!(labels(&first), ["first"]); @@ -3185,13 +3244,13 @@ mod postgres_tests { .publish_label(&served.scope, "third", "thirdly") .await; let (status, second) = served - .get(&format!("&$skiptoken={cursor}"), caller.clone()) + .get(&format!("&cursor={cursor}"), caller.clone()) .await; assert_eq!(status, axum::http::StatusCode::OK, "{second}"); assert_eq!(labels(&second), ["second"]); assert_eq!(second["count"], 3); let cursor = second["nextCursor"].as_str().unwrap().to_owned(); - let (status, third) = served.get(&format!("&$skiptoken={cursor}"), caller).await; + let (status, third) = served.get(&format!("&cursor={cursor}"), caller).await; assert_eq!(status, axum::http::StatusCode::OK, "{third}"); assert_eq!(labels(&third), ["thirdly"]); assert!(third.get("nextCursor").is_none()); @@ -3304,12 +3363,12 @@ mod postgres_tests { // A continuation of a plain list is as plain as its first page. let mut seen = BTreeMap::new(); - let (status, first) = served.get("&$top=2", caller.clone()).await; + let (status, first) = served.get("&limit=2", caller.clone()).await; assert_eq!(status, axum::http::StatusCode::OK, "{first}"); seen.extend(availabilities(&first)); let cursor = first["nextCursor"].as_str().unwrap().to_owned(); let (status, second) = served - .get(&format!("&$skiptoken={cursor}"), caller.clone()) + .get(&format!("&cursor={cursor}"), caller.clone()) .await; assert_eq!(status, axum::http::StatusCode::OK, "{second}"); assert_eq!(second["status"], "unavailable", "{second}"); @@ -3468,7 +3527,7 @@ mod postgres_tests { let served = Served::new(Duration::from_secs(2)).await; served.publish_all().await; let (status, first) = served - .get("&$top=1", reader("reader-principal", &["allowed"])) + .get("&limit=1", reader("reader-principal", &["allowed"])) .await; assert_eq!(status, axum::http::StatusCode::OK, "{first}"); let cursor = first["nextCursor"].as_str().unwrap().to_owned(); @@ -3482,7 +3541,7 @@ mod postgres_tests { "another row boundary", ), ] { - let (status, problem) = served.get(&format!("&$skiptoken={cursor}"), caller).await; + let (status, problem) = served.get(&format!("&cursor={cursor}"), caller).await; assert_eq!( status, axum::http::StatusCode::BAD_REQUEST, @@ -3495,7 +3554,7 @@ mod postgres_tests { } let (status, next) = served .get( - &format!("&$skiptoken={cursor}"), + &format!("&cursor={cursor}"), reader("reader-principal", &["allowed"]), ) .await; @@ -4860,7 +4919,7 @@ mod postgres_tests { ), (root_refresh(ROOTS[3].0, "desk"), desk_client()), ( - format!("{}&$top=1", root_refresh(ROOTS[0].0, "desk")), + format!("{}&limit=1", root_refresh(ROOTS[0].0, "desk")), desk_client(), ), ] { diff --git a/crates/registry-breg/src/problem_location.rs b/crates/registry-breg/src/problem_location.rs index a79f751c94..37c844bc31 100644 --- a/crates/registry-breg/src/problem_location.rs +++ b/crates/registry-breg/src/problem_location.rs @@ -182,6 +182,15 @@ impl RequestLocation { } } + /// The `input` member of an Action or Proposal body. + #[must_use] + pub fn input() -> Self { + Self { + pointer: "/input".to_owned(), + scope: Scope::Input, + } + } + /// One declared input of an Action or Proposal body. The caller passes /// only a compiled input API name; an over-long name falls back to /// `/input`. @@ -189,10 +198,7 @@ impl RequestLocation { pub fn action_input(api_name: &str) -> Self { let pointer = format!("/input/{}", escape_segment(api_name)); if pointer.chars().count() > MAX_FIELD_PATH_CHARS { - return Self { - pointer: "/input".to_owned(), - scope: Scope::Input, - }; + return Self::input(); } Self { pointer, diff --git a/crates/registry-breg/src/proposal_artifacts.rs b/crates/registry-breg/src/proposal_artifacts.rs index 450b1ad498..d5469a6fc9 100644 --- a/crates/registry-breg/src/proposal_artifacts.rs +++ b/crates/registry-breg/src/proposal_artifacts.rs @@ -568,7 +568,7 @@ fn append_message_openapi( let path = "/v1/proposals/{proposal_id}/messages"; let mut list = operation_document("proposals.list-messages", "get", profiles, false, additions); list["parameters"].as_array_mut().expect("query parameters").extend([ - json!({"name":"after","in":"query","schema":{"type":"string","pattern":"^[1-9][0-9]*$"}}), + json!({"name":"cursor","in":"query","schema":{"type":"string","pattern":"^[1-9][0-9]*$"}}), json!({"name":"limit","in":"query","schema":{"type":"integer","minimum":1,"maximum":50,"default":20}}), ]); list["responses"]["200"]["content"]["application/json"]["schema"] = json!({ @@ -962,7 +962,11 @@ pub(super) fn append_operation_problems(operation: &mut Value, method: &str) { codes.push(ProblemCode::ProposalMessageLimitReached); } if id == "proposals.list-messages" { - codes.extend([ProblemCode::QueryCursorInvalid, ProblemCode::RequestInvalid]); + codes.extend([ + ProblemCode::QueryCursorInvalid, + ProblemCode::QueryInvalid, + ProblemCode::RequestInvalid, + ]); } if id == "proposals.list" { codes.push(ProblemCode::QueryInvalid); diff --git a/crates/registry-breg/src/query.rs b/crates/registry-breg/src/query.rs index e962e604e1..b6aafeafc3 100644 --- a/crates/registry-breg/src/query.rs +++ b/crates/registry-breg/src/query.rs @@ -623,13 +623,11 @@ where } /// The fixed query parameter names a refusal may name as its location. -pub const QUERY_PARAMETERS: [&str; 13] = [ +pub const QUERY_PARAMETERS: [&str; 11] = [ "$select", "$filter", "$orderby", - "$top", "$count", - "$skiptoken", "bbox", "accessProfile", "asOf", @@ -741,7 +739,7 @@ struct QueryBuilder { top: Option, count: Option, bbox: Option, - skiptoken: Option<(String, &'static str)>, + skiptoken: Option, } impl QueryBuilder { @@ -770,7 +768,7 @@ impl QueryBuilder { ensure_absent(self.orderby.is_none())?; self.orderby = Some(parse_orderby(value)?); } - "limit" | "$top" => { + "limit" => { ensure_absent(self.top.is_none())?; self.top = Some(parse_top(value)?); } @@ -782,14 +780,9 @@ impl QueryBuilder { ensure_absent(self.bbox.is_none())?; self.bbox = Some(parse_bbox(value)?); } - "cursor" | "$skiptoken" => { + "cursor" => { ensure_absent(self.skiptoken.is_none())?; - let name = if key == "cursor" { - "cursor" - } else { - "$skiptoken" - }; - self.skiptoken = Some((parse_opaque_value(value, MAX_CURSOR_TOKEN_BYTES)?, name)); + self.skiptoken = Some(parse_opaque_value(value, MAX_CURSOR_TOKEN_BYTES)?); } "fields" | "filter" | "sort" | "pageSize" | "$skip" | "$apply" | "$expand" | "$batch" => { @@ -804,7 +797,7 @@ impl QueryBuilder { } fn cursor_parameter(&self) -> Option<&'static str> { - self.skiptoken.as_ref().map(|(_, parameter)| *parameter) + self.skiptoken.as_ref().map(|_| "cursor") } /// A continuation carries its whole query, so a conflict names the @@ -824,7 +817,7 @@ impl QueryBuilder { bbox: self.bbox, }; let mode = match self.skiptoken { - Some((token, _)) => { + Some(token) => { if self.as_of.is_some() || options.has_any_option() { return Err(QueryParseError::ConflictingOptions); } @@ -1825,7 +1818,7 @@ mod tests { ("$select", "case-code,status"), ("$filter", "status eq 'open'"), ("$orderby", "opened-on desc"), - ("$top", "50"), + ("limit", "50"), ("$count", "false"), ]) .expect("query parses"); @@ -1901,27 +1894,36 @@ mod tests { ); } assert_eq!( - parse([("$top", "10"), ("$top", "11")]), + parse([("limit", "10"), ("limit", "11")]), Err(QueryParseError::DuplicateOption) ); } #[test] - fn pagination_names_share_query_and_cursor_rules() { - assert_eq!(parse([("limit", "10")]), parse([("$top", "10")])); - assert_eq!( - parse([("accessProfile", "reader"), ("cursor", "opaque-token")]), - parse([("accessProfile", "reader"), ("$skiptoken", "opaque-token"),]) - ); - for (parameters, duplicate) in [ - ([("$top", "10"), ("limit", "10")], "limit"), - ([("limit", "10"), ("$top", "10")], "$top"), - ([("$skiptoken", "same"), ("cursor", "same")], "cursor"), - ([("cursor", "same"), ("$skiptoken", "same")], "$skiptoken"), + fn retired_page_names_have_no_public_parameter_location() { + for (alias, value) in [("$top", "10"), ("$skiptoken", "opaque")] { + assert_eq!( + parse_read_query_located([(alias, value)]).unwrap_err().1, + None + ); + assert_eq!( + parse_snapshot_query_located([(alias, value)]) + .unwrap_err() + .1, + None + ); + } + } + + #[test] + fn canonical_page_names_keep_their_fault_locations() { + for (parameters, member) in [ + ([("limit", "10"), ("limit", "11")], "limit"), + ([("cursor", "same"), ("cursor", "same")], "cursor"), ] { assert_eq!( parse_read_query_located(parameters), - Err((QueryParseError::DuplicateOption, Some(duplicate))) + Err((QueryParseError::DuplicateOption, Some(member))) ); } assert_eq!( @@ -1932,18 +1934,16 @@ mod tests { parse_read_query_located([("cursor", "opaque-token"), ("limit", "10")]), Err((QueryParseError::ConflictingOptions, Some("cursor"))) ); - for key in ["cursor", "$skiptoken"] { - assert_eq!( - parse_snapshot_query_located([(key, "opaque-token"), ("validAt", "later")]), - Err((QueryParseError::ConflictingOptions, Some(key))) - ); - } + assert_eq!( + parse_snapshot_query_located([("cursor", "opaque-token"), ("validAt", "later")]), + Err((QueryParseError::ConflictingOptions, Some("cursor"))) + ); } #[test] - fn skiptoken_only_allows_access_profile() { - let query = parse([("accessProfile", "reader"), ("$skiptoken", "opaque-token")]) - .expect("skiptoken query parses"); + fn cursor_only_allows_access_profile() { + let query = parse([("accessProfile", "reader"), ("cursor", "opaque-token")]) + .expect("cursor query parses"); assert!(matches!(query.mode, ParsedReadQueryMode::SkipToken { .. })); for pair in [ @@ -1951,11 +1951,11 @@ mod tests { ("$select", "field"), ("$filter", "field eq 'value'"), ("$orderby", "field"), - ("$top", "10"), + ("limit", "10"), ("$count", "true"), ] { assert_eq!( - parse([("$skiptoken", "opaque-token"), pair]), + parse([("cursor", "opaque-token"), pair]), Err(QueryParseError::ConflictingOptions) ); } @@ -1963,16 +1963,19 @@ mod tests { #[test] fn top_and_count_are_strict() { - assert!(parse([("$top", "1")]) + assert!(parse([("limit", "1")]) .unwrap() .canonical() .contains("top=1")); - assert!(parse([("$top", "100")]) + assert!(parse([("limit", "100")]) .unwrap() .canonical() .contains("top=100")); for value in ["", "0", "101", "-1", "1.0", "+1", "true"] { - assert_eq!(parse([("$top", value)]), Err(QueryParseError::InvalidValue)); + assert_eq!( + parse([("limit", value)]), + Err(QueryParseError::InvalidValue) + ); } assert!(parse([("$count", "true")]) .unwrap() @@ -2162,8 +2165,8 @@ mod tests { ); let token = "a".repeat(MAX_CURSOR_TOKEN_BYTES); - assert!(parse_read_query([("$skiptoken", token.as_str())]).is_ok()); - assert!(parse_snapshot_query([("$skiptoken", token.as_str())]).is_ok()); + assert!(parse_read_query([("cursor", token.as_str())]).is_ok()); + assert!(parse_snapshot_query([("cursor", token.as_str())]).is_ok()); assert!(parse_snapshot_query([("snapshot", "a".repeat(MAX_OPAQUE_VALUE_BYTES))]).is_ok()); assert_eq!( parse_snapshot_query([("snapshot", token.as_str())]), @@ -2171,7 +2174,7 @@ mod tests { ); let large_token = "a".repeat(MAX_CURSOR_TOKEN_BYTES + 1); assert_eq!( - parse_read_query([("$skiptoken", large_token.as_str())]), + parse_read_query([("cursor", large_token.as_str())]), Err(QueryParseError::InvalidValue) ); } @@ -2233,7 +2236,7 @@ mod tests { #[test] fn bbox_conflicts_with_skiptoken_and_is_value_free_in_debug() { assert_eq!( - parse([("$skiptoken", "cursor-canary"), ("bbox", "0,0,1,1")]), + parse([("cursor", "cursor-canary"), ("bbox", "0,0,1,1")]), Err(QueryParseError::ConflictingOptions) ); let parsed = parse([("bbox", "100.1,10.2,100.3,10.4")]).expect("bbox parses"); @@ -2315,7 +2318,7 @@ mod tests { ("$select", "household_id,valid_from"), ("$filter", "status eq 'active'"), ("$orderby", "valid_from"), - ("$top", "20"), + ("limit", "20"), ("$count", "true"), ]) .expect("snapshot query syntax"); @@ -2344,20 +2347,20 @@ mod tests { fn snapshot_continuations_cannot_override_the_bound_query() { assert!(parse_snapshot_query([ ("accessProfile", "caseworker"), - ("$skiptoken", "cursor-canary"), + ("cursor", "cursor-canary"), ]) .is_ok()); for key in [ - "snapshot", "validAt", "$select", "$filter", "$orderby", "$top", "$count", + "snapshot", "validAt", "$select", "$filter", "$orderby", "limit", "$count", ] { let value = match key { "$filter" => "field eq 'value'", - "$top" => "10", + "limit" => "10", "$count" => "true", _ => "value", }; assert_eq!( - parse_snapshot_query([("$skiptoken", "cursor-canary"), (key, value)]), + parse_snapshot_query([("cursor", "cursor-canary"), (key, value)]), Err(QueryParseError::ConflictingOptions) ); } @@ -2411,7 +2414,7 @@ mod tests { assert!(!debug.contains("secret")); assert!(!debug.contains("literal-canary")); - let cursor = parse([("$skiptoken", "cursor-canary")]).expect("cursor query parses"); + let cursor = parse([("cursor", "cursor-canary")]).expect("cursor query parses"); assert!(!format!("{cursor:?}").contains("cursor-canary")); } diff --git a/crates/registry-breg/tests/disclosure/history.rs b/crates/registry-breg/tests/disclosure/history.rs index 827eb15c02..fb02bb846b 100644 --- a/crates/registry-breg/tests/disclosure/history.rs +++ b/crates/registry-breg/tests/disclosure/history.rs @@ -306,7 +306,7 @@ impl History { async fn snapshot(&self, route: &str, profile: &str) -> Reply { self.get( - &format!("/v1/records/{route}:snapshot?$count=true&$top=100"), + &format!("/v1/records/{route}:snapshot?$count=true&limit=100"), profile, ) .await @@ -866,7 +866,7 @@ async fn an_old_snapshot_reference_does_not_read_a_record_marked_since() { history .get( &format!( - "/v1/records/{route}:snapshot?$count=true&$top=100&snapshot={reference}" + "/v1/records/{route}:snapshot?$count=true&limit=100&snapshot={reference}" ), REGISTRAR, ) diff --git a/crates/registry-breg/tests/http_read_only.rs b/crates/registry-breg/tests/http_read_only.rs index eb555471c8..29fbb52590 100644 --- a/crates/registry-breg/tests/http_read_only.rs +++ b/crates/registry-breg/tests/http_read_only.rs @@ -725,7 +725,7 @@ async fn snapshot_route_requires_its_own_current_authority_and_never_calls_live_ } assert!(snapshots.requests.lock().unwrap().is_empty()); let response = send_to(&app, Method::GET, - "/v1/records/assignments:snapshot?validAt=2026-06-05&$select=label&$filter=label%20eq%20'A'&$top=3&$count=true", + "/v1/records/assignments:snapshot?validAt=2026-06-05&$select=label&$filter=label%20eq%20'A'&limit=3&$count=true", Some(caseworker_claims("case-management"))).await; assert_eq!(response.status(), StatusCode::OK); assert_eq!(response.headers()["cache-control"], "no-store"); @@ -913,6 +913,179 @@ async fn snapshot_validity_is_typed_optional_and_has_no_clock_default() { assert!(snapshots.requests.lock().unwrap().is_empty()); } +#[tokio::test] +async fn retired_snapshot_paging_is_disclosed_only_to_the_selected_profile() { + let (app, records, snapshots) = snapshot_harness(SNAPSHOT_PROJECT, &[]); + for query in [ + "$top=1", + "%24top=private-canary&limit=1", + "cursor=opaque&%24skiptoken=private-canary", + "$top=1&$top=2", + ] { + for (profile, claims, expected) in [ + ("history", public_claims(), StatusCode::FORBIDDEN), + ( + "live-only", + caseworker_claims("case-management"), + StatusCode::FORBIDDEN, + ), + ] { + let response = send_to( + &app, + Method::GET, + &format!("/v1/records/assignments:snapshot?accessProfile={profile}&{query}"), + Some(claims), + ) + .await; + assert_eq!(response.status(), expected, "{query}"); + assert_ne!(body_json(response).await["code"], "query.invalid"); + } + let response = send_to( + &app, + Method::GET, + &format!("/v1/records/assignments:snapshot?{query}"), + Some(caseworker_claims("case-management")), + ) + .await; + assert_eq!(response.status(), StatusCode::BAD_REQUEST, "{query}"); + let problem = body_json(response).await; + assert_eq!(problem["code"], "query.invalid"); + assert_eq!(problem["fieldPath"], "query"); + assert!(!problem.to_string().contains("private-canary")); + } + assert!(snapshots.requests.lock().unwrap().is_empty()); + assert_eq!(records.calls(), 0); +} + +#[tokio::test] +async fn retired_get_paging_waits_for_admission_and_audit() { + assert_retired_exact_paging( + Method::GET, + "/v1/records/households/00000000-0000-4000-8000-000000000001", + ) + .await; +} + +#[tokio::test] +async fn retired_lookup_paging_waits_for_admission_and_audit() { + assert_retired_exact_paging(Method::POST, "/v1/records/households:lookup").await; +} + +async fn assert_retired_exact_paging(method: Method, route: &str) { + let harness = Harness::from_project(LOOKUP_PATH_PROJECT, true); + for (profile, claims, status, code) in [ + ( + "accessProfile=unknown&", + caseworker_claims("case-management"), + StatusCode::FORBIDDEN, + "profile.not-authorized", + ), + ( + "accessProfile=operator&", + caseworker_claims("wrong-purpose"), + StatusCode::FORBIDDEN, + "profile.not-authorized", + ), + ( + "", + caseworker_claims("case-management"), + StatusCode::BAD_REQUEST, + "query.invalid", + ), + ( + "%61ccessProfile=operator&", + caseworker_claims("case-management"), + StatusCode::BAD_REQUEST, + "query.invalid", + ), + ] { + let before = harness.records.refusal_calls(); + let response = harness + .send_json( + method.clone(), + &format!("{route}?{profile}%24top=private-canary"), + Some(claims), + json!({"selector": "by-household-code", "values": {"householdCode": "example"}}), + ) + .await; + assert_eq!(response.status(), status, "{route} {profile}"); + let problem = body_json(response).await; + assert_eq!(problem["code"], code); + if code == "query.invalid" { + assert_eq!(problem["fieldPath"], "query"); + } + assert!(!problem.to_string().contains("private-canary")); + assert_eq!(harness.records.refusal_calls(), before + 1); + } + assert_eq!(harness.records.calls(), 0); +} + +#[tokio::test] +async fn retired_paging_refuses_malformed_explicit_profile_selection() { + let harness = Harness::from_project(LOOKUP_PATH_PROJECT, true); + let (snapshots_app, snapshot_records, snapshots) = snapshot_harness(SNAPSHOT_PROJECT, &[]); + for selector in [ + "accessProfile", + "%61ccessProfile=%ff", + "accessProfile=", + "accessProfile=badProfile", + "accessProfile=operator&%61ccessProfile=operator", + "accessProfile=history&%61ccessProfile=history", + ] { + let claims = Some(caseworker_claims("case-management")); + let response = harness + .send( + Method::GET, + &format!("/v1/records/households?$top=1&{selector}"), + claims.clone(), + ) + .await; + assert_eq!(response.status(), StatusCode::FORBIDDEN, "{selector}"); + assert_eq!(body_json(response).await["code"], "profile.not-authorized"); + + let response = send_to( + &snapshots_app, + Method::GET, + &format!("/v1/records/assignments:snapshot?$top=1&{selector}"), + claims, + ) + .await; + assert_eq!(response.status(), StatusCode::NOT_FOUND, "{selector}"); + assert_eq!(body_json(response).await["code"], "resource.not-found"); + } + assert_eq!(harness.records.calls(), 0); + assert_eq!(snapshot_records.calls(), 0); + assert!(snapshots.requests.lock().unwrap().is_empty()); +} + +#[tokio::test] +async fn retired_record_paging_has_a_fixed_location_after_admission() { + let harness = Harness::new(true); + for accept in [Some("application/json"), Some("application/ld+json")] { + for query in [ + "$top=1", + "limit=1&%24top=private-canary", + "%24skiptoken=private-canary&cursor=opaque", + "$skiptoken=one&$skiptoken=two", + ] { + let response = harness + .send_with_accept( + Method::GET, + &format!("/v1/records/cases?{query}"), + Some(public_claims()), + accept, + ) + .await; + assert_eq!(response.status(), StatusCode::BAD_REQUEST, "{query}"); + let problem = body_json(response).await; + assert_eq!(problem["code"], "query.invalid"); + assert_eq!(problem["fieldPath"], "query"); + assert!(!problem.to_string().contains("private-canary")); + } + } + assert_eq!(harness.records.calls(), 0); +} + #[tokio::test] async fn snapshot_rejects_ambiguous_time_and_cursor_overrides_before_history_io() { let (app, records, snapshots) = snapshot_harness(SNAPSHOT_PROJECT, &[]); @@ -922,11 +1095,11 @@ async fn snapshot_rejects_ambiguous_time_and_cursor_overrides_before_history_io( "snapshot=forged-canary", "snapshot=a&snapshot=b", "validAt=2026-06-05&validAt=2026-07-05", - "$skiptoken=canary&validAt=2026-06-05", - "$skiptoken=canary&snapshot=canary", + "cursor=canary&validAt=2026-06-05", + "cursor=canary&snapshot=canary", "$expand=household", "$select=hidden", - "$top=101", + "limit=101", ] { let response = send_to( &app, @@ -1047,7 +1220,7 @@ async fn closed_query_grammar_reaches_record_service_as_compiled_query() { let accepted = harness .send( Method::GET, - "/v1/records/cases?$select=label&$filter=startswith(label,'Visible')&$orderby=label&$top=25", + "/v1/records/cases?$select=label&$filter=startswith(label,'Visible')&$orderby=label&limit=25", Some(public_claims()), ) .await; @@ -1115,7 +1288,7 @@ async fn bbox_reaches_record_service_only_with_declared_spatial_grant() { let accepted = harness .send_with_accept( Method::GET, - "/v1/records/sites?bbox=100,10,101,11&$filter=code%20eq%20'SITE-A'&$top=25", + "/v1/records/sites?bbox=100,10,101,11&$filter=code%20eq%20'SITE-A'&limit=25", Some(public_claims()), Some("application/geo+json"), ) @@ -1690,7 +1863,7 @@ async fn relationship_route_uses_path_grant_not_direct_target_rights() { .send( Method::GET, &format!( - "/v1/records/households/{root}/people?accessProfile=operator&$select=personCode&$filter=startswith(personCode,'P-')&$orderby=personCode&$top=5&$count=true" + "/v1/records/households/{root}/people?accessProfile=operator&$select=personCode&$filter=startswith(personCode,'P-')&$orderby=personCode&limit=5&$count=true" ), Some(caseworker_claims("case-management")), ) @@ -2047,7 +2220,7 @@ async fn derived_fields_are_discoverable_as_read_only_response_properties() { async fn continuation_requests_refuse_query_overrides_before_record_io() { let harness = Harness::new(true); let before = harness.records.calls(); - for parameter in ["cursor", "$skiptoken"] { + for parameter in ["cursor", "%63ursor"] { let response = harness .send( Method::GET, @@ -2058,7 +2231,7 @@ async fn continuation_requests_refuse_query_overrides_before_record_io() { assert_eq!(response.status(), StatusCode::BAD_REQUEST); let problem = body_json(response).await; assert_eq!(problem["code"], "query.invalid"); - assert_eq!(problem["fieldPath"], parameter); + assert_eq!(problem["fieldPath"], "cursor"); } assert_eq!(harness.records.calls(), before); } @@ -2118,9 +2291,9 @@ fn retired_proposal_history_query_name_is_not_advertised() { } #[tokio::test] -async fn record_list_accepts_limit_and_top_and_refuses_ambiguous_sizes() { +async fn record_list_accepts_limit_and_refuses_ambiguous_sizes() { let harness = Harness::new(true); - for query in ["limit=0", "$top=1&limit=1"] { + for query in ["limit=0", "limit=1&%6cimit=1"] { let response = harness .send( Method::GET, @@ -2135,7 +2308,7 @@ async fn record_list_accepts_limit_and_top_and_refuses_ambiguous_sizes() { } assert_eq!(harness.records.calls(), 0); - for query in ["limit=1", "$top=1"] { + for query in ["limit=1", "%6cimit=1"] { let accepted = harness .send( Method::GET, @@ -2149,7 +2322,7 @@ async fn record_list_accepts_limit_and_top_and_refuses_ambiguous_sizes() { } #[tokio::test] -async fn count_requires_compiled_permission_and_top_is_bounded() { +async fn count_requires_compiled_permission_and_limit_is_bounded() { let harness = Harness::new(true); let public_count = harness .send( @@ -2164,7 +2337,7 @@ async fn count_requires_compiled_permission_and_top_is_bounded() { let caseworker_count = harness .send( Method::GET, - "/v1/records/cases?accessProfile=caseworker&$count=true&$top=1", + "/v1/records/cases?accessProfile=caseworker&$count=true&limit=1", Some(caseworker_claims("case-management")), ) .await; @@ -2315,7 +2488,7 @@ async fn a_list_that_satisfies_an_alternative_runs() { async fn a_list_that_pins_no_alternative_is_refused_before_any_query() { for query in [ "", - "&$top=5", + "&limit=5", "&$filter=startswith(label,'Vis')", "&$filter=label%20ne%20'x'", "&$filter=label%20eq%20null", @@ -2450,7 +2623,7 @@ async fn continuation_keeps_the_criteria_and_cannot_drop_them() { let first_query = request_query(&first_request); let token = required_filters_cursor(first_query); - for parameter in ["cursor", "$skiptoken"] { + for parameter in ["cursor", "%63ursor"] { let next = required_filters_list(&harness, &format!("&{parameter}={token}")).await; assert_eq!(next.status(), StatusCode::OK, "{parameter}"); let next_request = harness.records.last_request(); @@ -2459,6 +2632,14 @@ async fn continuation_keeps_the_criteria_and_cannot_drop_them() { assert_eq!(single_filter_predicate(next_query).field_id, "label"); } + let calls = harness.records.calls(); + let retired = required_filters_list(&harness, &format!("&%24skiptoken={token}")).await; + assert_eq!(retired.status(), StatusCode::BAD_REQUEST); + let problem = body_json(retired).await; + assert_eq!(problem["code"], "query.invalid"); + assert_eq!(problem["fieldPath"], "query"); + assert_eq!(harness.records.calls(), calls); + // The same cursor without its filter no longer matches its own binding. let mut stripped = serde_json::to_value(&first_query.cursor_query).expect("query serializes"); stripped["filter"] = Value::Null; @@ -2478,7 +2659,7 @@ async fn continuation_keeps_the_criteria_and_cannot_drop_them() { let _ = &mut payload; let forged = codec.encode(&payload).expect("cursor encodes"); let calls = harness.records.calls(); - let refused = required_filters_list(&harness, &format!("&$skiptoken={forged}")).await; + let refused = required_filters_list(&harness, &format!("&cursor={forged}")).await; assert_eq!(refused.status(), StatusCode::BAD_REQUEST); assert_eq!(body_json(refused).await["code"], "query.cursor-invalid"); assert_eq!(harness.records.calls(), calls); @@ -2572,8 +2753,8 @@ fn strict_query_debug_output_redacts_identifiers_literals_and_tokens() { assert!(!rendered.contains("secret")); assert!(!rendered.contains("literal-canary")); - let token_query = strict_query::parse_read_query([("$skiptoken", "cursor-canary")]) - .expect("cursor query parses"); + let token_query = + strict_query::parse_read_query([("cursor", "cursor-canary")]).expect("cursor query parses"); assert!(!format!("{token_query:?}").contains("cursor-canary")); } @@ -3293,7 +3474,7 @@ async fn projection_can_only_reduce_the_authorized_profile() { let caller_limit = harness .send( Method::GET, - "/v1/records/cases?$top=101", + "/v1/records/cases?limit=101", Some(public_claims()), ) .await; @@ -3917,7 +4098,7 @@ async fn real_router_serves_only_authorized_explicit_revision_routes() { let malformed_query = send_to( &app, Method::GET, - &format!("{list_path}?accessProfile=caseworker&$top"), + &format!("{list_path}?accessProfile=caseworker&limit"), Some(caseworker_claims("case-management")), ) .await; @@ -4007,7 +4188,7 @@ async fn real_router_serves_only_authorized_explicit_revision_routes() { let audit_failure = send_to( &app, Method::GET, - &format!("{list_path}?$top=2"), + &format!("{list_path}?limit=2"), Some(caseworker_claims("case-management")), ) .await; @@ -4754,7 +4935,7 @@ async fn workspace_temporal_capabilities_and_no_store_cover_success_and_refusal( "/v1/records/public-records/00000000-0000-4000-8000-000000000001", "/v1/registry?accessProfile=unknown", "/v1/schemas/protected-ledger", - "/v1/records/public-records?$top=0", + "/v1/records/public-records?limit=0", "/missing", ] { let response = harness.send(Method::GET, uri, Some(public_claims())).await; @@ -4846,6 +5027,70 @@ async fn missing_row_boundary_claim_refuses_list_current_and_as_of_reads() { } } +#[tokio::test] +async fn retired_temporal_page_names_do_not_bypass_row_boundary_admission() { + let harness = Harness::from_project(TEMPORAL_ROW_BOUNDARY_PROJECT, true); + for uri in [ + "/v1/records/licences:current?%24top=1", + "/v1/records/licences:as-of?asOf=2026-06-05&%24skiptoken=opaque", + ] { + let response = harness + .send(Method::GET, uri, Some(claims_without_jurisdictions())) + .await; + assert_eq!(response.status(), StatusCode::FORBIDDEN, "{uri}"); + assert_eq!(body_json(response).await["code"], "profile.not-authorized"); + let response = harness + .send( + Method::GET, + uri, + Some(caseworker_claims_with_direct("case-management", [])), + ) + .await; + assert_eq!(response.status(), StatusCode::BAD_REQUEST, "{uri}"); + let problem = body_json(response).await; + assert_eq!(problem["code"], "query.invalid"); + assert_eq!(problem["fieldPath"], "query"); + } + assert_eq!(harness.records.calls(), 0); +} + +#[tokio::test] +async fn retired_related_page_names_follow_path_admission_and_root_format_checks() { + let harness = Harness::from_project(LOOKUP_PATH_PROJECT, true); + let root = "00000000-0000-4000-8000-000000000001"; + for (root_id, path, profile, expected) in [ + (root, "people", "operator", StatusCode::BAD_REQUEST), + (root, "people", "viewer", StatusCode::FORBIDDEN), + (root, "unknown-path", "operator", StatusCode::NOT_FOUND), + ("bad-root", "people", "operator", StatusCode::NOT_FOUND), + ] { + let response = harness + .send( + Method::GET, + &format!( + "/v1/records/households/{root_id}/{path}?accessProfile={profile}&%24top=1" + ), + Some(caseworker_claims_with_direct( + "case-management", + [( + "household_id", + VerifiedClaimValue::direct_string(root).unwrap(), + )], + )), + ) + .await; + assert_eq!(response.status(), expected, "{root_id}/{path} {profile}"); + let problem = body_json(response).await; + if expected == StatusCode::BAD_REQUEST { + assert_eq!(problem["code"], "query.invalid"); + assert_eq!(problem["fieldPath"], "query"); + } else { + assert_ne!(problem["code"], "query.invalid"); + } + } + assert_eq!(harness.records.calls(), 0); +} + /// Every public refusal names a problem type on the shared Registry Stack /// identifier host, so an adopter can resolve the type it was handed. A dot in /// the code separates path segments under the product prefix. diff --git a/crates/registry-breg/tests/postgres_access_log.rs b/crates/registry-breg/tests/postgres_access_log.rs index c41c65470b..df5b6e5065 100644 --- a/crates/registry-breg/tests/postgres_access_log.rs +++ b/crates/registry-breg/tests/postgres_access_log.rs @@ -494,7 +494,7 @@ async fn subject_access_log_requires_current_record_ownership_and_records_each_r &app, &agency, Method::GET, - "/v1/records/entries?$top=1", + "/v1/records/entries?limit=1", None, None ) @@ -551,7 +551,7 @@ async fn subject_access_log_requires_current_record_ownership_and_records_each_r &app, &agency, Method::GET, - "/v1/records/entries?$top=2", + "/v1/records/entries?limit=2", None, None ) @@ -1265,7 +1265,7 @@ async fn head_on_record_reads_is_refused_without_a_journaled_read() { let agency = token(&idp, "agency", "officer"); for uri in [ format!("/v1/records/entries/{RECORD_A}"), - "/v1/records/entries?$top=1".to_owned(), + "/v1/records/entries?limit=1".to_owned(), ] { assert_head_is_refused_like_an_unaccepted_method(&db, &app, &agency, &uri).await; } @@ -1405,7 +1405,7 @@ async fn a_request_without_its_required_access_reason_is_refused_before_any_reco &app, &agency, Method::GET, - "/v1/records/entries?accessProfile=reasoned&$top=1", + "/v1/records/entries?accessProfile=reasoned&limit=1", None, None, ) @@ -1429,6 +1429,46 @@ async fn a_request_without_its_required_access_reason_is_refused_before_any_reco db.cleanup().await; } +#[tokio::test] +async fn retired_exact_and_lookup_paging_waits_for_required_attribution() { + let (db, app, idp) = setup_registry(compiled_with_access_reason()).await; + let agency = token(&idp, "agency", "officer"); + let reason = reason_header("Review the synthetic record"); + for (method, route, body) in [ + (Method::GET, format!("/v1/records/entries/{RECORD_A}"), None), + ( + Method::POST, + "/v1/records/entries:lookup".to_owned(), + Some(json!({"selector":"by-subject","values":{"subject":SUBJECT}})), + ), + ] { + for (header, code) in [ + (None, "request.access-reason-required"), + (Some("not base64url!"), "request.access-reason-required"), + (Some(reason.as_str()), "query.invalid"), + ] { + let (status, problem) = send_reasoned( + &app, + &agency, + method.clone(), + &format!("{route}?accessProfile=reasoned&%24skiptoken=private-canary"), + body.clone(), + header, + ) + .await; + assert_eq!(status, StatusCode::BAD_REQUEST); + assert_eq!(problem["code"], code); + if code == "query.invalid" { + assert_eq!(problem["fieldPath"], "query"); + } + } + } + assert_eq!(access_log_rows(&db).await, 0); + drop(app); + drop(idp); + db.cleanup().await; +} + #[tokio::test] async fn an_invalid_access_reason_is_refused_like_a_missing_one() { let (db, app, idp) = setup_registry(compiled_with_access_reason()).await; @@ -1621,7 +1661,7 @@ async fn a_read_under_an_alerting_profile_emits_one_event_per_access_log_entry() &app, &agency, Method::GET, - "/v1/records/entries?accessProfile=reasoned&$top=2", + "/v1/records/entries?accessProfile=reasoned&limit=2", None, Some(&reason_header(reason)), ) @@ -1674,7 +1714,7 @@ async fn a_read_under_a_profile_the_hook_does_not_name_emits_none() { let agency = token(&idp, "agency", "officer"); for uri in [ format!("/v1/records/entries/{RECORD_A}"), - "/v1/records/entries?$top=2".to_owned(), + "/v1/records/entries?limit=2".to_owned(), ] { let (status, _) = send_reasoned(&app, &agency, Method::GET, &uri, None, None).await; assert_eq!(status, StatusCode::OK); diff --git a/crates/registry-breg/tests/postgres_consent_access.rs b/crates/registry-breg/tests/postgres_consent_access.rs index 521953d1bd..281217c34d 100644 --- a/crates/registry-breg/tests/postgres_consent_access.rs +++ b/crates/registry-breg/tests/postgres_consent_access.rs @@ -469,7 +469,7 @@ async fn real_postgres_consent_gates_every_read_operation_on_id_and_on_reference assert_eq!(ids(&page), expected, "{route}"); let first = h .get( - &format!("/v1/records/{route}?accessProfile={SCOPE}&$top=1&$count=true"), + &format!("/v1/records/{route}?accessProfile={SCOPE}&limit=1&$count=true"), &wfp, ) .await; @@ -629,7 +629,7 @@ async fn real_postgres_consent_gates_every_read_operation_on_id_and_on_reference for (route, cursor) in &cursors { let page = h .get( - &format!("/v1/records/{route}?accessProfile={SCOPE}&$skiptoken={cursor}"), + &format!("/v1/records/{route}?accessProfile={SCOPE}&cursor={cursor}"), &wfp, ) .await; @@ -950,7 +950,7 @@ async fn real_postgres_consent_matches_recipient_sets_purpose_and_scope_exactly( let alpha_give = h.decide(decision(&alpha_only, "ngo-alpha", "given")).await; let feed = h .get( - "/v1/records/consent-decisions?accessProfile=recipient-feed&$top=100", + "/v1/records/consent-decisions?accessProfile=recipient-feed&limit=100", &h.feed(WFP_CLIENT), ) .await; @@ -998,7 +998,7 @@ async fn real_postgres_consent_matches_recipient_sets_purpose_and_scope_exactly( ); let alpha_feed = h .get( - "/v1/records/consent-decisions?accessProfile=recipient-feed&$top=100", + "/v1/records/consent-decisions?accessProfile=recipient-feed&limit=100", &h.feed(ALPHA_CLIENT), ) .await; @@ -1019,7 +1019,7 @@ async fn real_postgres_consent_matches_recipient_sets_purpose_and_scope_exactly( let (status, body) = send( &h.app, Method::GET, - "/v1/records/consent-decisions?accessProfile=recipient-feed&$top=100", + "/v1/records/consent-decisions?accessProfile=recipient-feed&limit=100", Value::Null, None, &forged_feed, @@ -1105,7 +1105,7 @@ async fn real_postgres_consent_refusals_reach_no_recipient_through_an_authored_s let beta = h.feed(BETA_CLIENT); let feed = h .get( - "/v1/records/consent-decisions?accessProfile=recipient-feed&$top=100", + "/v1/records/consent-decisions?accessProfile=recipient-feed&limit=100", &beta, ) .await; @@ -1360,7 +1360,7 @@ async fn real_postgres_consent_probe_runs_once_per_list_and_count() { let wfp = h.reader(WFP_CLIENT, PURPOSE); let page = h .get( - &format!("/v1/records/persons?accessProfile={SCOPE}&$top=100&$count=true"), + &format!("/v1/records/persons?accessProfile={SCOPE}&limit=100&$count=true"), &wfp, ) .await; @@ -1585,7 +1585,7 @@ async fn real_postgres_consent_gated_list_latency_budget() { admin_task.abort(); let token = h.reader(WFP_CLIENT, PURPOSE); - let uri = format!("/v1/records/persons?accessProfile={SCOPE}&$top=100&$count=true"); + let uri = format!("/v1/records/persons?accessProfile={SCOPE}&limit=100&$count=true"); h.get(&uri, &token).await; let mut samples = Vec::with_capacity(SAMPLES); for _ in 0..SAMPLES { diff --git a/crates/registry-breg/tests/postgres_historical.rs b/crates/registry-breg/tests/postgres_historical.rs index d6363ac379..969b693eb3 100644 --- a/crates/registry-breg/tests/postgres_historical.rs +++ b/crates/registry-breg/tests/postgres_historical.rs @@ -124,7 +124,7 @@ async fn snapshot_http_reconstructs_before_filters_and_keeps_pages_pinned() { let vocabulary_search = send( &app, &format!( - "/v1/records/memberships:snapshot?snapshot={}&validAt=2026-06-05&$select=jurisdiction&$filter=contains(jurisdiction,'ONE-A')&$top=1", + "/v1/records/memberships:snapshot?snapshot={}&validAt=2026-06-05&$select=jurisdiction&$filter=contains(jurisdiction,'ONE-A')&limit=1", snapshot_ref(OLD_REFERENCE_UUID) ), Some(history_claims(["zone-a"])), @@ -207,7 +207,7 @@ async fn snapshot_http_reconstructs_before_filters_and_keeps_pages_pinned() { let first_page = send( &app, - "/v1/records/memberships:snapshot?validAt=2026-06-05&$select=householdCode&$orderby=householdCode&$top=1&$count=true", + "/v1/records/memberships:snapshot?validAt=2026-06-05&$select=householdCode&$orderby=householdCode&limit=1&$count=true", Some(history_claims(["zone-a"])), ) .await; @@ -225,7 +225,7 @@ async fn snapshot_http_reconstructs_before_filters_and_keeps_pages_pinned() { let second_page = send( &app, - &format!("/v1/records/memberships:snapshot?$skiptoken={cursor}"), + &format!("/v1/records/memberships:snapshot?cursor={cursor}"), Some(history_claims(["zone-a"])), ) .await; @@ -483,7 +483,7 @@ async fn snapshot_count_filter_probe_stays_bounded_and_pinned() { let started = Instant::now(); let first_page = send( &app, - "/v1/records/memberships:snapshot?$select=householdCode&$filter=householdCode%20eq%20'probe-even'&$orderby=householdCode&$top=100&$count=true", + "/v1/records/memberships:snapshot?$select=householdCode&$filter=householdCode%20eq%20'probe-even'&$orderby=householdCode&limit=100&$count=true", Some(history_claims(["zone-a"])), ) .await; @@ -504,7 +504,7 @@ async fn snapshot_count_filter_probe_stays_bounded_and_pinned() { let second_page = send( &app, - &format!("/v1/records/memberships:snapshot?$skiptoken={cursor}"), + &format!("/v1/records/memberships:snapshot?cursor={cursor}"), Some(history_claims(["zone-a"])), ) .await; diff --git a/crates/registry-breg/tests/postgres_ingestion_runs.rs b/crates/registry-breg/tests/postgres_ingestion_runs.rs index 0d0b7c070f..3ba613eec5 100644 --- a/crates/registry-breg/tests/postgres_ingestion_runs.rs +++ b/crates/registry-breg/tests/postgres_ingestion_runs.rs @@ -39,7 +39,8 @@ use registry_breg::postgres::{ RegistryStateTestIdentity, }; use registry_breg_client::{ - BRegBatchOperation, BRegIngestionChunk, BRegIngestionRunRequest, BRegIngestionRunStatus, + BRegAccessReason, BRegBatchBuilder, BRegBatchOperation, BRegCreateRequest, BRegIdempotencyKey, + BRegIngestionChunk, BRegIngestionRunRequest, BRegIngestionRunStatus, BaseRegistryClientError, BREG_INGESTION_CHUNK_ALGORITHM_VERSION, }; use registry_platform_audit::AuditProfile; @@ -4454,6 +4455,271 @@ async fn ingestion_batch_requires_the_reference_targets_reason_atomically() { harness.database.cleanup().await; } +/// Exercise a source Batch profile whose own reason requirement gates every +/// ingestion operation, independently of any reference-target grant. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn source_batch_requires_a_reason_on_each_ingestion_exchange() { + async fn exchange( + app: &axum::Router, + claims: &VerifiedRequestClaims, + method: Method, + uri: &str, + body: Option, + status: StatusCode, + ) -> Value { + let mut headers = Vec::new(); + let body = body.map_or_else(Vec::new, |value| { + headers.push(("content-type", "application/json")); + serde_json::to_vec(&value).unwrap() + }); + let refused = send( + app, + method.clone(), + uri, + Some(claims.clone()), + &headers, + body.clone(), + ) + .await; + assert_eq!(refused.status(), StatusCode::BAD_REQUEST, "{method} {uri}"); + assert_eq!( + body_json(refused).await["code"], + "request.access-reason-required" + ); + + let reason = URL_SAFE_NO_PAD.encode("Verify the announced input 🧭"); + headers.push(("registry-access-reason", reason.as_str())); + let allowed = send( + app, + method.clone(), + uri, + Some(claims.clone()), + &headers, + body, + ) + .await; + assert_eq!(allowed.status(), status, "{method} {uri}"); + body_json(allowed).await + } + + let mut source: Value = serde_json::from_str(&format!("{FIXTURE_HEAD}{FIXTURE_TAIL}")).unwrap(); + source["accessProfiles"]["operator"]["requireAccessReason"] = json!(true); + let project = parse_project_json(&serde_json::to_vec(&source).unwrap()).unwrap(); + let registry = compile_project(&project, &[], CompileProfile::Authoring).unwrap(); + let harness = IngestionHarness::from_registry(Arc::new(registry)).await; + let claims = operator_claims(PRINCIPAL, "zone-a"); + let runs = "/v1/records/widgets/ingestion-runs"; + let chunks = plan_chunks(&announce_items("source-reason", 5), 3); + let created = exchange( + &harness.app, + &claims, + Method::POST, + runs, + Some(run_body( + "create", + &harness.identity.schema_fingerprint, + &chunks, + )), + StatusCode::CREATED, + ) + .await; + let run_id = created["run"]["runId"].as_str().unwrap(); + let listed = exchange( + &harness.app, + &claims, + Method::GET, + runs, + None, + StatusCode::OK, + ) + .await; + assert_eq!(listed["runs"][0]["runId"], run_id); + let run = format!("{runs}/{run_id}"); + let read = exchange( + &harness.app, + &claims, + Method::GET, + &run, + None, + StatusCode::OK, + ) + .await; + assert_eq!(read["run"]["nextChunkIndex"], 0); + let chunk = format!("{run}/chunks"); + let submitted = exchange( + &harness.app, + &claims, + Method::POST, + &chunk, + Some(chunk_body(&chunks, 0)), + StatusCode::OK, + ) + .await; + assert_eq!(submitted["run"]["nextChunkIndex"], 1); + let receipt = exchange( + &harness.app, + &claims, + Method::GET, + &format!("{chunk}/0/receipt"), + None, + StatusCode::OK, + ) + .await; + assert_eq!(receipt["chunkIndex"], 0); + assert_eq!(receipt["digest"], submitted["receipt"]["digest"]); + assert_eq!(receipt["batch"], submitted["receipt"]["batch"]); + assert_eq!(receipt["replayed"], true); + let cancelled = exchange( + &harness.app, + &claims, + Method::POST, + &format!("{run}/cancel"), + None, + StatusCode::OK, + ) + .await; + assert_eq!(cancelled["run"]["status"], "cancelled"); + assert_eq!(durable_widget_count(&harness).await, 3); + + let document = body_json( + harness + .get_json("/openapi.json?accessProfile=operator", &claims) + .await, + ) + .await; + let paths = document["paths"].as_object().unwrap(); + let mut ingestion_operations = 0; + for operation in paths + .values() + .flat_map(|methods| methods.as_object().unwrap().values()) + { + if operation["x-registry-operation"] + .as_str() + .is_some_and(|marker| marker.starts_with("ingestion")) + { + let parameters = operation["parameters"].as_array().unwrap(); + let reason = parameters + .iter() + .find(|parameter| parameter["name"] == "Registry-Access-Reason") + .unwrap(); + assert_eq!(reason["required"], true); + ingestion_operations += 1; + } + } + assert_eq!(ingestion_operations, 6); + let parameters = paths["/v1/records/widgets:batch"]["post"]["parameters"] + .as_array() + .unwrap(); + let reason = parameters + .iter() + .find(|parameter| parameter["name"] == "Registry-Access-Reason") + .unwrap(); + assert_eq!(reason["in"], "header"); + assert_eq!(reason["required"], false); + assert_eq!( + reason["schema"], + json!({ + "type":"string", "minLength":1, "maxLength":684, "pattern":"^[A-Za-z0-9_-]+$" + }) + ); + harness.database.cleanup().await; +} + +/// Exercise both SDK transport paths against the same source-authorized Batch +/// and reason-required reference target through the PostGIS-backed HTTP router. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn sdk_batch_and_ingestion_carry_the_references_required_reason() { + let (harness, items) = reason_required_reference_batch().await; + let http = ClientHttp::start(harness.app.clone(), operator_claims(PRINCIPAL, "zone-a")).await; + let client = &http.client; + let metadata = client + .registry_contract(Some("operator")) + .await + .unwrap() + .value; + let binding = metadata.select_batch("widget", "operator").unwrap(); + let mut batch = BRegBatchBuilder::new(&binding); + for item in &items { + let mut data = item["data"].as_object().unwrap().clone(); + data.insert( + "label".to_owned(), + json!(format!("direct-{}", data["label"].as_str().unwrap())), + ); + batch = batch + .create(&BRegCreateRequest::new(data).unwrap()) + .unwrap(); + } + let batch = batch.build().unwrap(); + let key = BRegIdempotencyKey::parse("sdk-direct-reason-batch").unwrap(); + + let chunks = plan_chunks(&items, 3); + let request = BRegIngestionRunRequest::builder() + .operation(BRegBatchOperation::Create) + .profile("operator") + .unwrap() + .package_revision(registry_breg::postgres::test_package_digest( + PACKAGE_REVISION, + )) + .unwrap() + .schema_fingerprint(&harness.identity.schema_fingerprint) + .unwrap() + .input_digest(&chunks.input_digest) + .unwrap() + .input_length(chunks.input_length as u64) + .item_count(chunks.item_count as u64) + .unwrap() + .chunk_count(chunks.chunk_count as u64) + .unwrap() + .chunk_algorithm_version(BREG_INGESTION_CHUNK_ALGORITHM_VERSION) + .unwrap() + .build() + .unwrap(); + let run = client + .create_ingestion_run("widgets", &request) + .await + .unwrap() + .value; + let run_id = run.run_id(); + let chunk = BRegIngestionChunk::new(0, items, chunks.prefix_digests[0].as_str()).unwrap(); + + assert!(matches!( + client.batch_records(&binding, &batch, &key).await, + Err(BaseRegistryClientError::Problem { status: 409, .. }) + )); + assert!(matches!( + client + .submit_ingestion_chunk("widgets", run_id, &chunk, "operator") + .await, + Err(BaseRegistryClientError::Problem { status: 412, .. }) + )); + assert_no_reference_batch_commit(&harness).await; + + let reason = BRegAccessReason::new("Link the authorized ledger").unwrap(); + let direct = client + .batch_records_with_access_reason(&binding, &batch, &key, Some(&reason)) + .await + .unwrap() + .value; + assert_eq!(direct.results().len(), 2); + let submitted = client + .submit_ingestion_chunk_with_access_reason( + "widgets", + run_id, + &chunk, + "operator", + Some(&reason), + ) + .await + .unwrap() + .value; + assert!(submitted.run().complete()); + assert_eq!(submitted.receipt().batch().results().len(), 2); + assert_eq!(durable_widget_count(&harness).await, 4); + + drop(http); + harness.database.cleanup().await; +} + async fn reason_required_reference_batch() -> (IngestionHarness, Vec) { let project = parse_project_json(&serde_json::to_vec(&widget_project_with_ledger_reference()).unwrap()) diff --git a/crates/registry-breg/tests/postgres_list_page_plans.rs b/crates/registry-breg/tests/postgres_list_page_plans.rs index dade7fa7b1..0ce5e9a90a 100644 --- a/crates/registry-breg/tests/postgres_list_page_plans.rs +++ b/crates/registry-breg/tests/postgres_list_page_plans.rs @@ -200,7 +200,7 @@ impl Fixture { let (status, mut body) = send( &self.app, &format!( - "/v1/records/assets?accessProfile=reader&$filter=kind%20eq%20'kind-1'{order}&$top={PAGE}" + "/v1/records/assets?accessProfile=reader&$filter=kind%20eq%20'kind-1'{order}&limit={PAGE}" ), ) .await; @@ -217,7 +217,7 @@ impl Fixture { self.take_plan(); let (status, next) = send( &self.app, - &format!("/v1/records/assets?accessProfile=reader&$skiptoken={cursor}"), + &format!("/v1/records/assets?accessProfile=reader&cursor={cursor}"), ) .await; assert_eq!(status, StatusCode::OK, "{next}"); @@ -230,7 +230,7 @@ impl Fixture { while let Some(cursor) = body["pageInfo"]["nextCursor"].as_str().map(str::to_owned) { let (status, next) = send( &self.app, - &format!("/v1/records/assets?accessProfile=reader&$skiptoken={cursor}"), + &format!("/v1/records/assets?accessProfile=reader&cursor={cursor}"), ) .await; assert_eq!(status, StatusCode::OK, "{next}"); diff --git a/crates/registry-breg/tests/postgres_membership_access.rs b/crates/registry-breg/tests/postgres_membership_access.rs index 23b65d599a..84be848426 100644 --- a/crates/registry-breg/tests/postgres_membership_access.rs +++ b/crates/registry-breg/tests/postgres_membership_access.rs @@ -221,7 +221,7 @@ async fn real_postgres_membership_reads_recheck_live_membership_and_hide_process let (_, _, page) = send( &app, Method::GET, - &format!("/v1/records/{route}?accessProfile=member&$top=1&$count=true"), + &format!("/v1/records/{route}?accessProfile=member&limit=1&$count=true"), Value::Null, None, &member, @@ -232,7 +232,7 @@ async fn real_postgres_membership_reads_recheck_live_membership_and_hide_process let (_, _, snapshot) = send( &app, Method::GET, - &format!("/v1/records/{route}:snapshot?accessProfile=member&$count=true&$top=1"), + &format!("/v1/records/{route}:snapshot?accessProfile=member&$count=true&limit=1"), Value::Null, None, &member, @@ -353,11 +353,9 @@ async fn real_postgres_membership_reads_recheck_live_membership_and_hide_process ); for uri in [ format!("/v1/records/{route}?accessProfile=member&$count=true"), - format!("/v1/records/{route}?accessProfile=member&$skiptoken={cursor}"), + format!("/v1/records/{route}?accessProfile=member&cursor={cursor}"), format!("/v1/records/{route}:snapshot?accessProfile=member&$count=true"), - format!( - "/v1/records/{route}:snapshot?accessProfile=member&$skiptoken={snapshot_cursor}" - ), + format!("/v1/records/{route}:snapshot?accessProfile=member&cursor={snapshot_cursor}"), ] { let (status, _, body) = send(&app, Method::GET, &uri, Value::Null, None, &member).await; assert_eq!(status, StatusCode::OK, "{body}"); diff --git a/crates/registry-breg/tests/postgres_mutation.rs b/crates/registry-breg/tests/postgres_mutation.rs index 1c860ce21e..b144d4dc63 100644 --- a/crates/registry-breg/tests/postgres_mutation.rs +++ b/crates/registry-breg/tests/postgres_mutation.rs @@ -3743,8 +3743,8 @@ async fn record_and_query_refusals_name_only_fixed_members_and_admitted_fields() assert_identical_problems(&filter_unknown, &filter_withheld); let filter_syntax = problem(query("/v1/records/widgets?$filter=label%20eq").await).await; assert_query_invalid_at(&filter_syntax, Some("$filter")); - let top = problem(query("/v1/records/widgets?$top=0").await).await; - assert_query_invalid_at(&top, Some("$top")); + let limit = problem(query("/v1/records/widgets?limit=0").await).await; + assert_query_invalid_at(&limit, Some("limit")); let orderby = problem(query("/v1/records/widgets?$orderby=secret").await).await; assert_query_invalid_at(&orderby, Some("$orderby")); let invented = problem(query("/v1/records/widgets?noSuchParameter=1").await).await; diff --git a/crates/registry-breg/tests/postgres_proposal.rs b/crates/registry-breg/tests/postgres_proposal.rs index c24c9f9594..ae39a50fa0 100644 --- a/crates/registry-breg/tests/postgres_proposal.rs +++ b/crates/registry-breg/tests/postgres_proposal.rs @@ -2215,7 +2215,8 @@ async fn proposal_list_query_refusals_follow_authority_and_audit_concealment() { ("limit=0", "limit"), ("cursor=not-a-uuid", "cursor"), ("owner=another", "owner"), - ("top=1", "top"), + ("top=1", "query"), + ("limit=1&%74op=2", "query"), ] { let response = reqwest::get(format!( "{}/v1/proposals?accessProfile=clerk&{query}", diff --git a/crates/registry-breg/tests/postgres_proposal_messages.rs b/crates/registry-breg/tests/postgres_proposal_messages.rs index 2bfaa0a7b8..85823afed0 100644 --- a/crates/registry-breg/tests/postgres_proposal_messages.rs +++ b/crates/registry-breg/tests/postgres_proposal_messages.rs @@ -782,11 +782,12 @@ async fn the_applicant_and_the_reviewer_exchange_messages_and_an_unread_answer_i .as_str() .expect("a second page") .to_owned(); + let encoded_cursor: String = cursor.bytes().map(|byte| format!("%{byte:02X}")).collect(); let (status, _, rest) = request( &fixture, citizen(CITIZEN), "GET", - &format!("/v1/proposals/{id}/messages?accessProfile=citizen&limit=1&after={cursor}"), + &format!("/v1/proposals/{id}/messages?accessProfile=citizen&%6Cimit=%2B1&%63ursor={encoded_cursor}"), None, None, Value::Null, @@ -916,6 +917,124 @@ async fn the_owner_and_the_subject_post_and_read_and_a_neighbour_gets_not_found( fixture.finish().await; } +#[tokio::test] +async fn thread_page_faults_follow_visibility_and_are_audited() { + let fixture = fixture().await; + let id = filed( + &fixture, + citizen(CITIZEN), + "apply-for-licence", + CITIZEN, + "page-faults", + ) + .await; + let unknown = Uuid::new_v4(); + for (query, code, location) in [ + ("limit=1&%6Cimit=2", "request.invalid", "limit"), + ("limit=1&limit=2", "request.invalid", "limit"), + ("limit=%GG", "request.invalid", "limit"), + ("limit=0", "request.invalid", "limit"), + ("limit=51", "request.invalid", "limit"), + ("cursor=01", "query.cursor-invalid", "cursor"), + ("cursor=%2B1", "query.cursor-invalid", "cursor"), + ("cursor=1&%63ursor=2", "request.invalid", "cursor"), + ("cursor=opaque-canary", "query.cursor-invalid", "cursor"), + ("cursor=1&after=opaque-canary", "query.invalid", "query"), + ("cursor=1&%61fter=%GG", "query.invalid", "query"), + ("malformed-canary", "query.invalid", "query"), + ] { + let path = |id| format!("/v1/proposals/{id}/messages?{query}&accessProfile=citizen"); + let concealed = |mut body: Value| { + body.as_object_mut().unwrap().remove("traceId"); + body + }; + let (status, _, hidden) = request( + &fixture, + citizen(NEIGHBOUR), + "GET", + &path(id), + None, + None, + Value::Null, + ) + .await; + assert_eq!(status, StatusCode::NOT_FOUND, "{query}: {hidden}"); + let (status, _, missing) = request( + &fixture, + citizen(NEIGHBOUR), + "GET", + &path(unknown), + None, + None, + Value::Null, + ) + .await; + assert_eq!(status, StatusCode::NOT_FOUND, "{query}: {missing}"); + assert_eq!(hidden["code"], "resource.not-found"); + assert_eq!(concealed(hidden), concealed(missing)); + + let audit_start = fixture.audit_capture.entries().len(); + let (status, _, fault) = request( + &fixture, + citizen(CITIZEN), + "GET", + &path(id), + None, + None, + Value::Null, + ) + .await; + assert_eq!(status, StatusCode::BAD_REQUEST, "{query}: {fault}"); + assert_eq!(fault["code"], code, "{query}: {fault}"); + assert_eq!(fault["fieldPath"], location, "{query}: {fault}"); + assert!(!fault.to_string().contains("canary"), "{fault}"); + let entries = fixture.audit_capture.entries(); + let entries = &entries[audit_start..]; + assert!( + entries.iter().any(|entry| { + let record = &entry["record"]; + record["traceId"] == fault["traceId"] + && record["phase"] == "refusal" + && record["operationId"] == "proposals.apply-for-licence.message" + && record["selectedAccessProfile"] == "citizen" + }), + "{entries:?}" + ); + let audit = serde_json::to_string(entries).unwrap(); + assert!(!audit.contains("opaque-canary") && !audit.contains("malformed-canary")); + } + let (_, etag, _) = get(&fixture, citizen(CITIZEN), id).await; + for (suffix, location) in [("", "/text"), ("/read", "/through")] { + let (status, _, fault) = request( + &fixture, + citizen(CITIZEN), + "POST", + &format!("/v1/proposals/{id}/messages{suffix}?accessProfile=citizen"), + etag.as_deref(), + Some("missing-thread-body-member"), + json!({}), + ) + .await; + assert_eq!(status, StatusCode::BAD_REQUEST, "{fault}"); + assert_eq!(fault["code"], "request.invalid", "{fault}"); + assert_eq!(fault["fieldPath"], location, "{fault}"); + } + fixture.audit_capture.fail_after(0); + let (status, _, fault) = request( + &fixture, + citizen(CITIZEN), + "GET", + &format!("/v1/proposals/{id}/messages?accessProfile=citizen&limit=1&limit=2"), + None, + None, + Value::Null, + ) + .await; + assert_eq!(status, StatusCode::SERVICE_UNAVAILABLE, "{fault}"); + assert!(fault.get("fieldPath").is_none(), "{fault}"); + fixture.finish().await; +} + /// D6: an Action without review carries a thread. The office talks to the /// applicant and applies by hand; applying closes the thread for writes and /// leaves it readable. @@ -1866,6 +1985,20 @@ async fn bounded_office_staff_get_the_same_answer_for_a_hidden_proposal_and_an_u None, Value::Null, ), + ( + "GET", + format!("/v1/proposals/{target}/messages?limit=1&limit=2&accessProfile=district"), + None, + None, + Value::Null, + ), + ( + "GET", + format!("/v1/proposals/{target}/messages?cursor=%GG&accessProfile=district"), + None, + None, + Value::Null, + ), ( "POST", format!("/v1/proposals/{target}/messages/read?accessProfile=district"), diff --git a/crates/registry-breg/tests/postgres_read.rs b/crates/registry-breg/tests/postgres_read.rs index cf03dfac4b..eb3fb019a5 100644 --- a/crates/registry-breg/tests/postgres_read.rs +++ b/crates/registry-breg/tests/postgres_read.rs @@ -135,7 +135,7 @@ async fn benchmark_audited_record_read(workload: ReadBenchmark) { ReadBenchmark::ListCountContinuation => { let first = send( &app, - "/v1/records/widgets?$select=label&$filter=jurisdiction%20in%20('zone-b','zone-a')&$orderby=ordinal&$top=100&$count=true", + "/v1/records/widgets?$select=label&$filter=jurisdiction%20in%20('zone-b','zone-a')&$orderby=ordinal&limit=100&$count=true", Some(read_claims(["zone-a"])), ) .await; @@ -177,7 +177,7 @@ async fn benchmark_audited_record_read(workload: ReadBenchmark) { }); ( "audited_record_list_count_continuation", - format!("/v1/records/widgets?$skiptoken={cursor}"), + format!("/v1/records/widgets?cursor={cursor}"), serde_json::to_vec(&expected).expect("expected list response serializes"), ) } @@ -429,7 +429,7 @@ async fn real_postgres_read_is_authorized_bounded_minimized_and_audit_gated() { let repeated_in = send( &app, - "/v1/records/widgets?$select=label&$filter=jurisdiction%20in%20('zone-b','zone-a')&$top=2", + "/v1/records/widgets?$select=label&$filter=jurisdiction%20in%20('zone-b','zone-a')&limit=2", Some(read_claims(["zone-a"])), ) .await; @@ -483,7 +483,7 @@ async fn real_postgres_read_is_authorized_bounded_minimized_and_audit_gated() { } let vocabulary_search = send( &app, - "/v1/records/widgets?$select=jurisdiction&$filter=contains(jurisdiction,'ONE-A')&$top=1", + "/v1/records/widgets?$select=jurisdiction&$filter=contains(jurisdiction,'ONE-A')&limit=1", Some(read_claims(["zone-a"])), ) .await; @@ -522,7 +522,7 @@ async fn real_postgres_read_is_authorized_bounded_minimized_and_audit_gated() { let continuation = send( &app, - &format!("/v1/records/widgets?$skiptoken={next_cursor}"), + &format!("/v1/records/widgets?cursor={next_cursor}"), Some(read_claims(["zone-a"])), ) .await; @@ -550,7 +550,7 @@ async fn real_postgres_read_is_authorized_bounded_minimized_and_audit_gated() { let tampered = String::from_utf8(tampered).expect("cursor remains UTF-8"); let refused_cursor = send( &app, - &format!("/v1/records/widgets?$skiptoken={tampered}"), + &format!("/v1/records/widgets?cursor={tampered}"), Some(read_claims(["zone-a"])), ) .await; @@ -793,9 +793,48 @@ async fn real_postgres_temporal_keyset_and_cursor_binding_edges_are_enforced() { assert!(current["items"][0]["domainData"].get("valid-to").is_none()); assert!(!current.to_string().contains(TEMPORAL_OTHER_BOUNDARY_RECORD)); + let as_of_route = "/v1/records/assignments:as-of"; + let at = "2020-05-31T23:59:59Z"; + let claims = Some(read_claims(["zone-a", "zone-b"])); + let first = send( + &app, + &format!( + "{as_of_route}?accessProfile=operator&asOf={at}&$select=label&$orderby=label&limit=1" + ), + claims.clone(), + ) + .await; + assert_eq!(first.status(), StatusCode::OK); + let first = body_json(first).await; + assert_eq!(first["meta"]["asOf"], at); + let cursor = first["pageInfo"]["nextCursor"].as_str().unwrap(); + let continuation = format!("{as_of_route}?accessProfile=operator&cursor={cursor}"); + let second = send(&app, &continuation, claims.clone()).await; + assert_eq!(second.status(), StatusCode::OK); + let second = body_json(second).await; + assert_eq!(second["meta"]["asOf"], at); + assert!(second["pageInfo"]["nextCursor"].is_null()); + assert_eq!( + second["items"][0]["domainData"], + json!({"label": "lease-b"}) + ); + assert_ids(first, &[TEMPORAL_OLD_RECORD]); + assert_ids(second, &[TEMPORAL_OTHER_BOUNDARY_RECORD]); + + let override_time = send( + &app, + &format!("{continuation}&asOf=2020-06-01T00:00:00Z"), + claims, + ) + .await; + assert_eq!(override_time.status(), StatusCode::BAD_REQUEST); + let problem = body_json(override_time).await; + assert_eq!(problem["code"], "query.invalid"); + assert_eq!(problem["fieldPath"], "cursor"); + let sorted_first = send( &app, - "/v1/records/widgets?$select=label,rank&$filter=startswith(label,'sort-key-')&$orderby=rank&$top=2", + "/v1/records/widgets?$select=label,rank&$filter=startswith(label,'sort-key-')&$orderby=rank&limit=2", Some(read_claims(["zone-a"])), ) .await; @@ -811,7 +850,7 @@ async fn real_postgres_temporal_keyset_and_cursor_binding_edges_are_enforced() { .to_owned(); let sorted_second = send( &app, - &format!("/v1/records/widgets?$skiptoken={sorted_second_cursor}"), + &format!("/v1/records/widgets?cursor={sorted_second_cursor}"), Some(read_claims(["zone-a"])), ) .await; @@ -828,7 +867,7 @@ async fn real_postgres_temporal_keyset_and_cursor_binding_edges_are_enforced() { .to_owned(); let sorted_third = send( &app, - &format!("/v1/records/widgets?$skiptoken={sorted_third_cursor}"), + &format!("/v1/records/widgets?cursor={sorted_third_cursor}"), Some(read_claims(["zone-a"])), ) .await; @@ -839,7 +878,7 @@ async fn real_postgres_temporal_keyset_and_cursor_binding_edges_are_enforced() { let counted_first = send( &app, - "/v1/records/widgets?$select=label,rank&$filter=startswith(label,'sort-key-')&$orderby=rank&$top=2&$count=true", + "/v1/records/widgets?$select=label,rank&$filter=startswith(label,'sort-key-')&$orderby=rank&limit=2&$count=true", Some(read_claims(["zone-a"])), ) .await; @@ -859,7 +898,7 @@ async fn real_postgres_temporal_keyset_and_cursor_binding_edges_are_enforced() { .to_owned(); let counted_second = send( &app, - &format!("/v1/records/widgets?$skiptoken={counted_cursor}"), + &format!("/v1/records/widgets?cursor={counted_cursor}"), Some(read_claims(["zone-a"])), ) .await; @@ -883,29 +922,29 @@ async fn real_postgres_temporal_keyset_and_cursor_binding_edges_are_enforced() { let replay_cursor = next_cursor( &app, - "/v1/records/widgets?$select=label,rank&$filter=startswith(label,'sort-key-')&$orderby=rank&$top=2", + "/v1/records/widgets?$select=label,rank&$filter=startswith(label,'sort-key-')&$orderby=rank&limit=2", Some(read_claims(["zone-a"])), ) .await; for (uri, claims) in [ ( - format!("/v1/records/widgets?$skiptoken={replay_cursor}"), + format!("/v1/records/widgets?cursor={replay_cursor}"), read_claims_with(PRINCIPAL_CANARY, "audit-review", ["zone-a"]), ), ( - format!("/v1/records/widgets?$skiptoken={replay_cursor}"), + format!("/v1/records/widgets?cursor={replay_cursor}"), read_claims_with("other-principal-value", "case-management", ["zone-a"]), ), ( - format!("/v1/records/widgets?$skiptoken={replay_cursor}"), + format!("/v1/records/widgets?cursor={replay_cursor}"), read_claims_with(PRINCIPAL_CANARY, "case-management", ["zone-b"]), ), ( - format!("/v1/records/widgets?accessProfile=auditor&$skiptoken={replay_cursor}"), + format!("/v1/records/widgets?accessProfile=auditor&cursor={replay_cursor}"), read_claims(["zone-a"]), ), ( - format!("/v1/records/assignments?$skiptoken={replay_cursor}"), + format!("/v1/records/assignments?cursor={replay_cursor}"), read_claims(["zone-a"]), ), ] { @@ -928,14 +967,14 @@ async fn real_postgres_temporal_keyset_and_cursor_binding_edges_are_enforced() { ); assert_cursor_invalid( &package_changed_app, - &format!("/v1/records/widgets?$skiptoken={replay_cursor}"), + &format!("/v1/records/widgets?cursor={replay_cursor}"), Some(read_claims(["zone-a"])), ) .await; let projection_cursor = next_cursor( &app, - "/v1/records/widgets?$select=label,amount&$filter=startswith(label,'label-')&$orderby=ordinal&$top=2", + "/v1/records/widgets?$select=label,amount&$filter=startswith(label,'label-')&$orderby=ordinal&limit=2", Some(read_claims(["zone-a"])), ) .await; @@ -952,7 +991,7 @@ async fn real_postgres_temporal_keyset_and_cursor_binding_edges_are_enforced() { ); assert_cursor_invalid( &projection_changed_app, - &format!("/v1/records/widgets?$skiptoken={projection_cursor}"), + &format!("/v1/records/widgets?cursor={projection_cursor}"), Some(read_claims(["zone-a"])), ) .await; @@ -974,7 +1013,7 @@ async fn real_postgres_temporal_keyset_and_cursor_binding_edges_are_enforced() { ); assert_cursor_invalid( &changed_app, - &format!("/v1/records/widgets?$skiptoken={replay_cursor}"), + &format!("/v1/records/widgets?cursor={replay_cursor}"), Some(read_claims(["zone-a"])), ) .await; @@ -993,13 +1032,13 @@ async fn real_postgres_temporal_keyset_and_cursor_binding_edges_are_enforced() { ); let expired_cursor = next_cursor( &expiring_app, - "/v1/records/widgets?$select=label&$orderby=ordinal&$top=1", + "/v1/records/widgets?$select=label&$orderby=ordinal&limit=1", Some(read_claims(["zone-a"])), ) .await; assert_cursor_invalid( &expiring_app, - &format!("/v1/records/widgets?$skiptoken={expired_cursor}"), + &format!("/v1/records/widgets?cursor={expired_cursor}"), Some(read_claims(["zone-a"])), ) .await; @@ -1506,6 +1545,19 @@ async fn seed_records( ] { insert_assignment_row(transaction.transaction_for_test(), registry, row).await; } + } else { + insert_assignment_row( + transaction.transaction_for_test(), + registry, + AssignmentRow { + record_id: TEMPORAL_OTHER_BOUNDARY_RECORD, + jurisdiction, + label: "lease-b", + valid_from: "2020-01-01T00:00:00Z", + valid_to: None, + }, + ) + .await; } transaction .commit() diff --git a/crates/registry-breg/tests/postgres_read_dependencies.rs b/crates/registry-breg/tests/postgres_read_dependencies.rs index 68e440203e..a4ec61f56e 100644 --- a/crates/registry-breg/tests/postgres_read_dependencies.rs +++ b/crates/registry-breg/tests/postgres_read_dependencies.rs @@ -259,7 +259,7 @@ async fn exercise_read_dependencies(case: &str, invalid_population: bool, active // still reach their derived relation, including its cardinality guard. for query in [ "/v1/records/entries?$select=code&$filter=not%20(population%20lt%2032%20or%20population%20gt%2032)&$count=true", - "/v1/records/entries?$select=code&$orderby=population&$top=1", + "/v1/records/entries?$select=code&$orderby=population&limit=1", ] { let (status, body) = send(&app, query, false, "visible").await; if invalid_population { @@ -279,7 +279,7 @@ async fn exercise_combined_dependencies(app: &axum::Router, plans: &Mutex