diff --git a/clients/typescript/generate.ts b/clients/typescript/generate.ts index 9f04567b79..5542ca38a5 100644 --- a/clients/typescript/generate.ts +++ b/clients/typescript/generate.ts @@ -179,6 +179,16 @@ const bregPatchValue = new RegExp( 'u', ) +const bregPatchOperationValue = new RegExp( + '^/paths/~1v1~1records~1' + record + + '(?:~1\\{record_id\\}/patch/requestBody/content/application~1json-patch\\+json/schema/items' + + '|(?::batch|~1ingestion-runs~1\\{run_id\\}~1chunks)/post/requestBody/content/application~1json/schema' + + '/properties/items/items/oneOf/[01]/properties/patch/items)' + + '/oneOf/[0-3]/properties/value$', + 'u', +) +const bregAsOfRoute = new RegExp('^/v1/records/' + record + ':as-of$', 'u') + const isJson = (media: string) => /(?:\/json|\+json)(?:;|$)/u.test(media) const members = (value: Node | undefined): [string, any][] => Object.entries(value ?? {}) const identifier = (value: string) => value.replace(/[^a-zA-Z0-9_]/gu, '_') @@ -287,6 +297,22 @@ export function generate(source: string, settings: Settings = {}): string { lookup(target) return target } + function allowsBregPatchValue(pointer: string): boolean { + if (bregPatchValue.test(pointer)) return true + if (!bregPatchOperationValue.test(pointer)) return false + const branchPointer = pointer.slice(0, -'/properties/value'.length) + const batchEnd = branchPointer.indexOf('/properties/patch/items/') + if (batchEnd !== -1) { + const item = lookup(branchPointer.slice(0, batchEnd)) + if (item.properties?.operation?.const !== 'patch' + || !Array.isArray(item.required) || !item.required.includes('operation')) return false + } + const branch = lookup(branchPointer) + const operation = branch.properties?.op?.const + return (operation === 'add' || operation === 'replace' || operation === 'test') + && branch.properties?.path?.type === 'string' + && Array.isArray(branch.required) && ['op', 'path', 'value'].every(name => branch.required.includes(name)) + } function audit(schema: Node | boolean, pointer: string): void { if (rules.has(pointer)) return if (schema === false) { rules.set(pointer, false); return } @@ -300,7 +326,7 @@ export function generate(source: string, settings: Settings = {}): string { } } if (!keys.some(key => keywords.has(key))) { - if (!allowed.has(pointer) && !(breg && bregPatchValue.test(pointer))) { + if (!allowed.has(pointer) && !(breg && allowsBregPatchValue(pointer))) { fail(pointer, 'unconstrained schema is outside the reviewed allowlist') } used.add(pointer) @@ -613,10 +639,14 @@ export function generate(source: string, settings: Settings = {}): string { parameterMap.set(value.in + ':' + value.name, { value, pointer: at }) }) } + const exclusiveAsOf = breg && method === 'get' && bregAsOfRoute.test(path) + && parameterMap.has('query:asOf') && parameterMap.has('query:cursor') const args: Node = {} let requiredOptions = false for (const [location, group] of [['path', 'path'], ['query', 'query'], ['header', 'headers']] as const) { const fields: string[] = [] + const continuationFields: string[] = [] + const asOfQuery = exclusiveAsOf && location === 'query' let required = false for (const { value, pointer: at } of parameterMap.values()) { if (value.in !== location) continue @@ -629,12 +659,19 @@ export function generate(source: string, settings: Settings = {}): string { } const declaredType = describe(value.schema, child(at, 'schema')) const profileType = breg && value.name === 'accessProfile' && profiles?.length ? profile : undefined - const requiredParameter = value.required === true && !(location === 'query' && value.name === 'accessProfile') - fields.push(quote(value.name) + (requiredParameter ? '' : '?') + ': ' + (profileType ?? declaredType)) + const field = quote(value.name) + const type = profileType ?? declaredType + const requiredParameter = (asOfQuery && value.name === 'asOf') || + (value.required === true && !(location === 'query' && value.name === 'accessProfile')) + fields.push(asOfQuery && value.name === 'cursor' ? field + '?: never' + : field + (requiredParameter ? '' : '?') + ': ' + type) + if (asOfQuery) continuationFields.push(value.name === 'cursor' ? field + ': ' + type + : field + '?: ' + (value.name === 'accessProfile' ? type : 'never')) required ||= requiredParameter } if (fields.length) { args[group] = '{ ' + fields.join('; ') + ' }' + if (asOfQuery) args[group] += ' | { ' + continuationFields.join('; ') + ' }' inputs.push('{ ' + group + (required ? '' : '?') + ': ' + args[group] + ' }') requiredOptions ||= required } diff --git a/clients/typescript/generated/breg-facility.ts b/clients/typescript/generated/breg-facility.ts index a2eb4f0ca8..49f9dcef03 100644 --- a/clients/typescript/generated/breg-facility.ts +++ b/clients/typescript/generated/breg-facility.ts @@ -1,7 +1,11 @@ // Generated for Stack version 0.52.0, client version 0.52.0. -// Source SHA-256 5b60b01c07f05b3d1c776a8f6f43bce555990088ecad7175e60ec16c417cfd39 -// Unconstrained JSON /paths/~1v1~1records~1directory-entries~1{record_id}/patch/requestBody/content/application~1json-patch+json/schema/items/properties/value -// Unconstrained JSON /paths/~1v1~1records~1operators~1{record_id}/patch/requestBody/content/application~1json-patch+json/schema/items/properties/value +// Source SHA-256 d76a73b998a452c8dd084d24caea0f0a21384b4e34b38fa638634c308e48f4bc +// Unconstrained JSON /paths/~1v1~1records~1directory-entries~1{record_id}/patch/requestBody/content/application~1json-patch+json/schema/items/oneOf/0/properties/value +// Unconstrained JSON /paths/~1v1~1records~1directory-entries~1{record_id}/patch/requestBody/content/application~1json-patch+json/schema/items/oneOf/1/properties/value +// Unconstrained JSON /paths/~1v1~1records~1directory-entries~1{record_id}/patch/requestBody/content/application~1json-patch+json/schema/items/oneOf/2/properties/value +// Unconstrained JSON /paths/~1v1~1records~1operators~1{record_id}/patch/requestBody/content/application~1json-patch+json/schema/items/oneOf/0/properties/value +// Unconstrained JSON /paths/~1v1~1records~1operators~1{record_id}/patch/requestBody/content/application~1json-patch+json/schema/items/oneOf/1/properties/value +// Unconstrained JSON /paths/~1v1~1records~1operators~1{record_id}/patch/requestBody/content/application~1json-patch+json/schema/items/oneOf/2/properties/value import { assertClientVersion, type Transport, type Answer, type CallOptions, type JsonValue, type Operation, type Page, type RequestValues, type ResponseVariant, type WireBytes, type WireText } from "../core.ts" import { actionAvailability, type ActionAvailability, type DescribeOptions } from "../core.ts" import { sentence } from "../core.ts" @@ -33,7 +37,7 @@ export interface Operations { "actions.register-facility.invoke": { input: CallOptions & { query?: { "accessProfile"?: "facility-registrar" } } & { headers?: { "traceparent"?: (string) } } & ({ body: Schema_action_register_facility_invoke_input }) & { accept?: "application/json" | "*/*" }; required: true; output: Schema_action_register_facility_invoke_response } "actions.register-facility.availability": { input: CallOptions & { query?: { "accessProfile"?: "facility-registrar" } } & { headers?: { "traceparent"?: (string) } } & ({ body: Schema_action_register_facility_availability_input }) & { accept?: "application/json" | "*/*" }; required: true; output: Schema_action_register_facility_availability_response } "proposals.list": { input: CallOptions & { query?: { "accessProfile"?: "facility-correction-applier" | "facility-correction-author"; "action"?: (string); "owner"?: "caller"; "target"?: (string); "state"?: ("draft" | "submitted" | "applied" | "cancelled" | "rejected"); "turn"?: ("party" | "official" | "nobody"); "cursor"?: (string); "limit"?: (number); "pendingManualApplication"?: (boolean) } } & { accept?: "application/json" | "*/*" }; required: false; output: ({ "items": (Array<({ "actionId": (string); "actionRevision": (string); "application"?: ({ "applicationId": (string); "effectDigest": (string); "resultLinks": (Array<({ "recordId": (string); "recordType": (string); "revision": (number) })>); "submissionVersion": (number) }); "applicationStatus"?: ({ "automaticRetry"?: ({ "attempts": (number); "maximumAttempts": (number); "scheduled": (boolean) }); "mode": ("automatic" | "manual"); "reason"?: ("package-changed" | "dependency-outage" | "lease-expired" | "application-refused" | "attempts-exhausted"); "recovery"?: ("retry" | "rebase" | "revise" | "correct-input"); "state": ("awaiting-review" | "pending" | "applying" | "blocked" | "applied" | "cancelled" | "rejected") }); "asks"?: (Array<({ "answer"?: ({ "additions": (Array<(string)>); "answeredAt": (string); "formEntries"?: (Array<(string)>); "text"?: (string) }); "askedAt": (string); "dueAt"?: (string); "id": (string); "links": ({ "answer"?: ({ "accessProfile": (string); "availability": ({ "available": (boolean); "observedRevision": (number); "reason"?: ("pending-review" | "review-rejected" | "review-changes-requested" | "review-ended" | "stale-revision" | "package-changed" | "dependency-outage" | "invalid-input" | "already-applied" | "limit-reached" | "application-pending" | "attachment-required" | "attachment-pending" | "ask-answered" | "ask-closed" | "ask-due-passed"); "recovery"?: ("refresh" | "revise" | "retry" | "rebase" | "correct-input" | "receipt-only") }); "ifMatch": (string); "method": "POST"; "operation": "answer"; "path": (string) }) }); "state": ("open" | "answered" | "expired" | "closed"); "text": (string); "wants": (Array<(({ "kind": ("answer" | "document") }) | ({ "form": (string); "kind": "form" }))>) })>); "attachments"?: (Record); "id": (string); "links": (Record); "maximumBytes": (number); "required": (boolean); "value"?: ({ "byteSize": (number); "contentType": (string); "sha256": (string); "submissionVersion": (number); "uploadedAt"?: (string); "verificationStatus": ("notRequired" | "pending" | "approved" | "rejected") }) })>); "blockedReason"?: ("package-changed"); "createdAt"?: (string); "decision"?: ({ "decidedAt": (string); "publicReason"?: (string); "status": ("approved" | "rejected" | "changes-requested" | "answered") }); "effectDigest"?: (string); "handoffRefusal"?: ({ "code": ("review.initiator-required" | "review.initiator-excluded" | "review.policy-mismatch" | "review.refused") }); "id": (string); "input"?: (Record); "links": (Record); "partyRole"?: ("owner" | "subject"); "revision": (number); "state": ("draft" | "submitted" | "applied" | "cancelled" | "rejected"); "status"?: ("draft" | "awaiting-party" | "in-review" | "approved" | "processing" | "applied" | "rejected" | "cancelled"); "submissionVersion": (number); "title"?: (string); "turn": ("party" | "official" | "nobody") })>); "nextCursor"?: (string) }) } - "proposals.get-review-context-batch": { input: CallOptions & { query: { "accessProfile"?: "proposal-reviewer"; "ids": (Array<(string)>) } } & { accept?: "application/json" | "*/*" }; required: true; output: ({ "items": (Array<(({ "context": ({ "actionId": (string); "actionRevision": (string); "authority"?: (string); "context": ({ "contract": ({ "id": (string); "revision": (string); "schemaDigest": (string) }); "fields": (Record); "reference": (string) }); "effectDigest": (string); "id": (string); "policy"?: ({ "digest": (string); "id": (string); "version": (string) }); "result"?: ({ "availableUntil"?: (string); "completedAt"?: (string); "resultId"?: (string); "state": ("pending" | "approved" | "rejected" | "changes-requested" | "answered" | "cancelled" | "superseded" | "expired") }); "reviewable": (boolean); "revision": (number); "subject": ({ "digest": (string); "id": (string); "source": (string); "subjectType": "proposal"; "version": (string) }); "submissionVersion": (number) }); "id": (string); "status": "visible" }) | ({ "id": (string); "status": "concealed" }))>) }) } + "proposals.get-review-context-batch": { input: CallOptions & { query: { "accessProfile"?: "proposal-reviewer"; "ids": (Array<(string)>) } } & { accept?: "application/json" | "*/*" }; required: true; output: ({ "items": (Array<(({ "context": ({ "actionId": (string); "actionRevision": (string); "authority"?: (string); "context": ({ "contract": ({ "id": (string); "revision": (string); "schemaDigest": (string) }); "fields": (Record); "reference": (string) }); "effectDigest": (string); "id": (string); "policy"?: (({ "id": (string) }) | ({ "digest": (string); "id": (string); "version": (string) })); "result"?: ({ "availableUntil"?: (string); "completedAt"?: (string); "resultId"?: (string); "state": ("pending" | "approved" | "rejected" | "changes-requested" | "answered" | "cancelled" | "superseded" | "expired") }); "reviewable": (boolean); "revision": (number); "subject": ({ "digest": (string); "id": (string); "source": (string); "subjectType": "proposal"; "version": (string) }); "submissionVersion": (number) }); "id": (string); "status": "visible" }) | ({ "id": (string); "status": "concealed" }))>) }) } "proposals.get": { input: CallOptions & { path: { "proposal_id": (string) } } & { query?: { "accessProfile"?: "facility-correction-applier" | "facility-correction-author" } } & { accept?: "application/json" | "*/*" }; required: true; output: ({ "actionId": (string); "actionRevision": (string); "application"?: ({ "applicationId": (string); "appliedAt"?: (string); "appliedBy"?: (string); "effectDigest": (string); "resultLinks": (Array<({ "recordId": (string); "recordType": (string); "revision": (number) })>); "submissionVersion": (number) }); "applicationStatus"?: ({ "automaticRetry"?: ({ "attempts": (number); "maximumAttempts": (number); "scheduled": (boolean) }); "mode": ("automatic" | "manual"); "reason"?: ("package-changed" | "dependency-outage" | "lease-expired" | "application-refused" | "attempts-exhausted"); "recovery"?: ("retry" | "rebase" | "revise" | "correct-input"); "state": ("awaiting-review" | "pending" | "applying" | "blocked" | "applied" | "cancelled" | "rejected") }); "asks"?: (Array<({ "answer"?: ({ "additions": (Array<(string)>); "answeredAt": (string); "formEntries"?: (Array<(string)>); "text"?: (string) }); "askedAt": (string); "dueAt"?: (string); "id": (string); "links": ({ "answer"?: ({ "accessProfile": (string); "availability": ({ "available": (boolean); "observedRevision": (number); "reason"?: ("pending-review" | "review-rejected" | "review-changes-requested" | "review-ended" | "stale-revision" | "package-changed" | "dependency-outage" | "invalid-input" | "already-applied" | "limit-reached" | "application-pending" | "attachment-required" | "attachment-pending" | "ask-answered" | "ask-closed" | "ask-due-passed"); "recovery"?: ("refresh" | "revise" | "retry" | "rebase" | "correct-input" | "receipt-only") }); "ifMatch": (string); "method": "POST"; "operation": "answer"; "path": (string) }) }); "state": ("open" | "answered" | "expired" | "closed"); "text": (string); "wants": (Array<(({ "kind": ("answer" | "document") }) | ({ "form": (string); "kind": "form" }))>) })>); "attachments"?: (Record); "id": (string); "links": (Record); "maximumBytes": (number); "required": (boolean); "value"?: ({ "byteSize": (number); "contentType": (string); "sha256": (string); "submissionVersion": (number); "uploadedAt"?: (string); "verificationStatus": ("notRequired" | "pending" | "approved" | "rejected") }) })>); "blockedReason"?: ("package-changed"); "createdAt"?: (string); "decision"?: ({ "decidedAt": (string); "publicReason"?: (string); "status": ("approved" | "rejected" | "changes-requested" | "answered") }); "effectDigest"?: (string); "handoffRefusal"?: ({ "code": ("review.initiator-required" | "review.initiator-excluded" | "review.policy-mismatch" | "review.refused") }); "id": (string); "input"?: (Record); "links": (Record); "partyRole"?: ("owner" | "subject"); "revision": (number); "state": ("draft" | "submitted" | "applied" | "cancelled" | "rejected"); "status"?: ("draft" | "awaiting-party" | "in-review" | "approved" | "processing" | "applied" | "rejected" | "cancelled"); "submissionVersion": (number); "title"?: (string); "turn": ("party" | "official" | "nobody") }) } "proposals.apply": { input: CallOptions & { path: { "proposal_id": (string) } } & { query?: { "accessProfile"?: "facility-correction-applier" } } & { headers: { "If-Match": (string) } } & ({ body: ({ "effectDigest": (string); "reason"?: (string); "submissionVersion": (number) }) }) & { accept?: "application/json" | "*/*" }; required: true; output: ({ "actionId": (string); "actionRevision": (string); "application"?: ({ "applicationId": (string); "effectDigest": (string); "resultLinks": (Array<({ "recordId": (string); "recordType": (string); "revision": (number) })>); "submissionVersion": (number) }); "applicationStatus"?: ({ "automaticRetry"?: ({ "attempts": (number); "maximumAttempts": (number); "scheduled": (boolean) }); "mode": ("automatic" | "manual"); "reason"?: ("package-changed" | "dependency-outage" | "lease-expired" | "application-refused" | "attempts-exhausted"); "recovery"?: ("retry" | "rebase" | "revise" | "correct-input"); "state": ("awaiting-review" | "pending" | "applying" | "blocked" | "applied" | "cancelled" | "rejected") }); "asks"?: (Array<({ "answer"?: ({ "additions": (Array<(string)>); "answeredAt": (string); "formEntries"?: (Array<(string)>); "text"?: (string) }); "askedAt": (string); "dueAt"?: (string); "id": (string); "links": ({ "answer"?: ({ "accessProfile": (string); "availability": ({ "available": (boolean); "observedRevision": (number); "reason"?: ("pending-review" | "review-rejected" | "review-changes-requested" | "review-ended" | "stale-revision" | "package-changed" | "dependency-outage" | "invalid-input" | "already-applied" | "limit-reached" | "application-pending" | "attachment-required" | "attachment-pending" | "ask-answered" | "ask-closed" | "ask-due-passed"); "recovery"?: ("refresh" | "revise" | "retry" | "rebase" | "correct-input" | "receipt-only") }); "ifMatch": (string); "method": "POST"; "operation": "answer"; "path": (string) }) }); "state": ("open" | "answered" | "expired" | "closed"); "text": (string); "wants": (Array<(({ "kind": ("answer" | "document") }) | ({ "form": (string); "kind": "form" }))>) })>); "attachments"?: (Record); "id": (string); "links": (Record); "maximumBytes": (number); "required": (boolean); "value"?: ({ "byteSize": (number); "contentType": (string); "sha256": (string); "submissionVersion": (number); "uploadedAt"?: (string); "verificationStatus": ("notRequired" | "pending" | "approved" | "rejected") }) })>); "blockedReason"?: ("package-changed"); "createdAt"?: (string); "decision"?: ({ "decidedAt": (string); "publicReason"?: (string); "status": ("approved" | "rejected" | "changes-requested" | "answered") }); "effectDigest"?: (string); "handoffRefusal"?: ({ "code": ("review.initiator-required" | "review.initiator-excluded" | "review.policy-mismatch" | "review.refused") }); "id": (string); "input"?: (Record); "links": (Record); "partyRole"?: ("owner" | "subject"); "revision": (number); "state": ("draft" | "submitted" | "applied" | "cancelled" | "rejected"); "status"?: ("draft" | "awaiting-party" | "in-review" | "approved" | "processing" | "applied" | "rejected" | "cancelled"); "submissionVersion": (number); "title"?: (string); "turn": ("party" | "official" | "nobody") }) } "proposals.attachments.supporting-document.delete": { input: CallOptions & { path: { "proposal_id": (string) } } & { query?: { "accessProfile"?: "facility-correction-author" } } & { headers: { "If-Match": (string) } } & { accept?: "application/json" | "*/*" }; required: true; output: ({ "actionId": (string); "actionRevision": (string); "application"?: ({ "applicationId": (string); "effectDigest": (string); "resultLinks": (Array<({ "recordId": (string); "recordType": (string); "revision": (number) })>); "submissionVersion": (number) }); "applicationStatus"?: ({ "automaticRetry"?: ({ "attempts": (number); "maximumAttempts": (number); "scheduled": (boolean) }); "mode": ("automatic" | "manual"); "reason"?: ("package-changed" | "dependency-outage" | "lease-expired" | "application-refused" | "attempts-exhausted"); "recovery"?: ("retry" | "rebase" | "revise" | "correct-input"); "state": ("awaiting-review" | "pending" | "applying" | "blocked" | "applied" | "cancelled" | "rejected") }); "asks"?: (Array<({ "answer"?: ({ "additions": (Array<(string)>); "answeredAt": (string); "formEntries"?: (Array<(string)>); "text"?: (string) }); "askedAt": (string); "dueAt"?: (string); "id": (string); "links": ({ "answer"?: ({ "accessProfile": (string); "availability": ({ "available": (boolean); "observedRevision": (number); "reason"?: ("pending-review" | "review-rejected" | "review-changes-requested" | "review-ended" | "stale-revision" | "package-changed" | "dependency-outage" | "invalid-input" | "already-applied" | "limit-reached" | "application-pending" | "attachment-required" | "attachment-pending" | "ask-answered" | "ask-closed" | "ask-due-passed"); "recovery"?: ("refresh" | "revise" | "retry" | "rebase" | "correct-input" | "receipt-only") }); "ifMatch": (string); "method": "POST"; "operation": "answer"; "path": (string) }) }); "state": ("open" | "answered" | "expired" | "closed"); "text": (string); "wants": (Array<(({ "kind": ("answer" | "document") }) | ({ "form": (string); "kind": "form" }))>) })>); "attachments"?: (Record); "id": (string); "links": (Record); "maximumBytes": (number); "required": (boolean); "value"?: ({ "byteSize": (number); "contentType": (string); "sha256": (string); "submissionVersion": (number); "uploadedAt"?: (string); "verificationStatus": ("notRequired" | "pending" | "approved" | "rejected") }) })>); "blockedReason"?: ("package-changed"); "createdAt"?: (string); "decision"?: ({ "decidedAt": (string); "publicReason"?: (string); "status": ("approved" | "rejected" | "changes-requested" | "answered") }); "effectDigest"?: (string); "handoffRefusal"?: ({ "code": ("review.initiator-required" | "review.initiator-excluded" | "review.policy-mismatch" | "review.refused") }); "id": (string); "input"?: (Record); "links": (Record); "partyRole"?: ("owner" | "subject"); "revision": (number); "state": ("draft" | "submitted" | "applied" | "cancelled" | "rejected"); "status"?: ("draft" | "awaiting-party" | "in-review" | "approved" | "processing" | "applied" | "rejected" | "cancelled"); "submissionVersion": (number); "title"?: (string); "turn": ("party" | "official" | "nobody") }) } @@ -43,15 +47,15 @@ export interface Operations { "proposals.edit": { input: CallOptions & { path: { "proposal_id": (string) } } & { query?: { "accessProfile"?: "facility-correction-author" } } & { headers: { "If-Match": (string) } } & ({ body: (({ "input": ({ "addressLine"?: (string); "city"?: (string); "facilityId"?: (string); "postalCode"?: (string) }) }) | ({ "input": ({ "facilityId"?: (string) }) })) }) & { accept?: "application/json" | "*/*" }; required: true; output: ({ "actionId": (string); "actionRevision": (string); "application"?: ({ "applicationId": (string); "effectDigest": (string); "resultLinks": (Array<({ "recordId": (string); "recordType": (string); "revision": (number) })>); "submissionVersion": (number) }); "applicationStatus"?: ({ "automaticRetry"?: ({ "attempts": (number); "maximumAttempts": (number); "scheduled": (boolean) }); "mode": ("automatic" | "manual"); "reason"?: ("package-changed" | "dependency-outage" | "lease-expired" | "application-refused" | "attempts-exhausted"); "recovery"?: ("retry" | "rebase" | "revise" | "correct-input"); "state": ("awaiting-review" | "pending" | "applying" | "blocked" | "applied" | "cancelled" | "rejected") }); "asks"?: (Array<({ "answer"?: ({ "additions": (Array<(string)>); "answeredAt": (string); "formEntries"?: (Array<(string)>); "text"?: (string) }); "askedAt": (string); "dueAt"?: (string); "id": (string); "links": ({ "answer"?: ({ "accessProfile": (string); "availability": ({ "available": (boolean); "observedRevision": (number); "reason"?: ("pending-review" | "review-rejected" | "review-changes-requested" | "review-ended" | "stale-revision" | "package-changed" | "dependency-outage" | "invalid-input" | "already-applied" | "limit-reached" | "application-pending" | "attachment-required" | "attachment-pending" | "ask-answered" | "ask-closed" | "ask-due-passed"); "recovery"?: ("refresh" | "revise" | "retry" | "rebase" | "correct-input" | "receipt-only") }); "ifMatch": (string); "method": "POST"; "operation": "answer"; "path": (string) }) }); "state": ("open" | "answered" | "expired" | "closed"); "text": (string); "wants": (Array<(({ "kind": ("answer" | "document") }) | ({ "form": (string); "kind": "form" }))>) })>); "attachments"?: (Record); "id": (string); "links": (Record); "maximumBytes": (number); "required": (boolean); "value"?: ({ "byteSize": (number); "contentType": (string); "sha256": (string); "submissionVersion": (number); "uploadedAt"?: (string); "verificationStatus": ("notRequired" | "pending" | "approved" | "rejected") }) })>); "blockedReason"?: ("package-changed"); "createdAt"?: (string); "decision"?: ({ "decidedAt": (string); "publicReason"?: (string); "status": ("approved" | "rejected" | "changes-requested" | "answered") }); "effectDigest"?: (string); "handoffRefusal"?: ({ "code": ("review.initiator-required" | "review.initiator-excluded" | "review.policy-mismatch" | "review.refused") }); "id": (string); "input"?: (Record); "links": (Record); "partyRole"?: ("owner" | "subject"); "revision": (number); "state": ("draft" | "submitted" | "applied" | "cancelled" | "rejected"); "status"?: ("draft" | "awaiting-party" | "in-review" | "approved" | "processing" | "applied" | "rejected" | "cancelled"); "submissionVersion": (number); "title"?: (string); "turn": ("party" | "official" | "nobody") }) } "proposals.rebase": { input: CallOptions & { path: { "proposal_id": (string) } } & { query?: { "accessProfile"?: "facility-correction-author" } } & { headers: { "If-Match": (string) } } & ({ body: (({ "input": ({ "addressLine"?: (string); "city"?: (string); "facilityId"?: (string); "postalCode"?: (string) }) }) | ({ "input": ({ "facilityId"?: (string) }) })) }) & { accept?: "application/json" | "*/*" }; required: true; output: ({ "actionId": (string); "actionRevision": (string); "application"?: ({ "applicationId": (string); "effectDigest": (string); "resultLinks": (Array<({ "recordId": (string); "recordType": (string); "revision": (number) })>); "submissionVersion": (number) }); "applicationStatus"?: ({ "automaticRetry"?: ({ "attempts": (number); "maximumAttempts": (number); "scheduled": (boolean) }); "mode": ("automatic" | "manual"); "reason"?: ("package-changed" | "dependency-outage" | "lease-expired" | "application-refused" | "attempts-exhausted"); "recovery"?: ("retry" | "rebase" | "revise" | "correct-input"); "state": ("awaiting-review" | "pending" | "applying" | "blocked" | "applied" | "cancelled" | "rejected") }); "asks"?: (Array<({ "answer"?: ({ "additions": (Array<(string)>); "answeredAt": (string); "formEntries"?: (Array<(string)>); "text"?: (string) }); "askedAt": (string); "dueAt"?: (string); "id": (string); "links": ({ "answer"?: ({ "accessProfile": (string); "availability": ({ "available": (boolean); "observedRevision": (number); "reason"?: ("pending-review" | "review-rejected" | "review-changes-requested" | "review-ended" | "stale-revision" | "package-changed" | "dependency-outage" | "invalid-input" | "already-applied" | "limit-reached" | "application-pending" | "attachment-required" | "attachment-pending" | "ask-answered" | "ask-closed" | "ask-due-passed"); "recovery"?: ("refresh" | "revise" | "retry" | "rebase" | "correct-input" | "receipt-only") }); "ifMatch": (string); "method": "POST"; "operation": "answer"; "path": (string) }) }); "state": ("open" | "answered" | "expired" | "closed"); "text": (string); "wants": (Array<(({ "kind": ("answer" | "document") }) | ({ "form": (string); "kind": "form" }))>) })>); "attachments"?: (Record); "id": (string); "links": (Record); "maximumBytes": (number); "required": (boolean); "value"?: ({ "byteSize": (number); "contentType": (string); "sha256": (string); "submissionVersion": (number); "uploadedAt"?: (string); "verificationStatus": ("notRequired" | "pending" | "approved" | "rejected") }) })>); "blockedReason"?: ("package-changed"); "createdAt"?: (string); "decision"?: ({ "decidedAt": (string); "publicReason"?: (string); "status": ("approved" | "rejected" | "changes-requested" | "answered") }); "effectDigest"?: (string); "handoffRefusal"?: ({ "code": ("review.initiator-required" | "review.initiator-excluded" | "review.policy-mismatch" | "review.refused") }); "id": (string); "input"?: (Record); "links": (Record); "partyRole"?: ("owner" | "subject"); "revision": (number); "state": ("draft" | "submitted" | "applied" | "cancelled" | "rejected"); "status"?: ("draft" | "awaiting-party" | "in-review" | "approved" | "processing" | "applied" | "rejected" | "cancelled"); "submissionVersion": (number); "title"?: (string); "turn": ("party" | "official" | "nobody") }) } "proposals.retry": { input: CallOptions & { path: { "proposal_id": (string) } } & { query?: { "accessProfile"?: "facility-correction-author" } } & { headers: { "If-Match": (string) } } & ({ body: (Record) }) & { accept?: "application/json" | "*/*" }; required: true; output: ({ "actionId": (string); "actionRevision": (string); "application"?: ({ "applicationId": (string); "effectDigest": (string); "resultLinks": (Array<({ "recordId": (string); "recordType": (string); "revision": (number) })>); "submissionVersion": (number) }); "applicationStatus"?: ({ "automaticRetry"?: ({ "attempts": (number); "maximumAttempts": (number); "scheduled": (boolean) }); "mode": ("automatic" | "manual"); "reason"?: ("package-changed" | "dependency-outage" | "lease-expired" | "application-refused" | "attempts-exhausted"); "recovery"?: ("retry" | "rebase" | "revise" | "correct-input"); "state": ("awaiting-review" | "pending" | "applying" | "blocked" | "applied" | "cancelled" | "rejected") }); "asks"?: (Array<({ "answer"?: ({ "additions": (Array<(string)>); "answeredAt": (string); "formEntries"?: (Array<(string)>); "text"?: (string) }); "askedAt": (string); "dueAt"?: (string); "id": (string); "links": ({ "answer"?: ({ "accessProfile": (string); "availability": ({ "available": (boolean); "observedRevision": (number); "reason"?: ("pending-review" | "review-rejected" | "review-changes-requested" | "review-ended" | "stale-revision" | "package-changed" | "dependency-outage" | "invalid-input" | "already-applied" | "limit-reached" | "application-pending" | "attachment-required" | "attachment-pending" | "ask-answered" | "ask-closed" | "ask-due-passed"); "recovery"?: ("refresh" | "revise" | "retry" | "rebase" | "correct-input" | "receipt-only") }); "ifMatch": (string); "method": "POST"; "operation": "answer"; "path": (string) }) }); "state": ("open" | "answered" | "expired" | "closed"); "text": (string); "wants": (Array<(({ "kind": ("answer" | "document") }) | ({ "form": (string); "kind": "form" }))>) })>); "attachments"?: (Record); "id": (string); "links": (Record); "maximumBytes": (number); "required": (boolean); "value"?: ({ "byteSize": (number); "contentType": (string); "sha256": (string); "submissionVersion": (number); "uploadedAt"?: (string); "verificationStatus": ("notRequired" | "pending" | "approved" | "rejected") }) })>); "blockedReason"?: ("package-changed"); "createdAt"?: (string); "decision"?: ({ "decidedAt": (string); "publicReason"?: (string); "status": ("approved" | "rejected" | "changes-requested" | "answered") }); "effectDigest"?: (string); "handoffRefusal"?: ({ "code": ("review.initiator-required" | "review.initiator-excluded" | "review.policy-mismatch" | "review.refused") }); "id": (string); "input"?: (Record); "links": (Record); "partyRole"?: ("owner" | "subject"); "revision": (number); "state": ("draft" | "submitted" | "applied" | "cancelled" | "rejected"); "status"?: ("draft" | "awaiting-party" | "in-review" | "approved" | "processing" | "applied" | "rejected" | "cancelled"); "submissionVersion": (number); "title"?: (string); "turn": ("party" | "official" | "nobody") }) } - "proposals.get-review-context": { input: CallOptions & { path: { "proposal_id": (string) } } & { query?: { "accessProfile"?: "proposal-reviewer"; "include"?: "answers" } } & { accept?: "application/json" | "*/*" }; required: true; output: ({ "actionId": (string); "actionRevision": (string); "authority"?: (string); "context": ({ "asks"?: (Array<({ "answer"?: ({ "answeredAt": (string); "documents": (Array<({ "byteSize": (number); "contentType": (string); "download"?: ({ "accessProfile": (string); "method": "GET"; "operation": "get-review-context"; "path": (string) }); "id": (string); "sha256": (string); "verificationStatus": ("notRequired" | "pending" | "approved" | "rejected") })>); "formEntries"?: (Array<(({ "input": {} | null }) | ({ "contractChanged": {} | null })) & ({ "addedAt": (string); "contractChanged"?: true; "id": (string); "input"?: (Record) })>); "text"?: (string) }); "askedAt": (string); "dueAt"?: (string); "id": (string); "state": ("open" | "answered" | "expired" | "closed"); "text": (string); "wants": (Array<(({ "kind": ("answer" | "document") }) | ({ "form": (string); "kind": "form" }))>) })>); "contract": ({ "id": (string); "revision": (string); "schemaDigest": (string) }); "fields": (Record); "reference": (string) }); "effectDigest": (string); "id": (string); "policy"?: ({ "digest": (string); "id": (string); "version": (string) }); "result"?: ({ "availableUntil"?: (string); "completedAt"?: (string); "resultId"?: (string); "state": ("pending" | "approved" | "rejected" | "changes-requested" | "answered" | "cancelled" | "superseded" | "expired") }); "reviewable": (boolean); "revision": (number); "subject": ({ "digest": (string); "id": (string); "source": (string); "subjectType": "proposal"; "version": (string) }); "submissionVersion": (number) }) } - "proposals.get-review-status": { input: CallOptions & { path: { "proposal_id": (string) } } & { query?: { "accessProfile"?: "casework-review-status" | "facility-correction-author"; "include"?: "progress" } } & { accept?: "application/json" | "*/*" }; required: true; output: ({ "actionId": (string); "actionRevision": (string); "authority"?: (string); "context": ({ "contract"?: ({ "id": (string); "revision": (string); "schemaDigest": (string) }); "reference": (string) }); "effectDigest": (string); "handoff"?: ({ "reason"?: ("remote-refused" | "producer-identity-mismatch" | "review-acceptance-changed" | "review-policy-changed" | "submission-recovery-expired" | "operator-closed" | "unspecified"); "state": ("pending" | "accepted" | "failed" | "withdrawn") }); "id": (string); "policy"?: ({ "digest": (string); "id": (string); "version": (string) }); "progressCode"?: (string); "requestId"?: (string); "result"?: ({ "availableUntil"?: (string); "completedAt"?: (string); "resultId"?: (string); "state": ("pending" | "approved" | "rejected" | "changes-requested" | "answered" | "cancelled" | "superseded" | "expired") }); "reviewable": (boolean); "revision": (number); "subject": ({ "digest": (string); "id": (string); "source": (string); "subjectType": "proposal"; "version": (string) }); "submissionVersion": (number) }) } + "proposals.get-review-context": { input: CallOptions & { path: { "proposal_id": (string) } } & { query?: { "accessProfile"?: "proposal-reviewer"; "include"?: "answers" } } & { accept?: "application/json" | "*/*" }; required: true; output: ({ "actionId": (string); "actionRevision": (string); "authority"?: (string); "context": ({ "asks"?: (Array<({ "answer"?: ({ "answeredAt": (string); "documents": (Array<({ "byteSize": (number); "contentType": (string); "download"?: ({ "accessProfile": (string); "method": "GET"; "operation": "get-review-context"; "path": (string) }); "id": (string); "sha256": (string); "verificationStatus": ("notRequired" | "pending" | "approved" | "rejected") })>); "formEntries"?: (Array<(({ "input": {} | null }) | ({ "contractChanged": {} | null })) & ({ "addedAt": (string); "contractChanged"?: true; "id": (string); "input"?: (Record) })>); "text"?: (string) }); "askedAt": (string); "dueAt"?: (string); "id": (string); "state": ("open" | "answered" | "expired" | "closed"); "text": (string); "wants": (Array<(({ "kind": ("answer" | "document") }) | ({ "form": (string); "kind": "form" }))>) })>); "contract": ({ "id": (string); "revision": (string); "schemaDigest": (string) }); "fields": (Record); "reference": (string) }); "effectDigest": (string); "id": (string); "policy"?: (({ "id": (string) }) | ({ "digest": (string); "id": (string); "version": (string) })); "result"?: ({ "availableUntil"?: (string); "completedAt"?: (string); "resultId"?: (string); "state": ("pending" | "approved" | "rejected" | "changes-requested" | "answered" | "cancelled" | "superseded" | "expired") }); "reviewable": (boolean); "revision": (number); "subject": ({ "digest": (string); "id": (string); "source": (string); "subjectType": "proposal"; "version": (string) }); "submissionVersion": (number) }) } + "proposals.get-review-status": { input: CallOptions & { path: { "proposal_id": (string) } } & { query?: { "accessProfile"?: "casework-review-status" | "facility-correction-author"; "include"?: "progress" } } & { accept?: "application/json" | "*/*" }; required: true; output: ({ "actionId": (string); "actionRevision": (string); "authority"?: (string); "context": ({ "contract"?: ({ "id": (string); "revision": (string); "schemaDigest": (string) }); "reference": (string) }); "effectDigest": (string); "handoff"?: ({ "reason"?: ("remote-refused" | "producer-identity-mismatch" | "review-acceptance-changed" | "review-policy-changed" | "submission-recovery-expired" | "operator-closed" | "unspecified"); "state": ("pending" | "accepted" | "failed" | "withdrawn") }); "id": (string); "policy"?: (({ "id": (string) }) | ({ "digest": (string); "id": (string); "version": (string) })); "progressCode"?: (string); "requestId"?: (string); "result"?: ({ "availableUntil"?: (string); "completedAt"?: (string); "resultId"?: (string); "state": ("pending" | "approved" | "rejected" | "changes-requested" | "answered" | "cancelled" | "superseded" | "expired") }); "reviewable": (boolean); "revision": (number); "subject": ({ "digest": (string); "id": (string); "source": (string); "subjectType": "proposal"; "version": (string) }); "submissionVersion": (number) }) } "proposals.revise": { input: CallOptions & { path: { "proposal_id": (string) } } & { query?: { "accessProfile"?: "facility-correction-author" } } & { headers: { "If-Match": (string) } } & ({ body: (({ "input": ({ "addressLine"?: (string); "city"?: (string); "facilityId"?: (string); "postalCode"?: (string) }) }) | ({ "input": ({ "facilityId"?: (string) }) }) | (Record)) }) & { accept?: "application/json" | "*/*" }; required: true; output: ({ "actionId": (string); "actionRevision": (string); "application"?: ({ "applicationId": (string); "effectDigest": (string); "resultLinks": (Array<({ "recordId": (string); "recordType": (string); "revision": (number) })>); "submissionVersion": (number) }); "applicationStatus"?: ({ "automaticRetry"?: ({ "attempts": (number); "maximumAttempts": (number); "scheduled": (boolean) }); "mode": ("automatic" | "manual"); "reason"?: ("package-changed" | "dependency-outage" | "lease-expired" | "application-refused" | "attempts-exhausted"); "recovery"?: ("retry" | "rebase" | "revise" | "correct-input"); "state": ("awaiting-review" | "pending" | "applying" | "blocked" | "applied" | "cancelled" | "rejected") }); "asks"?: (Array<({ "answer"?: ({ "additions": (Array<(string)>); "answeredAt": (string); "formEntries"?: (Array<(string)>); "text"?: (string) }); "askedAt": (string); "dueAt"?: (string); "id": (string); "links": ({ "answer"?: ({ "accessProfile": (string); "availability": ({ "available": (boolean); "observedRevision": (number); "reason"?: ("pending-review" | "review-rejected" | "review-changes-requested" | "review-ended" | "stale-revision" | "package-changed" | "dependency-outage" | "invalid-input" | "already-applied" | "limit-reached" | "application-pending" | "attachment-required" | "attachment-pending" | "ask-answered" | "ask-closed" | "ask-due-passed"); "recovery"?: ("refresh" | "revise" | "retry" | "rebase" | "correct-input" | "receipt-only") }); "ifMatch": (string); "method": "POST"; "operation": "answer"; "path": (string) }) }); "state": ("open" | "answered" | "expired" | "closed"); "text": (string); "wants": (Array<(({ "kind": ("answer" | "document") }) | ({ "form": (string); "kind": "form" }))>) })>); "attachments"?: (Record); "id": (string); "links": (Record); "maximumBytes": (number); "required": (boolean); "value"?: ({ "byteSize": (number); "contentType": (string); "sha256": (string); "submissionVersion": (number); "uploadedAt"?: (string); "verificationStatus": ("notRequired" | "pending" | "approved" | "rejected") }) })>); "blockedReason"?: ("package-changed"); "createdAt"?: (string); "decision"?: ({ "decidedAt": (string); "publicReason"?: (string); "status": ("approved" | "rejected" | "changes-requested" | "answered") }); "effectDigest"?: (string); "handoffRefusal"?: ({ "code": ("review.initiator-required" | "review.initiator-excluded" | "review.policy-mismatch" | "review.refused") }); "id": (string); "input"?: (Record); "links": (Record); "partyRole"?: ("owner" | "subject"); "revision": (number); "state": ("draft" | "submitted" | "applied" | "cancelled" | "rejected"); "status"?: ("draft" | "awaiting-party" | "in-review" | "approved" | "processing" | "applied" | "rejected" | "cancelled"); "submissionVersion": (number); "title"?: (string); "turn": ("party" | "official" | "nobody") }) } "proposals.get-submission": { input: CallOptions & { path: { "proposal_id": (string); "submission_version": (number) } } & { query?: { "accessProfile"?: "facility-correction-applier" | "facility-correction-author" } } & { accept?: "application/json" | "*/*" }; required: true; output: ({ "actionId": (string); "application": (({ "applicationId": (string); "appliedAt"?: (string); "appliedBy"?: (string); "state": "applied" }) | ({ "automaticRetry"?: ({ "attempts": (number); "maximumAttempts": (number); "scheduled": (boolean) }); "mode": ("automatic" | "manual"); "reason"?: ("package-changed" | "dependency-outage" | "lease-expired" | "application-refused" | "attempts-exhausted"); "recovery"?: ("retry" | "rebase" | "revise" | "correct-input"); "state": ("awaiting-review" | "pending" | "applying" | "blocked" | "cancelled" | "rejected") }) | (null)); "current": (boolean); "decision"?: ({ "decidedAt": (string); "publicReason"?: (string); "status": ("approved" | "rejected" | "changes-requested" | "answered") }); "effectDigest": (string); "handoffRefusal"?: ({ "code": ("review.initiator-required" | "review.initiator-excluded" | "review.policy-mismatch" | "review.refused") }); "id": (string); "review": (({ "availableUntil"?: (string); "completedAt"?: (string); "resultId"?: (string); "state": ("pending" | "approved" | "rejected" | "changes-requested" | "answered" | "cancelled" | "superseded" | "expired") }) | (null)); "submissionVersion": (number) }) } "proposals.submit": { input: CallOptions & { path: { "proposal_id": (string) } } & { query?: { "accessProfile"?: "facility-correction-author" } } & { headers: { "If-Match": (string) } } & ({ body: (Record) }) & { accept?: "application/json" | "*/*" }; required: true; output: ({ "actionId": (string); "actionRevision": (string); "application"?: ({ "applicationId": (string); "effectDigest": (string); "resultLinks": (Array<({ "recordId": (string); "recordType": (string); "revision": (number) })>); "submissionVersion": (number) }); "applicationStatus"?: ({ "automaticRetry"?: ({ "attempts": (number); "maximumAttempts": (number); "scheduled": (boolean) }); "mode": ("automatic" | "manual"); "reason"?: ("package-changed" | "dependency-outage" | "lease-expired" | "application-refused" | "attempts-exhausted"); "recovery"?: ("retry" | "rebase" | "revise" | "correct-input"); "state": ("awaiting-review" | "pending" | "applying" | "blocked" | "applied" | "cancelled" | "rejected") }); "asks"?: (Array<({ "answer"?: ({ "additions": (Array<(string)>); "answeredAt": (string); "formEntries"?: (Array<(string)>); "text"?: (string) }); "askedAt": (string); "dueAt"?: (string); "id": (string); "links": ({ "answer"?: ({ "accessProfile": (string); "availability": ({ "available": (boolean); "observedRevision": (number); "reason"?: ("pending-review" | "review-rejected" | "review-changes-requested" | "review-ended" | "stale-revision" | "package-changed" | "dependency-outage" | "invalid-input" | "already-applied" | "limit-reached" | "application-pending" | "attachment-required" | "attachment-pending" | "ask-answered" | "ask-closed" | "ask-due-passed"); "recovery"?: ("refresh" | "revise" | "retry" | "rebase" | "correct-input" | "receipt-only") }); "ifMatch": (string); "method": "POST"; "operation": "answer"; "path": (string) }) }); "state": ("open" | "answered" | "expired" | "closed"); "text": (string); "wants": (Array<(({ "kind": ("answer" | "document") }) | ({ "form": (string); "kind": "form" }))>) })>); "attachments"?: (Record); "id": (string); "links": (Record); "maximumBytes": (number); "required": (boolean); "value"?: ({ "byteSize": (number); "contentType": (string); "sha256": (string); "submissionVersion": (number); "uploadedAt"?: (string); "verificationStatus": ("notRequired" | "pending" | "approved" | "rejected") }) })>); "blockedReason"?: ("package-changed"); "createdAt"?: (string); "decision"?: ({ "decidedAt": (string); "publicReason"?: (string); "status": ("approved" | "rejected" | "changes-requested" | "answered") }); "effectDigest"?: (string); "handoffRefusal"?: ({ "code": ("review.initiator-required" | "review.initiator-excluded" | "review.policy-mismatch" | "review.refused") }); "id": (string); "input"?: (Record); "links": (Record); "partyRole"?: ("owner" | "subject"); "revision": (number); "state": ("draft" | "submitted" | "applied" | "cancelled" | "rejected"); "status"?: ("draft" | "awaiting-party" | "in-review" | "approved" | "processing" | "applied" | "rejected" | "cancelled"); "submissionVersion": (number); "title"?: (string); "turn": ("party" | "official" | "nobody") }) } "records.directory-entry.list": { input: CallOptions & { query?: { "accessProfile"?: "directory-editor"; "$select"?: (string); "$filter"?: (string); "$orderby"?: (string); "limit"?: (number); "$count"?: (boolean); "cursor"?: (string) } } & { headers?: { "traceparent"?: (string); "Accept"?: ("application/json" | "application/ld+json") & (string) } } & { accept?: "application/json" | "application/ld+json" | "*/*" }; required: false; output: ({ "count"?: (number); "items": (Array<({ "domainData": ({ "email"?: (string); "jurisdiction"?: (string); "name"?: (string) }); "recordId": (string); "revisionId": (string) })>); "meta": ({ "datasetId": "facility-registry"; "recordTypeId": "directory-entry"; "registryId": "facility-registry" }); "pageInfo": ({ "nextCursor": (string | null) }) }) | ({ "@context": "https://id.registrystack.org/contexts/registry-record/v1"; "count"?: (number); "items": (Array<({ "domainData": ({ "email"?: (string); "jurisdiction"?: (string); "name"?: (string) }); "recordId": (string); "revisionId": (string) })>); "meta": ({ "datasetId": "facility-registry"; "recordTypeId": "directory-entry"; "registryId": "facility-registry" }); "pageInfo": ({ "nextCursor": (string | null) }) }) } "records.directory-entry.create": { input: CallOptions & { query?: { "accessProfile"?: "directory-editor" } } & { headers?: { "traceparent"?: (string); "Accept"?: ("application/json" | "application/ld+json") & (string) } } & ({ body: ({ "data": Schema_directory_entry_create_input }) }) & { accept?: "application/json" | "application/ld+json" | "*/*" }; required: true; output: ({ "data": ({ "domainData": Schema_directory_entry; "recordId": (string); "revisionId": (string) }); "meta": ({ "datasetId": "facility-registry"; "recordTypeId": "directory-entry"; "registryId": "facility-registry" }) }) | ({ "@context": "https://id.registrystack.org/contexts/registry-record/v1"; "data": ({ "domainData": Schema_directory_entry; "recordId": (string); "revisionId": (string) }); "meta": ({ "datasetId": "facility-registry"; "recordTypeId": "directory-entry"; "registryId": "facility-registry" }) }) } "records.directory-entry.get": { input: CallOptions & { path: { "record_id": (string) } } & { query?: { "accessProfile"?: "directory-editor"; "$select"?: (string) } } & { headers?: { "traceparent"?: (string); "Accept"?: ("application/json" | "application/ld+json") & (string) } } & { accept?: "application/json" | "application/ld+json" | "*/*" }; required: true; output: ({ "data": ({ "domainData": ({ "email"?: (string); "jurisdiction"?: (string); "name"?: (string) }); "recordId": (string); "revisionId": (string) }); "meta": ({ "datasetId": "facility-registry"; "recordTypeId": "directory-entry"; "registryId": "facility-registry" }) }) | ({ "@context": "https://id.registrystack.org/contexts/registry-record/v1"; "data": ({ "domainData": ({ "email"?: (string); "jurisdiction"?: (string); "name"?: (string) }); "recordId": (string); "revisionId": (string) }); "meta": ({ "datasetId": "facility-registry"; "recordTypeId": "directory-entry"; "registryId": "facility-registry" }) }) } - "records.directory-entry.patch": { input: CallOptions & { path: { "record_id": (string) } } & { query?: { "accessProfile"?: "directory-editor" } } & { headers: { "traceparent"?: (string); "If-Match": (string); "Accept"?: ("application/json" | "application/ld+json") & (string) } } & ({ body: (Array<({ "op": ("add" | "replace" | "remove" | "test") & (string); "path": (string); "value"?: JsonValue })>) }) & { accept?: "application/json" | "application/ld+json" | "*/*" }; required: true; output: ({ "data": ({ "domainData": Schema_directory_entry; "recordId": (string); "revisionId": (string) }); "meta": ({ "datasetId": "facility-registry"; "recordTypeId": "directory-entry"; "registryId": "facility-registry" }) }) | ({ "@context": "https://id.registrystack.org/contexts/registry-record/v1"; "data": ({ "domainData": Schema_directory_entry; "recordId": (string); "revisionId": (string) }); "meta": ({ "datasetId": "facility-registry"; "recordTypeId": "directory-entry"; "registryId": "facility-registry" }) }) } + "records.directory-entry.patch": { input: CallOptions & { path: { "record_id": (string) } } & { query?: { "accessProfile"?: "directory-editor" } } & { headers: { "traceparent"?: (string); "If-Match": (string); "Accept"?: ("application/json" | "application/ld+json") & (string) } } & ({ body: (Array<(({ "op": "add"; "path": ("/data/email" | "/data/jurisdiction" | "/data/name") & (string); "value": JsonValue }) | ({ "op": "replace"; "path": ("/data/email" | "/data/jurisdiction" | "/data/name") & (string); "value": JsonValue }) | ({ "op": "test"; "path": ("/data/email" | "/data/jurisdiction" | "/data/name") & (string); "value": JsonValue }))>) }) & { accept?: "application/json" | "application/ld+json" | "*/*" }; required: true; output: ({ "data": ({ "domainData": Schema_directory_entry; "recordId": (string); "revisionId": (string) }); "meta": ({ "datasetId": "facility-registry"; "recordTypeId": "directory-entry"; "registryId": "facility-registry" }) }) | ({ "@context": "https://id.registrystack.org/contexts/registry-record/v1"; "data": ({ "domainData": Schema_directory_entry; "recordId": (string); "revisionId": (string) }); "meta": ({ "datasetId": "facility-registry"; "recordTypeId": "directory-entry"; "registryId": "facility-registry" }) }) } "records.facility.list": { input: CallOptions & { query?: { "accessProfile"?: "facility-reader"; "$select"?: (string); "$filter"?: (string); "$orderby"?: (string); "limit"?: (number); "$count"?: (boolean); "cursor"?: (string) } } & { headers?: { "traceparent"?: (string); "Accept"?: ("application/json" | "application/ld+json") & (string) } } & { accept?: "application/json" | "application/ld+json" | "*/*" }; required: false; output: ({ "count"?: (number); "items": (Array<({ "domainData": ({ "addressLine"?: (string); "city"?: (string); "facilityCode"?: (string); "jurisdiction"?: (string); "name"?: (string); "postalCode"?: (string); "status"?: ("active" | "inactive") & (string) }); "recordId": (string); "revisionId": (string) })>); "meta": ({ "datasetId": "facility-registry"; "recordTypeId": "facility"; "registryId": "facility-registry" }); "pageInfo": ({ "nextCursor": (string | null) }) }) | ({ "@context": "https://id.registrystack.org/contexts/registry-record/v1"; "count"?: (number); "items": (Array<({ "domainData": ({ "addressLine"?: (string); "city"?: (string); "facilityCode"?: (string); "jurisdiction"?: (string); "name"?: (string); "postalCode"?: (string); "status"?: ("active" | "inactive") & (string) }); "recordId": (string); "revisionId": (string) })>); "meta": ({ "datasetId": "facility-registry"; "recordTypeId": "facility"; "registryId": "facility-registry" }); "pageInfo": ({ "nextCursor": (string | null) }) }) } "records.facility.get": { input: CallOptions & { path: { "record_id": (string) } } & { query?: { "accessProfile"?: "facility-reader" | "proposal-reviewer"; "$select"?: (string) } } & { headers?: { "traceparent"?: (string); "Accept"?: ("application/json" | "application/ld+json") & (string) } } & { accept?: "application/json" | "application/ld+json" | "*/*" }; required: true; output: ({ "data": ({ "domainData": ({ "addressLine"?: (string); "city"?: (string); "facilityCode"?: (string); "jurisdiction"?: (string); "name"?: (string); "postalCode"?: (string); "status"?: ("active" | "inactive") & (string) }); "recordId": (string); "revisionId": (string) }); "meta": ({ "datasetId": "facility-registry"; "recordTypeId": "facility"; "registryId": "facility-registry" }) }) | ({ "@context": "https://id.registrystack.org/contexts/registry-record/v1"; "data": ({ "domainData": ({ "addressLine"?: (string); "city"?: (string); "facilityCode"?: (string); "jurisdiction"?: (string); "name"?: (string); "postalCode"?: (string); "status"?: ("active" | "inactive") & (string) }); "recordId": (string); "revisionId": (string) }); "meta": ({ "datasetId": "facility-registry"; "recordTypeId": "facility"; "registryId": "facility-registry" }) }) } "records.facility.path.operators": { input: CallOptions & { path: { "record_id": (string) } } & { query?: { "accessProfile"?: "facility-reader"; "$select"?: (string); "$filter"?: (string); "$orderby"?: (string); "limit"?: (number); "$count"?: (boolean); "cursor"?: (string) } } & { headers?: { "traceparent"?: (string); "Accept"?: ("application/json" | "application/ld+json") & (string) } } & { accept?: "application/json" | "application/ld+json" | "*/*" }; required: true; output: ({ "count"?: (number); "items": (Array<({ "domainData": ({ "jurisdiction"?: (string); "operatorCode"?: (string); "status"?: ("active" | "inactive") & (string) }); "recordId": (string); "revisionId": (string) })>); "meta": ({ "datasetId": "facility-registry"; "recordTypeId": "operator"; "registryId": "facility-registry" }); "pageInfo": ({ "nextCursor": (string | null) }) }) | ({ "@context": "https://id.registrystack.org/contexts/registry-record/v1"; "count"?: (number); "items": (Array<({ "domainData": ({ "jurisdiction"?: (string); "operatorCode"?: (string); "status"?: ("active" | "inactive") & (string) }); "recordId": (string); "revisionId": (string) })>); "meta": ({ "datasetId": "facility-registry"; "recordTypeId": "operator"; "registryId": "facility-registry" }); "pageInfo": ({ "nextCursor": (string | null) }) }) } @@ -60,7 +64,7 @@ export interface Operations { "records.operator.list": { input: CallOptions & { query?: { "accessProfile"?: "facility-reader" | "operator-editor"; "$select"?: (string); "$filter"?: (string); "$orderby"?: (string); "limit"?: (number); "$count"?: (boolean); "cursor"?: (string) } } & { headers?: { "traceparent"?: (string); "Accept"?: ("application/json" | "application/ld+json") & (string) } } & { accept?: "application/json" | "application/ld+json" | "*/*" }; required: false; output: ({ "count"?: (number); "items": (Array<({ "domainData": ({ "jurisdiction"?: (string); "operatorCode"?: (string); "status"?: ("active" | "inactive") & (string) }); "recordId": (string); "revisionId": (string) })>); "meta": ({ "datasetId": "facility-registry"; "recordTypeId": "operator"; "registryId": "facility-registry" }); "pageInfo": ({ "nextCursor": (string | null) }) }) | ({ "@context": "https://id.registrystack.org/contexts/registry-record/v1"; "count"?: (number); "items": (Array<({ "domainData": ({ "jurisdiction"?: (string); "operatorCode"?: (string); "status"?: ("active" | "inactive") & (string) }); "recordId": (string); "revisionId": (string) })>); "meta": ({ "datasetId": "facility-registry"; "recordTypeId": "operator"; "registryId": "facility-registry" }); "pageInfo": ({ "nextCursor": (string | null) }) }) } "records.operator.create": { input: CallOptions & { query?: { "accessProfile"?: "operator-editor" } } & { headers?: { "traceparent"?: (string); "Accept"?: ("application/json" | "application/ld+json") & (string) } } & ({ body: ({ "data": Schema_operator_create_input }) }) & { accept?: "application/json" | "application/ld+json" | "*/*" }; required: true; output: ({ "data": ({ "domainData": Schema_operator; "recordId": (string); "revisionId": (string) }); "meta": ({ "datasetId": "facility-registry"; "recordTypeId": "operator"; "registryId": "facility-registry" }) }) | ({ "@context": "https://id.registrystack.org/contexts/registry-record/v1"; "data": ({ "domainData": Schema_operator; "recordId": (string); "revisionId": (string) }); "meta": ({ "datasetId": "facility-registry"; "recordTypeId": "operator"; "registryId": "facility-registry" }) }) } "records.operator.get": { input: CallOptions & { path: { "record_id": (string) } } & { query?: { "accessProfile"?: "facility-reader" | "operator-editor"; "$select"?: (string) } } & { headers?: { "traceparent"?: (string); "Accept"?: ("application/json" | "application/ld+json") & (string) } } & { accept?: "application/json" | "application/ld+json" | "*/*" }; required: true; output: ({ "data": ({ "domainData": ({ "jurisdiction"?: (string); "operatorCode"?: (string); "status"?: ("active" | "inactive") & (string) }); "recordId": (string); "revisionId": (string) }); "meta": ({ "datasetId": "facility-registry"; "recordTypeId": "operator"; "registryId": "facility-registry" }) }) | ({ "@context": "https://id.registrystack.org/contexts/registry-record/v1"; "data": ({ "domainData": ({ "jurisdiction"?: (string); "operatorCode"?: (string); "status"?: ("active" | "inactive") & (string) }); "recordId": (string); "revisionId": (string) }); "meta": ({ "datasetId": "facility-registry"; "recordTypeId": "operator"; "registryId": "facility-registry" }) }) } - "records.operator.patch": { input: CallOptions & { path: { "record_id": (string) } } & { query?: { "accessProfile"?: "operator-editor" } } & { headers: { "traceparent"?: (string); "If-Match": (string); "Accept"?: ("application/json" | "application/ld+json") & (string) } } & ({ body: (Array<({ "op": ("add" | "replace" | "remove" | "test") & (string); "path": (string); "value"?: JsonValue })>) }) & { accept?: "application/json" | "application/ld+json" | "*/*" }; required: true; output: ({ "data": ({ "domainData": Schema_operator; "recordId": (string); "revisionId": (string) }); "meta": ({ "datasetId": "facility-registry"; "recordTypeId": "operator"; "registryId": "facility-registry" }) }) | ({ "@context": "https://id.registrystack.org/contexts/registry-record/v1"; "data": ({ "domainData": Schema_operator; "recordId": (string); "revisionId": (string) }); "meta": ({ "datasetId": "facility-registry"; "recordTypeId": "operator"; "registryId": "facility-registry" }) }) } + "records.operator.patch": { input: CallOptions & { path: { "record_id": (string) } } & { query?: { "accessProfile"?: "operator-editor" } } & { headers: { "traceparent"?: (string); "If-Match": (string); "Accept"?: ("application/json" | "application/ld+json") & (string) } } & ({ body: (Array<(({ "op": "add"; "path": ("/data/jurisdiction" | "/data/operatorCode" | "/data/status") & (string); "value": JsonValue }) | ({ "op": "replace"; "path": ("/data/jurisdiction" | "/data/operatorCode" | "/data/status") & (string); "value": JsonValue }) | ({ "op": "test"; "path": ("/data/jurisdiction" | "/data/operatorCode" | "/data/status") & (string); "value": JsonValue }))>) }) & { accept?: "application/json" | "application/ld+json" | "*/*" }; required: true; output: ({ "data": ({ "domainData": Schema_operator; "recordId": (string); "revisionId": (string) }); "meta": ({ "datasetId": "facility-registry"; "recordTypeId": "operator"; "registryId": "facility-registry" }) }) | ({ "@context": "https://id.registrystack.org/contexts/registry-record/v1"; "data": ({ "domainData": Schema_operator; "recordId": (string); "revisionId": (string) }); "meta": ({ "datasetId": "facility-registry"; "recordTypeId": "operator"; "registryId": "facility-registry" }) }) } "receiveReviewCompletion": { input: CallOptions & { headers: { "Registry-Recipient-Binding": (string); "webhook-id": (string); "webhook-timestamp": (string); "webhook-signature": (string) } } & ({ body: Uint8Array }); required: true; output: undefined } } @@ -167,7 +171,7 @@ const rules: Record = Object.fromEntries([ ["/paths/~1v1~1proposals/get/responses/404/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"resource.not-found\"]}},\"type\":\"object\"}]}")], ["/paths/~1v1~1proposals/get/responses/503/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"service.unavailable\",\"source.unavailable\"]}},\"type\":\"object\"}]}")], ["/paths/~1v1~1proposals/get/responses/504/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"request.timeout\"]}},\"type\":\"object\"}]}")], - ["/paths/~1v1~1proposals~1review-context/get/responses/200/content/application~1json/schema", JSON.parse("{\"additionalProperties\":false,\"properties\":{\"items\":{\"items\":{\"oneOf\":[{\"additionalProperties\":false,\"properties\":{\"context\":{\"additionalProperties\":false,\"properties\":{\"actionId\":{\"type\":\"string\"},\"actionRevision\":{\"type\":\"string\"},\"authority\":{\"type\":\"string\"},\"context\":{\"additionalProperties\":false,\"properties\":{\"contract\":{\"additionalProperties\":false,\"properties\":{\"id\":{\"maxLength\":2048,\"pattern\":\"^urn:registry:breg:review-context:\",\"type\":\"string\"},\"revision\":{\"pattern\":\"^sha256:[0-9a-f]{64}$\",\"type\":\"string\"},\"schemaDigest\":{\"pattern\":\"^sha256:[0-9a-f]{64}$\",\"type\":\"string\"}},\"required\":[\"id\",\"revision\",\"schemaDigest\"],\"type\":\"object\"},\"fields\":{\"type\":\"object\"},\"reference\":{\"type\":\"string\"}},\"required\":[\"reference\",\"contract\",\"fields\"],\"type\":\"object\"},\"effectDigest\":{\"type\":\"string\"},\"id\":{\"type\":\"string\"},\"policy\":{\"additionalProperties\":false,\"properties\":{\"digest\":{\"type\":\"string\"},\"id\":{\"type\":\"string\"},\"version\":{\"type\":\"string\"}},\"required\":[\"id\",\"version\",\"digest\"],\"type\":\"object\"},\"result\":{\"additionalProperties\":false,\"properties\":{\"availableUntil\":{\"type\":\"string\"},\"completedAt\":{\"type\":\"string\"},\"resultId\":{\"type\":\"string\"},\"state\":{\"enum\":[\"pending\",\"approved\",\"rejected\",\"changes-requested\",\"answered\",\"cancelled\",\"superseded\",\"expired\"]}},\"required\":[\"state\"],\"type\":\"object\"},\"reviewable\":{\"type\":\"boolean\"},\"revision\":{\"minimum\":1,\"type\":\"integer\"},\"subject\":{\"additionalProperties\":false,\"properties\":{\"digest\":{\"type\":\"string\"},\"id\":{\"type\":\"string\"},\"source\":{\"type\":\"string\"},\"subjectType\":{\"const\":\"proposal\"},\"version\":{\"type\":\"string\"}},\"required\":[\"source\",\"subjectType\",\"id\",\"version\",\"digest\"],\"type\":\"object\"},\"submissionVersion\":{\"minimum\":1,\"type\":\"integer\"}},\"required\":[\"id\",\"actionId\",\"actionRevision\",\"submissionVersion\",\"revision\",\"effectDigest\",\"subject\",\"context\",\"reviewable\"],\"type\":\"object\"},\"id\":{\"type\":\"string\"},\"status\":{\"const\":\"visible\"}},\"required\":[\"id\",\"status\",\"context\"],\"type\":\"object\"},{\"additionalProperties\":false,\"properties\":{\"id\":{\"type\":\"string\"},\"status\":{\"const\":\"concealed\"}},\"required\":[\"id\",\"status\"],\"type\":\"object\"}]},\"maxItems\":100,\"minItems\":1,\"type\":\"array\"}},\"required\":[\"items\"],\"type\":\"object\"}")], + ["/paths/~1v1~1proposals~1review-context/get/responses/200/content/application~1json/schema", JSON.parse("{\"additionalProperties\":false,\"properties\":{\"items\":{\"items\":{\"oneOf\":[{\"additionalProperties\":false,\"properties\":{\"context\":{\"additionalProperties\":false,\"properties\":{\"actionId\":{\"type\":\"string\"},\"actionRevision\":{\"type\":\"string\"},\"authority\":{\"type\":\"string\"},\"context\":{\"additionalProperties\":false,\"properties\":{\"contract\":{\"additionalProperties\":false,\"properties\":{\"id\":{\"maxLength\":2048,\"pattern\":\"^urn:registry:breg:review-context:\",\"type\":\"string\"},\"revision\":{\"pattern\":\"^sha256:[0-9a-f]{64}$\",\"type\":\"string\"},\"schemaDigest\":{\"pattern\":\"^sha256:[0-9a-f]{64}$\",\"type\":\"string\"}},\"required\":[\"id\",\"revision\",\"schemaDigest\"],\"type\":\"object\"},\"fields\":{\"type\":\"object\"},\"reference\":{\"type\":\"string\"}},\"required\":[\"reference\",\"contract\",\"fields\"],\"type\":\"object\"},\"effectDigest\":{\"type\":\"string\"},\"id\":{\"type\":\"string\"},\"policy\":{\"oneOf\":[{\"additionalProperties\":false,\"properties\":{\"id\":{\"type\":\"string\"}},\"required\":[\"id\"],\"type\":\"object\"},{\"additionalProperties\":false,\"properties\":{\"digest\":{\"type\":\"string\"},\"id\":{\"type\":\"string\"},\"version\":{\"type\":\"string\"}},\"required\":[\"id\",\"version\",\"digest\"],\"type\":\"object\"}]},\"result\":{\"additionalProperties\":false,\"properties\":{\"availableUntil\":{\"type\":\"string\"},\"completedAt\":{\"type\":\"string\"},\"resultId\":{\"type\":\"string\"},\"state\":{\"enum\":[\"pending\",\"approved\",\"rejected\",\"changes-requested\",\"answered\",\"cancelled\",\"superseded\",\"expired\"]}},\"required\":[\"state\"],\"type\":\"object\"},\"reviewable\":{\"type\":\"boolean\"},\"revision\":{\"minimum\":1,\"type\":\"integer\"},\"subject\":{\"additionalProperties\":false,\"properties\":{\"digest\":{\"type\":\"string\"},\"id\":{\"type\":\"string\"},\"source\":{\"type\":\"string\"},\"subjectType\":{\"const\":\"proposal\"},\"version\":{\"type\":\"string\"}},\"required\":[\"source\",\"subjectType\",\"id\",\"version\",\"digest\"],\"type\":\"object\"},\"submissionVersion\":{\"minimum\":1,\"type\":\"integer\"}},\"required\":[\"id\",\"actionId\",\"actionRevision\",\"submissionVersion\",\"revision\",\"effectDigest\",\"subject\",\"context\",\"reviewable\"],\"type\":\"object\"},\"id\":{\"type\":\"string\"},\"status\":{\"const\":\"visible\"}},\"required\":[\"id\",\"status\",\"context\"],\"type\":\"object\"},{\"additionalProperties\":false,\"properties\":{\"id\":{\"type\":\"string\"},\"status\":{\"const\":\"concealed\"}},\"required\":[\"id\",\"status\"],\"type\":\"object\"}]},\"maxItems\":100,\"minItems\":1,\"type\":\"array\"}},\"required\":[\"items\"],\"type\":\"object\"}")], ["/paths/~1v1~1proposals~1review-context/get/responses/400/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"access-profile.ambiguous\"]}},\"type\":\"object\"}]}")], ["/paths/~1v1~1proposals~1review-context/get/responses/401/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"authentication.refused\"]}},\"type\":\"object\"}]}")], ["/paths/~1v1~1proposals~1review-context/get/responses/403/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"profile.not-authorized\"]}},\"type\":\"object\"}]}")], @@ -271,14 +275,14 @@ const rules: Record = Object.fromEntries([ ["/paths/~1v1~1proposals~1{proposal_id}~1retry/post/responses/428/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"precondition.required\"]}},\"type\":\"object\"}]}")], ["/paths/~1v1~1proposals~1{proposal_id}~1retry/post/responses/503/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"service.unavailable\",\"source.unavailable\"]}},\"type\":\"object\"}]}")], ["/paths/~1v1~1proposals~1{proposal_id}~1retry/post/responses/504/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"request.timeout\"]}},\"type\":\"object\"}]}")], - ["/paths/~1v1~1proposals~1{proposal_id}~1review-context/get/responses/200/content/application~1json/schema", JSON.parse("{\"additionalProperties\":false,\"properties\":{\"actionId\":{\"type\":\"string\"},\"actionRevision\":{\"type\":\"string\"},\"authority\":{\"type\":\"string\"},\"context\":{\"additionalProperties\":false,\"properties\":{\"asks\":{\"items\":{\"additionalProperties\":false,\"properties\":{\"answer\":{\"additionalProperties\":false,\"properties\":{\"answeredAt\":{\"type\":\"string\"},\"documents\":{\"items\":{\"additionalProperties\":false,\"properties\":{\"byteSize\":{\"maximum\":16777216,\"minimum\":1,\"type\":\"integer\"},\"contentType\":{\"maxLength\":255,\"type\":\"string\"},\"download\":{\"additionalProperties\":false,\"properties\":{\"accessProfile\":{\"type\":\"string\"},\"method\":{\"const\":\"GET\"},\"operation\":{\"const\":\"get-review-context\"},\"path\":{\"type\":\"string\"}},\"required\":[\"method\",\"operation\",\"accessProfile\",\"path\"],\"type\":\"object\"},\"id\":{\"type\":\"string\"},\"sha256\":{\"pattern\":\"^[0-9a-f]{64}$\",\"type\":\"string\"},\"verificationStatus\":{\"enum\":[\"notRequired\",\"pending\",\"approved\",\"rejected\"]}},\"required\":[\"id\",\"sha256\",\"contentType\",\"byteSize\",\"verificationStatus\"],\"type\":\"object\"},\"maxItems\":32,\"type\":\"array\"},\"formEntries\":{\"items\":{\"additionalProperties\":false,\"oneOf\":[{\"not\":{\"required\":[\"contractChanged\"]},\"required\":[\"input\"]},{\"not\":{\"required\":[\"input\"]},\"required\":[\"contractChanged\"]}],\"properties\":{\"addedAt\":{\"type\":\"string\"},\"contractChanged\":{\"const\":true},\"id\":{\"type\":\"string\"},\"input\":{\"maxProperties\":16,\"minProperties\":1,\"type\":\"object\"}},\"required\":[\"id\",\"addedAt\"],\"type\":\"object\"},\"maxItems\":32,\"type\":\"array\"},\"text\":{\"maxLength\":2000,\"minLength\":1,\"type\":\"string\"}},\"required\":[\"documents\",\"answeredAt\"],\"type\":\"object\"},\"askedAt\":{\"type\":\"string\"},\"dueAt\":{\"type\":\"string\"},\"id\":{\"type\":\"string\"},\"state\":{\"enum\":[\"open\",\"answered\",\"expired\",\"closed\"]},\"text\":{\"maxLength\":2000,\"minLength\":1,\"type\":\"string\"},\"wants\":{\"items\":{\"oneOf\":[{\"additionalProperties\":false,\"properties\":{\"kind\":{\"enum\":[\"answer\",\"document\"]}},\"required\":[\"kind\"],\"type\":\"object\"},{\"additionalProperties\":false,\"properties\":{\"form\":{\"pattern\":\"^[a-z][a-z0-9_-]{0,63}$\",\"type\":\"string\"},\"kind\":{\"const\":\"form\"}},\"required\":[\"kind\",\"form\"],\"type\":\"object\"}]},\"maxItems\":8,\"type\":\"array\",\"uniqueItems\":true}},\"required\":[\"id\",\"text\",\"wants\",\"askedAt\",\"state\"],\"type\":\"object\"},\"maxItems\":50,\"type\":\"array\"},\"contract\":{\"additionalProperties\":false,\"properties\":{\"id\":{\"maxLength\":2048,\"pattern\":\"^urn:registry:breg:review-context:\",\"type\":\"string\"},\"revision\":{\"pattern\":\"^sha256:[0-9a-f]{64}$\",\"type\":\"string\"},\"schemaDigest\":{\"pattern\":\"^sha256:[0-9a-f]{64}$\",\"type\":\"string\"}},\"required\":[\"id\",\"revision\",\"schemaDigest\"],\"type\":\"object\"},\"fields\":{\"type\":\"object\"},\"reference\":{\"type\":\"string\"}},\"required\":[\"reference\",\"contract\",\"fields\"],\"type\":\"object\"},\"effectDigest\":{\"type\":\"string\"},\"id\":{\"type\":\"string\"},\"policy\":{\"additionalProperties\":false,\"properties\":{\"digest\":{\"type\":\"string\"},\"id\":{\"type\":\"string\"},\"version\":{\"type\":\"string\"}},\"required\":[\"id\",\"version\",\"digest\"],\"type\":\"object\"},\"result\":{\"additionalProperties\":false,\"properties\":{\"availableUntil\":{\"type\":\"string\"},\"completedAt\":{\"type\":\"string\"},\"resultId\":{\"type\":\"string\"},\"state\":{\"enum\":[\"pending\",\"approved\",\"rejected\",\"changes-requested\",\"answered\",\"cancelled\",\"superseded\",\"expired\"]}},\"required\":[\"state\"],\"type\":\"object\"},\"reviewable\":{\"type\":\"boolean\"},\"revision\":{\"minimum\":1,\"type\":\"integer\"},\"subject\":{\"additionalProperties\":false,\"properties\":{\"digest\":{\"type\":\"string\"},\"id\":{\"type\":\"string\"},\"source\":{\"type\":\"string\"},\"subjectType\":{\"const\":\"proposal\"},\"version\":{\"type\":\"string\"}},\"required\":[\"source\",\"subjectType\",\"id\",\"version\",\"digest\"],\"type\":\"object\"},\"submissionVersion\":{\"minimum\":1,\"type\":\"integer\"}},\"required\":[\"id\",\"actionId\",\"actionRevision\",\"submissionVersion\",\"revision\",\"effectDigest\",\"subject\",\"context\",\"reviewable\"],\"type\":\"object\"}")], + ["/paths/~1v1~1proposals~1{proposal_id}~1review-context/get/responses/200/content/application~1json/schema", JSON.parse("{\"additionalProperties\":false,\"properties\":{\"actionId\":{\"type\":\"string\"},\"actionRevision\":{\"type\":\"string\"},\"authority\":{\"type\":\"string\"},\"context\":{\"additionalProperties\":false,\"properties\":{\"asks\":{\"items\":{\"additionalProperties\":false,\"properties\":{\"answer\":{\"additionalProperties\":false,\"properties\":{\"answeredAt\":{\"type\":\"string\"},\"documents\":{\"items\":{\"additionalProperties\":false,\"properties\":{\"byteSize\":{\"maximum\":16777216,\"minimum\":1,\"type\":\"integer\"},\"contentType\":{\"maxLength\":255,\"type\":\"string\"},\"download\":{\"additionalProperties\":false,\"properties\":{\"accessProfile\":{\"type\":\"string\"},\"method\":{\"const\":\"GET\"},\"operation\":{\"const\":\"get-review-context\"},\"path\":{\"type\":\"string\"}},\"required\":[\"method\",\"operation\",\"accessProfile\",\"path\"],\"type\":\"object\"},\"id\":{\"type\":\"string\"},\"sha256\":{\"pattern\":\"^[0-9a-f]{64}$\",\"type\":\"string\"},\"verificationStatus\":{\"enum\":[\"notRequired\",\"pending\",\"approved\",\"rejected\"]}},\"required\":[\"id\",\"sha256\",\"contentType\",\"byteSize\",\"verificationStatus\"],\"type\":\"object\"},\"maxItems\":32,\"type\":\"array\"},\"formEntries\":{\"items\":{\"additionalProperties\":false,\"oneOf\":[{\"not\":{\"required\":[\"contractChanged\"]},\"required\":[\"input\"]},{\"not\":{\"required\":[\"input\"]},\"required\":[\"contractChanged\"]}],\"properties\":{\"addedAt\":{\"type\":\"string\"},\"contractChanged\":{\"const\":true},\"id\":{\"type\":\"string\"},\"input\":{\"maxProperties\":16,\"minProperties\":1,\"type\":\"object\"}},\"required\":[\"id\",\"addedAt\"],\"type\":\"object\"},\"maxItems\":32,\"type\":\"array\"},\"text\":{\"maxLength\":2000,\"minLength\":1,\"type\":\"string\"}},\"required\":[\"documents\",\"answeredAt\"],\"type\":\"object\"},\"askedAt\":{\"type\":\"string\"},\"dueAt\":{\"type\":\"string\"},\"id\":{\"type\":\"string\"},\"state\":{\"enum\":[\"open\",\"answered\",\"expired\",\"closed\"]},\"text\":{\"maxLength\":2000,\"minLength\":1,\"type\":\"string\"},\"wants\":{\"items\":{\"oneOf\":[{\"additionalProperties\":false,\"properties\":{\"kind\":{\"enum\":[\"answer\",\"document\"]}},\"required\":[\"kind\"],\"type\":\"object\"},{\"additionalProperties\":false,\"properties\":{\"form\":{\"pattern\":\"^[a-z][a-z0-9_-]{0,63}$\",\"type\":\"string\"},\"kind\":{\"const\":\"form\"}},\"required\":[\"kind\",\"form\"],\"type\":\"object\"}]},\"maxItems\":8,\"type\":\"array\",\"uniqueItems\":true}},\"required\":[\"id\",\"text\",\"wants\",\"askedAt\",\"state\"],\"type\":\"object\"},\"maxItems\":50,\"type\":\"array\"},\"contract\":{\"additionalProperties\":false,\"properties\":{\"id\":{\"maxLength\":2048,\"pattern\":\"^urn:registry:breg:review-context:\",\"type\":\"string\"},\"revision\":{\"pattern\":\"^sha256:[0-9a-f]{64}$\",\"type\":\"string\"},\"schemaDigest\":{\"pattern\":\"^sha256:[0-9a-f]{64}$\",\"type\":\"string\"}},\"required\":[\"id\",\"revision\",\"schemaDigest\"],\"type\":\"object\"},\"fields\":{\"type\":\"object\"},\"reference\":{\"type\":\"string\"}},\"required\":[\"reference\",\"contract\",\"fields\"],\"type\":\"object\"},\"effectDigest\":{\"type\":\"string\"},\"id\":{\"type\":\"string\"},\"policy\":{\"oneOf\":[{\"additionalProperties\":false,\"properties\":{\"id\":{\"type\":\"string\"}},\"required\":[\"id\"],\"type\":\"object\"},{\"additionalProperties\":false,\"properties\":{\"digest\":{\"type\":\"string\"},\"id\":{\"type\":\"string\"},\"version\":{\"type\":\"string\"}},\"required\":[\"id\",\"version\",\"digest\"],\"type\":\"object\"}]},\"result\":{\"additionalProperties\":false,\"properties\":{\"availableUntil\":{\"type\":\"string\"},\"completedAt\":{\"type\":\"string\"},\"resultId\":{\"type\":\"string\"},\"state\":{\"enum\":[\"pending\",\"approved\",\"rejected\",\"changes-requested\",\"answered\",\"cancelled\",\"superseded\",\"expired\"]}},\"required\":[\"state\"],\"type\":\"object\"},\"reviewable\":{\"type\":\"boolean\"},\"revision\":{\"minimum\":1,\"type\":\"integer\"},\"subject\":{\"additionalProperties\":false,\"properties\":{\"digest\":{\"type\":\"string\"},\"id\":{\"type\":\"string\"},\"source\":{\"type\":\"string\"},\"subjectType\":{\"const\":\"proposal\"},\"version\":{\"type\":\"string\"}},\"required\":[\"source\",\"subjectType\",\"id\",\"version\",\"digest\"],\"type\":\"object\"},\"submissionVersion\":{\"minimum\":1,\"type\":\"integer\"}},\"required\":[\"id\",\"actionId\",\"actionRevision\",\"submissionVersion\",\"revision\",\"effectDigest\",\"subject\",\"context\",\"reviewable\"],\"type\":\"object\"}")], ["/paths/~1v1~1proposals~1{proposal_id}~1review-context/get/responses/400/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"access-profile.ambiguous\"]}},\"type\":\"object\"}]}")], ["/paths/~1v1~1proposals~1{proposal_id}~1review-context/get/responses/401/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"authentication.refused\"]}},\"type\":\"object\"}]}")], ["/paths/~1v1~1proposals~1{proposal_id}~1review-context/get/responses/403/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"profile.not-authorized\"]}},\"type\":\"object\"}]}")], ["/paths/~1v1~1proposals~1{proposal_id}~1review-context/get/responses/404/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"resource.not-found\"]}},\"type\":\"object\"}]}")], ["/paths/~1v1~1proposals~1{proposal_id}~1review-context/get/responses/503/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"service.unavailable\",\"source.unavailable\"]}},\"type\":\"object\"}]}")], ["/paths/~1v1~1proposals~1{proposal_id}~1review-context/get/responses/504/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"request.timeout\"]}},\"type\":\"object\"}]}")], - ["/paths/~1v1~1proposals~1{proposal_id}~1review-status/get/responses/200/content/application~1json/schema", JSON.parse("{\"additionalProperties\":false,\"properties\":{\"actionId\":{\"type\":\"string\"},\"actionRevision\":{\"type\":\"string\"},\"authority\":{\"type\":\"string\"},\"context\":{\"additionalProperties\":false,\"properties\":{\"contract\":{\"additionalProperties\":false,\"properties\":{\"id\":{\"maxLength\":2048,\"pattern\":\"^urn:registry:breg:review-context:\",\"type\":\"string\"},\"revision\":{\"pattern\":\"^sha256:[0-9a-f]{64}$\",\"type\":\"string\"},\"schemaDigest\":{\"pattern\":\"^sha256:[0-9a-f]{64}$\",\"type\":\"string\"}},\"required\":[\"id\",\"revision\",\"schemaDigest\"],\"type\":\"object\"},\"reference\":{\"type\":\"string\"}},\"required\":[\"reference\"],\"type\":\"object\"},\"effectDigest\":{\"type\":\"string\"},\"handoff\":{\"additionalProperties\":false,\"properties\":{\"reason\":{\"enum\":[\"remote-refused\",\"producer-identity-mismatch\",\"review-acceptance-changed\",\"review-policy-changed\",\"submission-recovery-expired\",\"operator-closed\",\"unspecified\"]},\"state\":{\"enum\":[\"pending\",\"accepted\",\"failed\",\"withdrawn\"]}},\"required\":[\"state\"],\"type\":\"object\"},\"id\":{\"type\":\"string\"},\"policy\":{\"additionalProperties\":false,\"properties\":{\"digest\":{\"type\":\"string\"},\"id\":{\"type\":\"string\"},\"version\":{\"type\":\"string\"}},\"required\":[\"id\",\"version\",\"digest\"],\"type\":\"object\"},\"progressCode\":{\"maxLength\":64,\"pattern\":\"^[a-z][a-z0-9_-]{0,63}$\",\"type\":\"string\"},\"requestId\":{\"type\":\"string\"},\"result\":{\"additionalProperties\":false,\"properties\":{\"availableUntil\":{\"type\":\"string\"},\"completedAt\":{\"type\":\"string\"},\"resultId\":{\"type\":\"string\"},\"state\":{\"enum\":[\"pending\",\"approved\",\"rejected\",\"changes-requested\",\"answered\",\"cancelled\",\"superseded\",\"expired\"]}},\"required\":[\"state\"],\"type\":\"object\"},\"reviewable\":{\"type\":\"boolean\"},\"revision\":{\"minimum\":1,\"type\":\"integer\"},\"subject\":{\"additionalProperties\":false,\"properties\":{\"digest\":{\"type\":\"string\"},\"id\":{\"type\":\"string\"},\"source\":{\"type\":\"string\"},\"subjectType\":{\"const\":\"proposal\"},\"version\":{\"type\":\"string\"}},\"required\":[\"source\",\"subjectType\",\"id\",\"version\",\"digest\"],\"type\":\"object\"},\"submissionVersion\":{\"minimum\":1,\"type\":\"integer\"}},\"required\":[\"id\",\"actionId\",\"actionRevision\",\"submissionVersion\",\"revision\",\"effectDigest\",\"subject\",\"context\",\"reviewable\"],\"type\":\"object\"}")], + ["/paths/~1v1~1proposals~1{proposal_id}~1review-status/get/responses/200/content/application~1json/schema", JSON.parse("{\"additionalProperties\":false,\"properties\":{\"actionId\":{\"type\":\"string\"},\"actionRevision\":{\"type\":\"string\"},\"authority\":{\"type\":\"string\"},\"context\":{\"additionalProperties\":false,\"properties\":{\"contract\":{\"additionalProperties\":false,\"properties\":{\"id\":{\"maxLength\":2048,\"pattern\":\"^urn:registry:breg:review-context:\",\"type\":\"string\"},\"revision\":{\"pattern\":\"^sha256:[0-9a-f]{64}$\",\"type\":\"string\"},\"schemaDigest\":{\"pattern\":\"^sha256:[0-9a-f]{64}$\",\"type\":\"string\"}},\"required\":[\"id\",\"revision\",\"schemaDigest\"],\"type\":\"object\"},\"reference\":{\"type\":\"string\"}},\"required\":[\"reference\"],\"type\":\"object\"},\"effectDigest\":{\"type\":\"string\"},\"handoff\":{\"additionalProperties\":false,\"properties\":{\"reason\":{\"enum\":[\"remote-refused\",\"producer-identity-mismatch\",\"review-acceptance-changed\",\"review-policy-changed\",\"submission-recovery-expired\",\"operator-closed\",\"unspecified\"]},\"state\":{\"enum\":[\"pending\",\"accepted\",\"failed\",\"withdrawn\"]}},\"required\":[\"state\"],\"type\":\"object\"},\"id\":{\"type\":\"string\"},\"policy\":{\"oneOf\":[{\"additionalProperties\":false,\"properties\":{\"id\":{\"type\":\"string\"}},\"required\":[\"id\"],\"type\":\"object\"},{\"additionalProperties\":false,\"properties\":{\"digest\":{\"type\":\"string\"},\"id\":{\"type\":\"string\"},\"version\":{\"type\":\"string\"}},\"required\":[\"id\",\"version\",\"digest\"],\"type\":\"object\"}]},\"progressCode\":{\"maxLength\":64,\"pattern\":\"^[a-z][a-z0-9_-]{0,63}$\",\"type\":\"string\"},\"requestId\":{\"type\":\"string\"},\"result\":{\"additionalProperties\":false,\"properties\":{\"availableUntil\":{\"type\":\"string\"},\"completedAt\":{\"type\":\"string\"},\"resultId\":{\"type\":\"string\"},\"state\":{\"enum\":[\"pending\",\"approved\",\"rejected\",\"changes-requested\",\"answered\",\"cancelled\",\"superseded\",\"expired\"]}},\"required\":[\"state\"],\"type\":\"object\"},\"reviewable\":{\"type\":\"boolean\"},\"revision\":{\"minimum\":1,\"type\":\"integer\"},\"subject\":{\"additionalProperties\":false,\"properties\":{\"digest\":{\"type\":\"string\"},\"id\":{\"type\":\"string\"},\"source\":{\"type\":\"string\"},\"subjectType\":{\"const\":\"proposal\"},\"version\":{\"type\":\"string\"}},\"required\":[\"source\",\"subjectType\",\"id\",\"version\",\"digest\"],\"type\":\"object\"},\"submissionVersion\":{\"minimum\":1,\"type\":\"integer\"}},\"required\":[\"id\",\"actionId\",\"actionRevision\",\"submissionVersion\",\"revision\",\"effectDigest\",\"subject\",\"context\",\"reviewable\"],\"type\":\"object\"}")], ["/paths/~1v1~1proposals~1{proposal_id}~1review-status/get/responses/400/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"access-profile.ambiguous\"]}},\"type\":\"object\"}]}")], ["/paths/~1v1~1proposals~1{proposal_id}~1review-status/get/responses/401/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"authentication.refused\"]}},\"type\":\"object\"}]}")], ["/paths/~1v1~1proposals~1{proposal_id}~1review-status/get/responses/403/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"profile.not-authorized\"]}},\"type\":\"object\"}]}")], diff --git a/clients/typescript/generated/breg-minimal.ts b/clients/typescript/generated/breg-minimal.ts index 0b83a11d31..09df548a04 100644 --- a/clients/typescript/generated/breg-minimal.ts +++ b/clients/typescript/generated/breg-minimal.ts @@ -1,6 +1,8 @@ // Generated for Stack version 0.52.0, client version 0.52.0. -// Source SHA-256 a0c571c73a3d832ce42d500fd151a8d72947955a848e0a138e9dfbed0b08ff78 -// Unconstrained JSON /paths/~1v1~1records~1contacts~1{record_id}/patch/requestBody/content/application~1json-patch+json/schema/items/properties/value +// Source SHA-256 13e08ab78e0288597af557e82fdce29c82ecd8ff2eff395da92cddfe7c6198a5 +// Unconstrained JSON /paths/~1v1~1records~1contacts~1{record_id}/patch/requestBody/content/application~1json-patch+json/schema/items/oneOf/0/properties/value +// Unconstrained JSON /paths/~1v1~1records~1contacts~1{record_id}/patch/requestBody/content/application~1json-patch+json/schema/items/oneOf/1/properties/value +// Unconstrained JSON /paths/~1v1~1records~1contacts~1{record_id}/patch/requestBody/content/application~1json-patch+json/schema/items/oneOf/2/properties/value import { assertClientVersion, type Transport, type Answer, type CallOptions, type JsonValue, type Operation, type Page, type RequestValues, type ResponseVariant, type WireBytes, type WireText } from "../core.ts" import { actionAvailability, type ActionAvailability, type DescribeOptions } from "../core.ts" import { sentence } from "../core.ts" @@ -36,7 +38,7 @@ export interface Operations { "records.contact.list": { input: CallOptions & { query?: { "accessProfile"?: "directory-editor"; "$select"?: (string); "$filter"?: (string); "$orderby"?: (string); "limit"?: (number); "$count"?: (boolean); "cursor"?: (string) } } & { headers?: { "traceparent"?: (string); "Accept"?: ("application/json" | "application/ld+json") & (string) } } & { accept?: "application/json" | "application/ld+json" | "*/*" }; required: false; output: ({ "count"?: (number); "items": (Array<({ "domainData": ({ "email"?: (string); "jurisdiction"?: (string); "name"?: (string) }); "recordId": (string); "revisionId": (string) })>); "meta": ({ "datasetId": "directory"; "recordTypeId": "contact"; "registryId": "local-directory" }); "pageInfo": ({ "nextCursor": (string | null) }) }) | ({ "@context": "https://id.registrystack.org/contexts/registry-record/v1"; "count"?: (number); "items": (Array<({ "domainData": ({ "email"?: (string); "jurisdiction"?: (string); "name"?: (string) }); "recordId": (string); "revisionId": (string) })>); "meta": ({ "datasetId": "directory"; "recordTypeId": "contact"; "registryId": "local-directory" }); "pageInfo": ({ "nextCursor": (string | null) }) }) } "records.contact.create": { input: CallOptions & { query?: { "accessProfile"?: "directory-editor" } } & { headers?: { "traceparent"?: (string); "Accept"?: ("application/json" | "application/ld+json") & (string) } } & ({ body: ({ "data": Schema_contact_create_input }) }) & { accept?: "application/json" | "application/ld+json" | "*/*" }; required: true; output: ({ "data": ({ "domainData": Schema_contact; "recordId": (string); "revisionId": (string) }); "meta": ({ "datasetId": "directory"; "recordTypeId": "contact"; "registryId": "local-directory" }) }) | ({ "@context": "https://id.registrystack.org/contexts/registry-record/v1"; "data": ({ "domainData": Schema_contact; "recordId": (string); "revisionId": (string) }); "meta": ({ "datasetId": "directory"; "recordTypeId": "contact"; "registryId": "local-directory" }) }) } "records.contact.get": { input: CallOptions & { path: { "record_id": (string) } } & { query?: { "accessProfile"?: "directory-editor"; "$select"?: (string) } } & { headers?: { "traceparent"?: (string); "Accept"?: ("application/json" | "application/ld+json") & (string) } } & { accept?: "application/json" | "application/ld+json" | "*/*" }; required: true; output: ({ "data": ({ "domainData": ({ "email"?: (string); "jurisdiction"?: (string); "name"?: (string) }); "recordId": (string); "revisionId": (string) }); "meta": ({ "datasetId": "directory"; "recordTypeId": "contact"; "registryId": "local-directory" }) }) | ({ "@context": "https://id.registrystack.org/contexts/registry-record/v1"; "data": ({ "domainData": ({ "email"?: (string); "jurisdiction"?: (string); "name"?: (string) }); "recordId": (string); "revisionId": (string) }); "meta": ({ "datasetId": "directory"; "recordTypeId": "contact"; "registryId": "local-directory" }) }) } - "records.contact.patch": { input: CallOptions & { path: { "record_id": (string) } } & { query?: { "accessProfile"?: "directory-editor" } } & { headers: { "traceparent"?: (string); "If-Match": (string); "Accept"?: ("application/json" | "application/ld+json") & (string) } } & ({ body: (Array<({ "op": ("add" | "replace" | "remove" | "test") & (string); "path": (string); "value"?: JsonValue })>) }) & { accept?: "application/json" | "application/ld+json" | "*/*" }; required: true; output: ({ "data": ({ "domainData": Schema_contact; "recordId": (string); "revisionId": (string) }); "meta": ({ "datasetId": "directory"; "recordTypeId": "contact"; "registryId": "local-directory" }) }) | ({ "@context": "https://id.registrystack.org/contexts/registry-record/v1"; "data": ({ "domainData": Schema_contact; "recordId": (string); "revisionId": (string) }); "meta": ({ "datasetId": "directory"; "recordTypeId": "contact"; "registryId": "local-directory" }) }) } + "records.contact.patch": { input: CallOptions & { path: { "record_id": (string) } } & { query?: { "accessProfile"?: "directory-editor" } } & { headers: { "traceparent"?: (string); "If-Match": (string); "Accept"?: ("application/json" | "application/ld+json") & (string) } } & ({ body: (Array<(({ "op": "add"; "path": ("/data/email" | "/data/jurisdiction" | "/data/name") & (string); "value": JsonValue }) | ({ "op": "replace"; "path": ("/data/email" | "/data/jurisdiction" | "/data/name") & (string); "value": JsonValue }) | ({ "op": "test"; "path": ("/data/email" | "/data/jurisdiction" | "/data/name") & (string); "value": JsonValue }))>) }) & { accept?: "application/json" | "application/ld+json" | "*/*" }; required: true; output: ({ "data": ({ "domainData": Schema_contact; "recordId": (string); "revisionId": (string) }); "meta": ({ "datasetId": "directory"; "recordTypeId": "contact"; "registryId": "local-directory" }) }) | ({ "@context": "https://id.registrystack.org/contexts/registry-record/v1"; "data": ({ "domainData": Schema_contact; "recordId": (string); "revisionId": (string) }); "meta": ({ "datasetId": "directory"; "recordTypeId": "contact"; "registryId": "local-directory" }) }) } "receiveReviewCompletion": { input: CallOptions & { headers: { "Registry-Recipient-Binding": (string); "webhook-id": (string); "webhook-timestamp": (string); "webhook-signature": (string) } } & ({ body: Uint8Array }); required: true; output: undefined } } 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/clients/typescript/tests/fixtures/breg-list.openapi.json b/clients/typescript/tests/fixtures/breg-list.openapi.json index 797e496837..30b076259f 100644 --- a/clients/typescript/tests/fixtures/breg-list.openapi.json +++ b/clients/typescript/tests/fixtures/breg-list.openapi.json @@ -46,9 +46,9 @@ "maxLength": 128 } }, - "top": { + "limit": { "in": "query", - "name": "$top", + "name": "limit", "required": false, "explode": false, "schema": { @@ -66,9 +66,9 @@ "type": "boolean" } }, - "skiptoken": { + "cursor": { "in": "query", - "name": "$skiptoken", + "name": "cursor", "required": false, "explode": false, "schema": { @@ -461,13 +461,13 @@ "$ref": "#/components/parameters/orderby" }, { - "$ref": "#/components/parameters/top" + "$ref": "#/components/parameters/limit" }, { "$ref": "#/components/parameters/count" }, { - "$ref": "#/components/parameters/skiptoken" + "$ref": "#/components/parameters/cursor" } ], "responses": { @@ -556,10 +556,10 @@ "$ref": "#/components/parameters/orderby" }, { - "$ref": "#/components/parameters/top" + "$ref": "#/components/parameters/limit" }, { - "$ref": "#/components/parameters/skiptoken" + "$ref": "#/components/parameters/cursor" } ], "responses": { @@ -626,10 +626,10 @@ "$ref": "#/components/parameters/orderby" }, { - "$ref": "#/components/parameters/top" + "$ref": "#/components/parameters/limit" }, { - "$ref": "#/components/parameters/skiptoken" + "$ref": "#/components/parameters/cursor" } ], "responses": { diff --git a/clients/typescript/tests/fixtures/breg-list.ts b/clients/typescript/tests/fixtures/breg-list.ts index d0db458e30..a93255e606 100644 --- a/clients/typescript/tests/fixtures/breg-list.ts +++ b/clients/typescript/tests/fixtures/breg-list.ts @@ -1,5 +1,5 @@ // Generated for Stack version 0.52.0, client version 0.52.0. -// Source SHA-256 980a691726386db10800d31c5ebad1371d895e78ac34f58073b10e22a0644ad4 +// Source SHA-256 07990e1069b98224760b62b53e6a3d895a15cff0e5ea0a97eddaa7da5aaa18ee import { assertClientVersion, type Transport, type Answer, type CallOptions, type JsonValue, type Operation, type Page, type RequestValues, type ResponseVariant, type WireBytes, type WireText } from "../../core.ts" import { validator } from "../../schema.ts" import { listPage, listQuery, type FieldValue, type Filter, type ListPage, type ListRequest, type ListRules } from "../../core.ts" @@ -12,10 +12,10 @@ export type Schema_Permit = ({ "domainData": ({ "label"?: (string); "permitCode" export type Schema_PermitPage = ({ "items": (Array); "pageInfo": ({ "nextCursor": (string | null) }) }) export interface Operations { - "records.licence.list": { input: CallOptions & { query?: { "accessProfile"?: "licence-holder" | "licence-officer"; "$select"?: (string); "$filter"?: (string); "$orderby"?: (string); "$top"?: (number); "$count"?: (boolean); "$skiptoken"?: (string) } } & { accept?: "application/json" | "*/*" }; required: false; output: Schema_LicencePage } + "records.licence.list": { input: CallOptions & { query?: { "accessProfile"?: "licence-holder" | "licence-officer"; "$select"?: (string); "$filter"?: (string); "$orderby"?: (string); "limit"?: (number); "$count"?: (boolean); "cursor"?: (string) } } & { accept?: "application/json" | "*/*" }; required: false; output: Schema_LicencePage } "records.licence.get": { input: CallOptions & { path: { "record_id": (string) } } & { accept?: "application/json" | "*/*" }; required: true; output: ({ "data": Schema_Licence }) } - "records.site.list": { input: CallOptions & { query?: { "$select"?: (string); "$filter"?: (string); "$orderby"?: (string); "$top"?: (number); "$skiptoken"?: (string) } } & { accept?: "application/json" | "*/*" }; required: false; output: Schema_SitePage } - "records.permit.list": { input: CallOptions & { query?: { "accessProfile"?: "permit-clerk"; "$select"?: (string); "$filter"?: (string); "$orderby"?: (string); "$top"?: (number); "$skiptoken"?: (string) } } & { accept?: "application/json" | "*/*" }; required: false; output: Schema_PermitPage } + "records.site.list": { input: CallOptions & { query?: { "$select"?: (string); "$filter"?: (string); "$orderby"?: (string); "limit"?: (number); "cursor"?: (string) } } & { accept?: "application/json" | "*/*" }; required: false; output: Schema_SitePage } + "records.permit.list": { input: CallOptions & { query?: { "accessProfile"?: "permit-clerk"; "$select"?: (string); "$filter"?: (string); "$orderby"?: (string); "limit"?: (number); "cursor"?: (string) } } & { accept?: "application/json" | "*/*" }; required: false; output: Schema_PermitPage } } // The row each list returns, and the list options its query profiles allow. @@ -25,11 +25,11 @@ export interface ListRows { "permit": Schema_Permit } export interface ListOptions { - "licence": (CallOptions & { accessProfile?: "licence-holder"; where: ({ "holderId": FieldValue } | { "licenceNumber": FieldValue; "status": FieldValue }) & { "holderId"?: Filter, "equals">; "licenceNumber"?: Filter, "equals" | "in">; "status"?: Filter, "equals"> }; orderBy?: never; select?: ReadonlyArray<"licenceNumber" | "status">; count?: never; top?: number; after?: never }) | (CallOptions & { accessProfile?: "licence-holder"; after: string; where?: never; orderBy?: never; select?: never; count?: never; top?: never }) | (CallOptions & { accessProfile?: "licence-officer"; where?: { "expiresOn"?: Filter, "range">; "fee"?: Filter, "equals" | "range">; "holderName"?: Filter, "prefix" | "contains">; "region"?: Filter, "equals" | "in">; "status"?: Filter, "equals" | "in">; "suspendedOn"?: Filter, "is-null" | "is-not-null"> }; orderBy?: "expiresOn" | "holderName" | "holderName desc"; select?: ReadonlyArray<"expiresOn" | "fee" | "holderName" | "licenceNumber" | "region" | "status">; count?: boolean; top?: number; after?: never }) | (CallOptions & { accessProfile?: "licence-officer"; after: string; where?: never; orderBy?: never; select?: never; count?: never; top?: never }) - "site": (CallOptions & { accessProfile?: never; where?: { "siteCode"?: Filter, "equals"> }; orderBy?: "label"; select?: ReadonlyArray<"label" | "siteCode">; count?: never; top?: number; after?: never }) | (CallOptions & { accessProfile?: never; after: string; where?: never; orderBy?: never; select?: never; count?: never; top?: never }) - "permit": (CallOptions & { accessProfile?: "permit-clerk"; where?: { "permitCode"?: Filter, "equals"> }; orderBy?: "label"; select?: ReadonlyArray<"label" | "permitCode">; count?: never; top?: number; after?: never }) | (CallOptions & { accessProfile?: "permit-clerk"; after: string; where?: never; orderBy?: never; select?: never; count?: never; top?: never }) + "licence": (CallOptions & { accessProfile?: "licence-holder"; where: ({ "holderId": FieldValue } | { "licenceNumber": FieldValue; "status": FieldValue }) & { "holderId"?: Filter, "equals">; "licenceNumber"?: Filter, "equals" | "in">; "status"?: Filter, "equals"> }; orderBy?: never; select?: ReadonlyArray<"licenceNumber" | "status">; count?: never; limit?: number; cursor?: never }) | (CallOptions & { accessProfile?: "licence-holder"; cursor: string; where?: never; orderBy?: never; select?: never; count?: never; limit?: never }) | (CallOptions & { accessProfile?: "licence-officer"; where?: { "expiresOn"?: Filter, "range">; "fee"?: Filter, "equals" | "range">; "holderName"?: Filter, "prefix" | "contains">; "region"?: Filter, "equals" | "in">; "status"?: Filter, "equals" | "in">; "suspendedOn"?: Filter, "is-null" | "is-not-null"> }; orderBy?: "expiresOn" | "holderName" | "holderName desc"; select?: ReadonlyArray<"expiresOn" | "fee" | "holderName" | "licenceNumber" | "region" | "status">; count?: boolean; limit?: number; cursor?: never }) | (CallOptions & { accessProfile?: "licence-officer"; cursor: string; where?: never; orderBy?: never; select?: never; count?: never; limit?: never }) + "site": (CallOptions & { accessProfile?: never; where?: { "siteCode"?: Filter, "equals"> }; orderBy?: "label"; select?: ReadonlyArray<"label" | "siteCode">; count?: never; limit?: number; cursor?: never }) | (CallOptions & { accessProfile?: never; cursor: string; where?: never; orderBy?: never; select?: never; count?: never; limit?: never }) + "permit": (CallOptions & { accessProfile?: "permit-clerk"; where?: { "permitCode"?: Filter, "equals"> }; orderBy?: "label"; select?: ReadonlyArray<"label" | "permitCode">; count?: never; limit?: number; cursor?: never }) | (CallOptions & { accessProfile?: "permit-clerk"; cursor: string; where?: never; orderBy?: never; select?: never; count?: never; limit?: never }) } -const listRules: Record = JSON.parse("{\"licence\":{\"operation\":\"records.licence.list\",\"requiresAccessProfile\":false,\"accessProfileParameter\":true,\"recordProperties\":[\"expiresOn\",\"fee\",\"holderId\",\"holderName\",\"licenceNumber\",\"region\",\"status\",\"suspendedOn\"],\"profiles\":{\"licence-holder\":{\"maximumPageSize\":20,\"allowCount\":false,\"selectable\":[\"licenceNumber\",\"status\"],\"filterable\":{\"holderId\":[\"equals\"],\"licenceNumber\":[\"equals\",\"in\"],\"status\":[\"equals\"]},\"sortable\":{},\"requiredFilters\":[[\"holderId\"],[\"licenceNumber\",\"status\"]]},\"licence-officer\":{\"maximumPageSize\":50,\"allowCount\":true,\"selectable\":[\"expiresOn\",\"fee\",\"holderName\",\"licenceNumber\",\"region\",\"status\"],\"filterable\":{\"expiresOn\":[\"range\"],\"fee\":[\"equals\",\"range\"],\"holderName\":[\"prefix\",\"contains\"],\"region\":[\"equals\",\"in\"],\"status\":[\"equals\",\"in\"],\"suspendedOn\":[\"is-null\",\"is-not-null\"]},\"sortable\":{\"expiresOn\":[\"asc\"],\"holderName\":[\"asc\",\"desc\"]}}}},\"site\":{\"operation\":\"records.site.list\",\"requiresAccessProfile\":false,\"accessProfileParameter\":false,\"recordProperties\":[\"label\",\"siteCode\"],\"profiles\":{\"site-planner\":{\"maximumPageSize\":10,\"allowCount\":false,\"selectable\":[\"label\",\"siteCode\"],\"filterable\":{\"siteCode\":[\"equals\"]},\"sortable\":{\"label\":[\"asc\"]}}}},\"permit\":{\"operation\":\"records.permit.list\",\"requiresAccessProfile\":true,\"accessProfileParameter\":true,\"recordProperties\":[\"label\",\"permitCode\"],\"profiles\":{\"permit-clerk\":{\"maximumPageSize\":10,\"allowCount\":false,\"selectable\":[\"label\",\"permitCode\"],\"filterable\":{\"permitCode\":[\"equals\"]},\"sortable\":{\"label\":[\"asc\"]}}}}}") +const listRules: Record = JSON.parse("{\"licence\":{\"operation\":\"records.licence.list\",\"requiresAccessProfile\":false,\"accessProfileParameter\":true,\"paginationParameters\":{\"size\":\"limit\",\"cursor\":\"cursor\"},\"recordProperties\":[\"expiresOn\",\"fee\",\"holderId\",\"holderName\",\"licenceNumber\",\"region\",\"status\",\"suspendedOn\"],\"profiles\":{\"licence-holder\":{\"maximumPageSize\":20,\"allowCount\":false,\"selectable\":[\"licenceNumber\",\"status\"],\"filterable\":{\"holderId\":[\"equals\"],\"licenceNumber\":[\"equals\",\"in\"],\"status\":[\"equals\"]},\"sortable\":{},\"requiredFilters\":[[\"holderId\"],[\"licenceNumber\",\"status\"]]},\"licence-officer\":{\"maximumPageSize\":50,\"allowCount\":true,\"selectable\":[\"expiresOn\",\"fee\",\"holderName\",\"licenceNumber\",\"region\",\"status\"],\"filterable\":{\"expiresOn\":[\"range\"],\"fee\":[\"equals\",\"range\"],\"holderName\":[\"prefix\",\"contains\"],\"region\":[\"equals\",\"in\"],\"status\":[\"equals\",\"in\"],\"suspendedOn\":[\"is-null\",\"is-not-null\"]},\"sortable\":{\"expiresOn\":[\"asc\"],\"holderName\":[\"asc\",\"desc\"]}}}},\"site\":{\"operation\":\"records.site.list\",\"requiresAccessProfile\":false,\"accessProfileParameter\":false,\"paginationParameters\":{\"size\":\"limit\",\"cursor\":\"cursor\"},\"recordProperties\":[\"label\",\"siteCode\"],\"profiles\":{\"site-planner\":{\"maximumPageSize\":10,\"allowCount\":false,\"selectable\":[\"label\",\"siteCode\"],\"filterable\":{\"siteCode\":[\"equals\"]},\"sortable\":{\"label\":[\"asc\"]}}}},\"permit\":{\"operation\":\"records.permit.list\",\"requiresAccessProfile\":true,\"accessProfileParameter\":true,\"paginationParameters\":{\"size\":\"limit\",\"cursor\":\"cursor\"},\"recordProperties\":[\"label\",\"permitCode\"],\"profiles\":{\"permit-clerk\":{\"maximumPageSize\":10,\"allowCount\":false,\"selectable\":[\"label\",\"permitCode\"],\"filterable\":{\"permitCode\":[\"equals\"]},\"sortable\":{\"label\":[\"asc\"]}}}}}") interface ReadRows { "licence": Operations["records.licence.get"]["output"]["data"] @@ -88,27 +88,30 @@ export class Client { return this.#transport.call(route, options) } async records_licence_listPage(options: Operations["records.licence.list"]["input"] = {}, cursor?: string): Promise> { - const { data } = await this.call("records.licence.list", { ...options, query: cursor === undefined ? options.query : { accessProfile: options.query?.accessProfile, "$skiptoken": cursor } }) + const { data } = await this.call("records.licence.list", { ...options, query: cursor === undefined ? options.query : { accessProfile: options.query?.accessProfile, "cursor": cursor } }) return { items: data.items, nextCursor: data.pageInfo.nextCursor ?? null } } async records_site_listPage(options: Operations["records.site.list"]["input"] = {}, cursor?: string): Promise> { - const { data } = await this.call("records.site.list", { ...options, query: cursor === undefined ? options.query : { "$skiptoken": cursor } }) + const { data } = await this.call("records.site.list", { ...options, query: cursor === undefined ? options.query : { "cursor": cursor } }) return { items: data.items, nextCursor: data.pageInfo.nextCursor ?? null } } async records_permit_listPage(options: Operations["records.permit.list"]["input"] = {}, cursor?: string): Promise> { - const { data } = await this.call("records.permit.list", { ...options, query: cursor === undefined ? options.query : { accessProfile: options.query?.accessProfile, "$skiptoken": cursor } }) + const { data } = await this.call("records.permit.list", { ...options, query: cursor === undefined ? options.query : { accessProfile: options.query?.accessProfile, "cursor": cursor } }) return { items: data.items, nextCursor: data.pageInfo.nextCursor ?? null } } list(recordType: K, ...args: {} extends ListOptions[K] ? [options?: ListOptions[K]] : [options: ListOptions[K]]): Promise>> - async list(recordType: string, options: ListRequest & { after?: string } = {}): Promise>> { + async list(recordType: string, options: ListRequest & { after?: string; cursor?: string } = {}): Promise>> { const rules = Object.hasOwn(listRules, recordType) ? listRules[recordType] : undefined if (!rules) throw new TypeError("Unknown record type for list") - const { accessProfile, where, orderBy, select, count, top, after, ...call } = options - if (after !== undefined && [where, orderBy, select, count, top].some(value => value !== undefined)) { - throw new TypeError("Use after without where, orderBy, select, count or top.") + const { accessProfile, where, orderBy, select, count, top, limit, after, cursor, ...call } = options + const continuationName = rules.paginationParameters ? "cursor" : "after" + const continuation = rules.paginationParameters ? cursor : after + if ((rules.paginationParameters ? after : cursor) !== undefined) throw new TypeError("Use " + continuationName + " for continuation.") + if (continuation !== undefined && [where, orderBy, select, count, top, limit].some(value => value !== undefined)) { + throw new TypeError("Use " + continuationName + " without first-page query options.") } - if (after !== undefined && (typeof after !== "string" || !after)) throw new TypeError("Use a nonempty cursor for after.") - const query = listQuery(rules, options, after, this.#transport.profile) + if (continuation !== undefined && (typeof continuation !== "string" || !continuation)) throw new TypeError("Use a nonempty " + continuationName + ".") + const query = listQuery(rules, options, continuation, this.#transport.profile) const { data } = await this.#call<{ items: RecordEnvelope[]; pageInfo: { nextCursor?: string | null }; count?: number }>(rules.operation, { ...call, query }) const page = listPage(data) return { ...page, items: page.items.map(recordRow) } diff --git a/clients/typescript/tests/generate-project.test.ts b/clients/typescript/tests/generate-project.test.ts index 6491d2a3dc..27e30985d9 100644 --- a/clients/typescript/tests/generate-project.test.ts +++ b/clients/typescript/tests/generate-project.test.ts @@ -147,9 +147,6 @@ assert.equal(typeof client.documents.upload, 'function') assert.deepEqual(new Set(registerImports.map(line => line.split(' from ')[1])), new Set([JSON.stringify(name + '/core'), JSON.stringify(name + '/schema')])) assert.ok(service.includes('from ' + JSON.stringify(name + '/products/casework'))) - if (scenario === 'renamed writable registry') { - assert.match(register, /"records\.contact\.patch": \{ input: .*"value"\?: JsonValue/u) - } if (scenario === 'renamed writable registry' || scenario === 'two registers') { const tsc = join(root, 'node_modules/typescript/bin/tsc') const installed = join(dir, 'node_modules', name) @@ -161,13 +158,37 @@ assert.equal(typeof client.documents.upload, 'function') assert.equal(build.status, 0, build.stdout + build.stderr) const config = join(dir, 'tsconfig.json') writeFileSync(join(dir, 'package.json'), JSON.stringify({ type: 'module' })) + const files = ['app/service.ts'] + if (scenario === 'renamed writable registry') { + files.push('app/contact-patch.ts') + writeFileSync(join(dir, 'app', 'contact-patch.ts'), ` +import type { Operations } from './service.licences.js' + +type ContactPatch = Operations['records.contact.patch']['input']['body'] + +export const patch: ContactPatch = [ + { op: 'add', path: '/data/email', value: 'contact@example.org' }, + { op: 'replace', path: '/data/jurisdiction', value: { code: 'north' } }, + { op: 'test', path: '/data/name', value: null }, +] + +// @ts-expect-error Every Contact Patch operation requires a value. +export const missingValue: ContactPatch = [{ op: 'replace', path: '/data/name' }] +// @ts-expect-error Contact Patch accepts only declared data paths. +export const unknownPath: ContactPatch = [{ op: 'add', path: '/data/unknown', value: 'x' }] +// @ts-expect-error Contact Patch supports add, replace and test. +export const unsupportedOperation: ContactPatch = [{ op: 'remove', path: '/data/name', value: null }] +// @ts-expect-error Contact Patch values must be JSON. +export const nonJsonValue: ContactPatch = [{ op: 'test', path: '/data/name', value: () => 'x' }] +`) + } for (const moduleResolution of ['NodeNext', 'Bundler']) { writeFileSync(config, JSON.stringify({ compilerOptions: { target: 'ES2023', module: moduleResolution === 'NodeNext' ? 'NodeNext' : 'ESNext', moduleResolution, strict: true, types: [], }, - files: ['app/service.ts'], + files, })) const check = spawnSync(process.execPath, [tsc, '--noEmit', '-p', config], { encoding: 'utf8' }) assert.equal(check.status, 0, moduleResolution + '\n' + check.stdout + check.stderr) diff --git a/clients/typescript/tests/generator.test.ts b/clients/typescript/tests/generator.test.ts index fc8d51b2a0..30e91d333a 100644 --- a/clients/typescript/tests/generator.test.ts +++ b/clients/typescript/tests/generator.test.ts @@ -704,3 +704,178 @@ for (const status of ['200', '401', '403', 'default']) { assert.throws(() => generate(JSON.stringify(input)), /x-registry-empty-answer.*404.*410/u) }) } + +test('BReg permits open Patch values only on effective operation branches', async t => { + const operation = (op: string, value: boolean | undefined, path: string) => ({ + type: 'object', + additionalProperties: false, + required: ['op', 'path', ...(value === undefined ? [] : ['value'])], + properties: { + op: { const: op }, + path: { type: 'string', enum: [path] }, + ...(value === undefined ? {} : { value }), + }, + }) + const patch = { + type: 'array', + minItems: 1, + maxItems: 128, + items: { oneOf: [ + operation('add', true, '/data/editable'), + operation('replace', true, '/data/editable'), + operation('remove', undefined, '/data/editable'), + operation('test', true, '/data/readable'), + ] }, + } + const item = (name: string) => ({ + type: 'object', + required: ['operation', 'patch'], + properties: { operation: { const: name }, patch }, + }) + const request = (id: string, media: string, schema: object) => ({ + operationId: id, + requestBody: { required: true, content: { [media]: { schema } } }, + responses: { 200: { description: 'Accepted' } }, + }) + const direct = (schema: object) => ({ patch: request('patchRecord', 'application/json-patch+json', schema) }) + const group = (id: string, items: object[]) => ({ post: request(id, 'application/json', { + type: 'object', + required: ['items'], + properties: { items: { type: 'array', items: { oneOf: items } } }, + }) }) + const directPath = '/v1/records/enrolments/{record_id}' + const batchPath = '/v1/records/enrolments:batch' + const chunkPath = '/v1/records/enrolments/ingestion-runs/{run_id}/chunks' + const create = { + type: 'object', + required: ['operation', 'data'], + properties: { operation: { const: 'create' }, data: { type: 'string' } }, + } + const settings = { breg: true } + const source = { + ...document({ type: 'string' }), + paths: { + [directPath]: direct(patch), + [batchPath]: group('batchRecords', [create, item('patch')]), + [chunkPath]: group('submitChunk', [item('patch')]), + }, + } + const output = generate(JSON.stringify(source), settings) + assert.match(output, /"patchRecord": .*"value": JsonValue/u) + assert.match(output, /"batchRecords": .*"value": JsonValue/u) + assert.match(output, /"submitChunk": .*"value": JsonValue/u) + + const add = operation('add', true, '/data/editable') + for (const [name, branch] of [ + ['optional op', { ...add, required: ['path', 'value'] }], + ['optional path', { ...add, required: ['op', 'value'] }], + ['untyped path', { ...add, properties: { ...add.properties, path: { enum: ['/data/editable'] } } }], + ['missing path', { ...add, properties: { op: add.properties.op, value: true } }], + ] as const) { + await t.test('refuses open value with ' + name, () => { + const schema = { ...patch, items: { oneOf: [branch] } } + assert.throws(() => generate(JSON.stringify({ + ...source, paths: { [directPath]: direct(schema) }, + }), settings), /oneOf\/0\/properties\/value: unconstrained schema/u) + }) + } + for (const [path, id, items] of [ + [batchPath, 'batchRecords', [create]], + [chunkPath, 'submitChunk', []], + ] as const) { + await t.test('refuses open value with optional operation in ' + id, () => { + const optionalOperation = { ...item('patch'), required: ['patch'] } + assert.throws(() => generate(JSON.stringify({ + ...source, paths: { [path]: group(id, [...items, optionalOperation]) }, + }), settings), /properties\/patch\/items\/oneOf\/0\/properties\/value: unconstrained schema/u) + }) + } + + const remove = { ...patch, items: { oneOf: [operation('remove', true, '/data/editable')] } } + assert.throws(() => generate(JSON.stringify({ + ...source, paths: { [directPath]: direct(remove) }, + }), settings), /oneOf\/0\/properties\/value: unconstrained schema/u) + assert.throws(() => generate(JSON.stringify({ + ...source, paths: { [chunkPath]: group('submitChunk', [item('create')]) }, + }), settings), /oneOf\/0\/properties\/value: unconstrained schema/u) + assert.throws(() => generate(JSON.stringify({ + ...source, paths: { [batchPath]: group('batchRecords', [{ ...create, properties: { + ...create.properties, data: true, + } }]) }, + }), settings), /oneOf\/0\/properties\/data: unconstrained schema/u) +}) + +test('BReg canonical as-of continuations omit first-page query options', async (t) => { + const path = '/v1/records/enrolments:as-of' + const operationId = 'records.enrolments.asOf' + const source = { + ...document({ type: 'string' }), + paths: { [path]: { get: { + operationId, + 'x-registry-queryKind': 'as-of', + parameters: [ + { in: 'query', name: 'accessProfile', schema: { type: 'string' } }, + { in: 'query', name: 'asOf', required: false, schema: { type: 'string', format: 'date' } }, + { in: 'query', name: 'limit', schema: { type: 'integer', minimum: 1 } }, + { in: 'query', name: 'cursor', schema: { type: 'string' } }, + ], + responses: { + 200: { description: 'As-of page', content: { 'application/json': { schema: { + type: 'object', + required: ['items', 'pageInfo'], + properties: { + items: { type: 'array', items: { type: 'string' } }, + pageInfo: { type: 'object', properties: { nextCursor: { type: ['string', 'null'] } } }, + }, + } } } }, + }, + } } }, + } + const text = JSON.stringify(source) + const entry = fileURLToPath(new URL('../generated/breg-minimal.ts', import.meta.url)) + const output = generate(text, { breg: true, coreImport: '../core.ts', schemaImport: '../schema.ts' }) + ` +declare const client: Client +client.call('records.enrolments.asOf', { query: { asOf: '2026-01-01', limit: 3 } }) +client.call('records.enrolments.asOf', { query: { cursor: 'next', accessProfile: 'operator' } }) +// @ts-expect-error a first page needs asOf +client.call('records.enrolments.asOf', { query: { limit: 3 } }) +// @ts-expect-error an exclusive cursor carries asOf +client.call('records.enrolments.asOf', { query: { asOf: '2026-01-01', cursor: 'next' } }) +// @ts-expect-error an exclusive cursor carries the original page size +client.call('records.enrolments.asOf', { query: { cursor: 'next', limit: 3 } }) +` + const options: ts.CompilerOptions = { + strict: true, noEmit: true, skipLibCheck: true, types: [], + target: ts.ScriptTarget.ES2023, module: ts.ModuleKind.NodeNext, allowImportingTsExtensions: true, + } + const host = ts.createCompilerHost(options) + const readFile = host.readFile + host.readFile = name => name === entry ? output : readFile(name) + assert.equal(ts.formatDiagnostics(ts.getPreEmitDiagnostics(ts.createProgram([entry], options, host)), host), '') + + const dir = realpathSync(mkdtempSync(join(tmpdir(), 'registry-as-of-'))) + t.after(() => rmSync(dir, { recursive: true, force: true })) + const root = dirname(fileURLToPath(new URL('../generate.ts', import.meta.url))) + const file = join(dir, 'client.ts') + writeFileSync(file, generate(text, { + breg: true, coreImport: join(root, 'core.ts'), schemaImport: join(root, 'schema.ts'), + })) + const { Client } = await import(file) + const { Transport, allPages } = await import('../core.ts') + const seen: URL[] = [] + const client = new Client(new Transport({ + baseUrl: 'https://registry.example', token: () => 'fixture', + fetch: async url => { + seen.push(new URL(String(url))) + return seen.length === 1 + ? Response.json({ items: ['first'], pageInfo: { nextCursor: 'opaque+/=' } }) + : Response.json({ items: ['second'], pageInfo: { nextCursor: null } }) + }, + })) + const query = { accessProfile: 'operator', asOf: '2026-01-01', limit: 3 } + assert.deepEqual(await allPages(cursor => client.records_enrolments_asOfPage({ query }, cursor)), ['first', 'second']) + assert.deepEqual(seen.map(url => [url.pathname, Object.fromEntries(url.searchParams)]), [ + [path, { ...query, limit: '3' }], + [path, { accessProfile: 'operator', cursor: 'opaque+/=' }], + ]) +}) diff --git a/clients/typescript/tests/list.test.ts b/clients/typescript/tests/list.test.ts index 96e8952686..9fdb6a2c8a 100644 --- a/clients/typescript/tests/list.test.ts +++ b/clients/typescript/tests/list.test.ts @@ -1,10 +1,7 @@ import test from 'node:test' import { make } from './helpers.ts' import assert from 'node:assert/strict' -import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { fileURLToPath } from 'node:url' +import { readFileSync } from 'node:fs' import { generate } from '../generate.ts' import { Client } from './fixtures/breg-list.ts' import { Client as FacilityClient } from '../generated/breg-facility.ts' @@ -27,7 +24,7 @@ test('the generator types list options from each query profile', () => { assert.match(output, /^export interface ListOptions \{$/mu) assert.match(output, /accessProfile\?: "licence-holder"; where: \(\{ "holderId": FieldValue \} \| \{ "licenceNumber": FieldValue<[^>]+>; "status": FieldValue<[^>]+> \}\) & \{/u) assert.match(output, /accessProfile\?: "licence-officer"; where\?: \{ "expiresOn"\?: Filter, "range">/u) - assert.match(output, /orderBy\?: "expiresOn" \| "holderName" \| "holderName desc"; select\?: ReadonlyArray<"expiresOn" \| "fee" \| "holderName" \| "licenceNumber" \| "region" \| "status">; count\?: boolean; top\?: number/u) + assert.match(output, /orderBy\?: "expiresOn" \| "holderName" \| "holderName desc"; select\?: ReadonlyArray<"expiresOn" \| "fee" \| "holderName" \| "licenceNumber" \| "region" \| "status">; count\?: boolean; limit\?: number/u) assert.match(output, /"site": \(CallOptions & \{ accessProfile\?: never; where\?: \{ "siteCode"\?: /u) }) @@ -82,7 +79,7 @@ for (const [name, change, pointer] of [ }) } -test('list builds the query from where, orderBy, select, top and count', async () => { +test('list builds the query from where, orderBy, select, limit and count', async () => { const { urls, client } = recording() const page = await client.list('licence', { accessProfile: 'licence-officer', @@ -90,7 +87,7 @@ test('list builds the query from where, orderBy, select, top and count', async ( status: ['active', 'suspended'], region: 'north', holderName: { startsWith: "O'Br" }, expiresOn: { lt: '2028-01-01', ge: '2027-01-01' }, suspendedOn: { isNull: true }, fee: 25.5, }, - orderBy: 'holderName desc', select: ['licenceNumber', 'status'], top: 25, count: true, + orderBy: 'holderName desc', select: ['licenceNumber', 'status'], limit: 25, count: true, }) assert.deepEqual(page, { items: [{ id: licence.recordId, revision: licence.revisionId, data: licence.domainData }], nextCursor: 'next-1', count: 7 }) assert.equal(urls[0]!.pathname, '/v1/records/licences') @@ -98,7 +95,7 @@ test('list builds the query from where, orderBy, select, top and count', async ( accessProfile: 'licence-officer', $filter: "status in ('active','suspended') and region eq 'north' and startswith(holderName,'O''Br')" + " and expiresOn ge '2027-01-01' and expiresOn lt '2028-01-01' and suspendedOn eq null and fee eq 25.5", - $orderby: 'holderName desc', $select: 'licenceNumber,status', $top: '25', $count: 'true', + $orderby: 'holderName desc', $select: 'licenceNumber,status', limit: '25', $count: 'true', }) }) @@ -110,57 +107,42 @@ test('a call profile beats the default on a list, and a list without a profile p assert.deepEqual(urls.map(url => url.searchParams.get('accessProfile')), ['licence-holder', 'licence-officer', null]) }) -test('a continuation sends only the access profile and the cursor', async () => { - const { urls, client } = recording(() => Response.json({ items: [], pageInfo: { nextCursor: null } })) - const options = { accessProfile: 'licence-officer', after: 'next-1' } as const - assert.deepEqual(await client.list('licence', options), { items: [], nextCursor: null }) - assert.deepEqual(query(urls[0]!), { accessProfile: 'licence-officer', $skiptoken: 'next-1' }) -}) - -test('a generated BReg client uses declared limit and cursor keys', async t => { - const doc = fixture() - doc.components.parameters.top.name = 'limit' - doc.components.parameters.skiptoken.name = 'cursor' - const directory = mkdtempSync(join(tmpdir(), 'registry-list-pagination-')) - t.after(() => rmSync(directory, { recursive: true, force: true })) - const file = join(directory, 'client.ts') - writeFileSync(file, generate(JSON.stringify(doc), { - breg: true, - coreImport: fileURLToPath(new URL('../core.ts', import.meta.url)), - schemaImport: fileURLToPath(new URL('../schema.ts', import.meta.url)), +test('list and generated page methods preserve the returned cursor and send only it and the profile', async () => { + const opaque = 'opaque+/=' + const { urls, client } = recording(() => Response.json({ + items: [], + pageInfo: { nextCursor: opaque }, })) - const { Client } = await import(file) as typeof import('./fixtures/breg-list.ts') - const urls: URL[] = [] - const fetch: typeof globalThis.fetch = async url => { - urls.push(new URL(String(url))) - return Response.json({ items: [], pageInfo: { nextCursor: null } }) - } - const client = make(Client, { baseUrl, token: () => 'fixture', fetch }) - await Reflect.apply(client.list, client, ['licence', { accessProfile: 'licence-officer', where: { status: 'active' }, limit: 3 }]) - await Reflect.apply(client.list, client, ['licence', { accessProfile: 'licence-officer', cursor: 'opaque+/=' }]) - await assert.rejects(Reflect.apply(client.list, client, ['licence', { - accessProfile: 'licence-officer', cursor: 'opaque+/=', limit: 3, - }]), /Use cursor without first-page query options/u) - // The generated call signature follows the synthetic OpenAPI's query names. + const first = await client.list('licence', { + accessProfile: 'licence-officer', where: { status: 'active' }, limit: 3, + }) + assert.equal(first.nextCursor, opaque) + await client.list('licence', { accessProfile: 'licence-officer', cursor: first.nextCursor! }) + const options = { query: { accessProfile: 'licence-officer', limit: 3, $filter: "status eq 'active'" } } as const - await client.records_licence_listPage(options) - await client.records_licence_listPage(options, 'opaque+/=') + const page = await client.records_licence_listPage(options) + assert.equal(page.nextCursor, opaque) + await client.records_licence_listPage(options, page.nextCursor!) assert.deepEqual(urls.map(query), [ { accessProfile: 'licence-officer', $filter: "status eq 'active'", limit: '3' }, - { accessProfile: 'licence-officer', cursor: 'opaque+/=' }, + { accessProfile: 'licence-officer', cursor: opaque }, { accessProfile: 'licence-officer', limit: '3', $filter: "status eq 'active'" }, - { accessProfile: 'licence-officer', cursor: 'opaque+/=' }, + { accessProfile: 'licence-officer', cursor: opaque }, ]) + for (const index of [1, 3]) { + assert.equal(urls[index]!.searchParams.size, 2) + assert.match(urls[index]!.search, /cursor=opaque%2B%2F%3D/u) + } }) test('a single-profile route sends no access profile', async () => { const { urls, client } = recording(() => Response.json({ items: [], pageInfo: { nextCursor: null } })) await client.list('site', { where: { siteCode: 'S-1' }, orderBy: 'label' }) await client.list('site') - await client.list('site', { after: 'next-2' }) - await client.records_site_listPage({ query: { $top: 3 } }, 'next-3') - assert.deepEqual(urls.map(query), [{ $filter: "siteCode eq 'S-1'", $orderby: 'label' }, {}, { $skiptoken: 'next-2' }, - { $skiptoken: 'next-3' }]) + await client.list('site', { cursor: 'next-2' }) + await client.records_site_listPage({ query: { limit: 3 } }, 'next-3') + assert.deepEqual(urls.map(query), [{ $filter: "siteCode eq 'S-1'", $orderby: 'label' }, {}, { cursor: 'next-2' }, + { cursor: 'next-3' }]) }) test('a profile with required filters lists only with one of its alternatives', async () => { @@ -198,9 +180,9 @@ test('list explains a refusal from the profile and never repeats a value', async [{ ...officer, select: [] }, '`select` needs at least one property'], [{ ...officer, select: ['fee', 'fee'] }, '`select` names a property twice'], [{ ...officer, select: ['suspendedOn'] }, '`suspendedOn` cannot be selected under profile `licence-officer`'], - [{ ...officer, top: 0 }, '`top` must be a whole number from 1 to 50 under profile `licence-officer`'], - [{ ...officer, top: 51 }, '`top` must be a whole number from 1 to 50 under profile `licence-officer`'], - [{ ...officer, top: 1.5 }, '`top` must be a whole number from 1 to 50 under profile `licence-officer`'], + [{ ...officer, limit: 0 }, '`limit` must be a whole number from 1 to 50 under profile `licence-officer`'], + [{ ...officer, limit: 51 }, '`limit` must be a whole number from 1 to 50 under profile `licence-officer`'], + [{ ...officer, limit: 1.5 }, '`limit` must be a whole number from 1 to 50 under profile `licence-officer`'], [{ accessProfile: 'licence-holder', where: { holderId, region: 'private' } }, '`region` cannot be filtered under profile `licence-holder`'], [{ accessProfile: 'licence-holder', where: { holderId }, count: true }, 'Profile `licence-holder` does not allow count'], [{ ...officer, count: 'yes' }, '`count` must be true or false'], @@ -265,12 +247,20 @@ function typeChecks(client: Client, facility: FacilityClient) { client.list('missing') client.list('licence', { accessProfile: 'licence-officer', where: { expiresOn: { ge: '2027-01-01' }, suspendedOn: { isNull: false }, holderName: { contains: 'Br' }, fee: 3, - }, orderBy: 'holderName desc', count: true, top: 10 }).then(page => page.count) + }, orderBy: 'holderName desc', count: true, limit: 10 }).then(page => page.count) client.list('site').then(page => { const code: string | undefined = page.items[0]?.data.siteCode // @ts-expect-error rows are typed. return page.items[0]?.data.missing ?? code }) + // @ts-expect-error page size is exposed as limit. + client.list('licence', { accessProfile: 'licence-officer', top: 3 }) + // @ts-expect-error continuation is exposed as cursor. + client.list('licence', { accessProfile: 'licence-officer', after: 'opaque' }) + // @ts-expect-error the raw BReg query exposes limit. + client.records_licence_listPage({ query: { accessProfile: 'licence-officer', $top: 3 } }) + // @ts-expect-error the raw BReg query exposes cursor. + client.call('records.licence.list', { query: { accessProfile: 'licence-officer', $skiptoken: 'opaque' } }) // @ts-expect-error facility-assignment filters facility by equality, in and null checks only. facility.list('facility-assignment', { accessProfile: 'facility-reader', where: { facility: { startsWith: 'a' } } }) } @@ -278,14 +268,14 @@ void typeChecks test('continuation skips required filters and refuses new query options before dispatch', async () => { const { urls, client } = recording() - await client.list('licence', { accessProfile: 'licence-holder', after: 'cursor' }) - for (const extra of [{ where: { holderId } }, { orderBy: 'expiresOn' }, { select: ['status'] }, { count: false }, { top: 5 }]) { - await assert.rejects(client.list('licence', { accessProfile: 'licence-holder', after: 'private', ...extra } as never), - { name: 'TypeError', message: 'Use after without where, orderBy, select, count or top.' }) + await client.list('licence', { accessProfile: 'licence-holder', cursor: 'cursor' }) + for (const extra of [{ where: { holderId } }, { orderBy: 'expiresOn' }, { select: ['status'] }, { count: false }, { limit: 5 }]) { + await assert.rejects(client.list('licence', { accessProfile: 'licence-holder', cursor: 'private', ...extra } as never), + { name: 'TypeError', message: 'Use cursor without first-page query options.' }) } - await assert.rejects(client.list('licence', { accessProfile: 'licence-holder', after: '' }), - { name: 'TypeError', message: 'Use a nonempty cursor for after.' }) - assert.deepEqual(urls.map(query), [{ accessProfile: 'licence-holder', $skiptoken: 'cursor' }]) + await assert.rejects(client.list('licence', { accessProfile: 'licence-holder', cursor: '' }), + { name: 'TypeError', message: 'Use a nonempty cursor.' }) + assert.deepEqual(urls.map(query), [{ accessProfile: 'licence-holder', cursor: 'cursor' }]) }) test('a list that requires its profile refuses without one, even when it publishes only one', async () => { @@ -300,7 +290,7 @@ test('a client default the record type does not publish is refused with a messag const unpublished = { name: 'TypeError', message: "The client's default access profile is not one this record type publishes, so name one on the call." } const { client, urls } = recording(undefined, 'licence-officer') await assert.rejects(client.list('permit', {} as never), unpublished) - await assert.rejects(client.list('permit', { after: 'cursor' } as never), unpublished) + await assert.rejects(client.list('permit', { cursor: 'cursor' } as never), unpublished) assert.equal(urls.length, 0) const facility = make(FacilityClient, { baseUrl, token: () => 'fixture', profile: 'facility-reader', fetch: async () => { throw new Error('nothing is sent') } }) await assert.rejects(facility.list('directory-entry'), unpublished) @@ -331,9 +321,14 @@ test('list and read return the same facility row and preserve the sub-collection assert.deepEqual((await client.call('records.facility.path.operators', { path: { record_id: holderId }, query: { accessProfile: 'facility-reader' }, })).data.items, []) - assert.deepEqual((await client.records_facility_path_operatorsPage({ - path: { record_id: holderId }, query: { accessProfile: 'facility-reader' }, - })).items, []) + const options = { path: { record_id: holderId }, query: { accessProfile: 'facility-reader', limit: 3 } } as const + assert.deepEqual((await client.records_facility_path_operatorsPage(options)).items, []) + assert.deepEqual((await client.records_facility_path_operatorsPage(options, 'opaque+/=')).items, []) + assert.deepEqual(urls.slice(2).map(query), [ + { accessProfile: 'facility-reader' }, + { accessProfile: 'facility-reader', limit: '3' }, + { accessProfile: 'facility-reader', cursor: 'opaque+/=' }, + ]) }) test('read refuses a private profile locally and preserves a 404 refusal', async () => { @@ -360,9 +355,9 @@ function readTypeChecks(client: FacilityClient, licence: Client) { // @ts-expect-error sub-collections use call or their generated page method void client.list('records.facility.path.operators') // @ts-expect-error a continuation carries the original filters - void licence.list('licence', { accessProfile: 'licence-officer', after: 'cursor', count: false }) - // @ts-expect-error a continuation keeps the first page's size, so it takes no top - void licence.list('licence', { accessProfile: 'licence-officer', after: 'cursor', top: 50 }) + void licence.list('licence', { accessProfile: 'licence-officer', cursor: 'cursor', count: false }) + // @ts-expect-error a continuation keeps the first page's size, so it takes no limit + void licence.list('licence', { accessProfile: 'licence-officer', cursor: 'cursor', limit: 50 }) void client.read('facility', holderId, { accessProfile: 'proposal-reviewer' }).then(row => { const name: string | undefined = row.data.name // @ts-expect-error the facility row only exposes declared domain fields @@ -372,15 +367,15 @@ function readTypeChecks(client: FacilityClient, licence: Client) { void readTypeChecks -test('list checks filters against the default profile and reuses it for after', async () => { +test('list checks filters against the default profile and reuses it for continuation', async () => { const { client, urls } = recording(undefined, 'licence-officer') const page = await client.list('licence', { where: { region: 'north' } }) await assert.rejects(client.list('licence', { where: { licenceNumber: 'L-1' } } as never), { name: 'TypeError', message: '`licenceNumber` cannot be filtered under profile `licence-officer`' }) - await client.list('licence', { after: page.nextCursor! }) + await client.list('licence', { cursor: page.nextCursor! }) assert.deepEqual(urls.map(query), [ { accessProfile: 'licence-officer', $filter: "region eq 'north'" }, - { accessProfile: 'licence-officer', $skiptoken: 'next-1' }, + { accessProfile: 'licence-officer', cursor: 'next-1' }, ]) }) diff --git a/crates/registry-adapter-connectors/tests/breg_action_proposal.rs b/crates/registry-adapter-connectors/tests/breg_action_proposal.rs index a77fefd461..1c0b2b4a96 100644 --- a/crates/registry-adapter-connectors/tests/breg_action_proposal.rs +++ b/crates/registry-adapter-connectors/tests/breg_action_proposal.rs @@ -20,6 +20,13 @@ use support::{ action_receipt, problem, proposal, Mock, APPLICATION_ID, PROPOSAL_ID, RECORD_ID, TOKEN, }; +// Current GET replies report whose turn it is. Older receipts can omit it. +fn current_proposal(state: &str, revision: u64, turn: &str) -> support::MockResponse { + let mut value = proposal(state, revision); + value["turn"] = json!(turn); + support::mutation_json(StatusCode::OK, value) +} + fn key(step: &str) -> CommandKey { CommandKey::new(format!("adapter-unit/company/{step}")).expect("derived key") } @@ -325,7 +332,7 @@ async fn item_scoped_refusals_stay_refused_outcomes() { async fn proposal_submit_completes_at_the_submitted_receipt() { let mock = Mock::start("proposal", false).await; // The send's fresh authorized read, then the transition. - mock.push(support::mutation_json(StatusCode::OK, proposal("draft", 2))); + mock.push(current_proposal("draft", 2, "party")); mock.push(support::mutation_json( StatusCode::OK, proposal("submitted", 3), @@ -359,7 +366,7 @@ async fn proposal_submit_completes_at_the_submitted_receipt() { async fn proposal_submit_horizon_refusals_surface_and_recover_by_reading() { // Send answers 409 key-reused: refused, never a fallback. let mock = Mock::start("proposal", false).await; - mock.push(support::mutation_json(StatusCode::OK, proposal("draft", 2))); + mock.push(current_proposal("draft", 2, "party")); mock.push(problem(BRegProblemCode::IdempotencyConflict)); let stored = { let prepared = mock @@ -388,7 +395,7 @@ async fn proposal_submit_horizon_refusals_surface_and_recover_by_reading() { // Send answers 410 expired: refused, and recovery reads the resource // and returns the observed outcome without sending again. let mock = Mock::start("proposal", false).await; - mock.push(support::mutation_json(StatusCode::OK, proposal("draft", 2))); + mock.push(current_proposal("draft", 2, "party")); mock.push(problem(BRegProblemCode::IdempotencyExpired)); let refused = { let prepared = mock @@ -408,10 +415,7 @@ async fn proposal_submit_horizon_refusals_surface_and_recover_by_reading() { Some("idempotency.expired") ); // The read shows the transition already holds: observed completion. - mock.push(support::mutation_json( - StatusCode::OK, - proposal("submitted", 3), - )); + mock.push(current_proposal("submitted", 3, "official")); let recovered = { let prepared = mock .connector @@ -438,7 +442,7 @@ async fn proposal_submit_horizon_refusals_surface_and_recover_by_reading() { async fn proposal_submit_unknown_outcome_recovers_to_the_observed_or_replayed_result() { let mock = Mock::start("proposal", false).await; // First send: the fresh read answers, then the transition hangs. - mock.push(support::mutation_json(StatusCode::OK, proposal("draft", 2))); + mock.push(current_proposal("draft", 2, "party")); mock.push(support::mutation_json(StatusCode::OK, json!({})).hanging()); let stored = { let prepared = mock @@ -461,7 +465,7 @@ async fn proposal_submit_unknown_outcome_recovers_to_the_observed_or_replayed_re assert_eq!(uncertain.category, OutcomeCategory::Uncertain); // Recovery: the fresh read proves the draft still holds, so the exact // prepared transition is re-armed and executed under the same key. - mock.push(support::mutation_json(StatusCode::OK, proposal("draft", 2))); + mock.push(current_proposal("draft", 2, "party")); mock.push(support::mutation_json( StatusCode::OK, proposal("submitted", 3), @@ -496,10 +500,7 @@ async fn proposal_submit_refuses_when_the_draft_left_the_transition_behind() { let mock = Mock::start("proposal", false).await; // The read shows the draft was cancelled: the transition can never // run, and no mode falls back. - mock.push(support::mutation_json( - StatusCode::OK, - proposal("cancelled", 3), - )); + mock.push(current_proposal("cancelled", 3, "nobody")); let outcome = { let prepared = mock .connector @@ -520,14 +521,8 @@ async fn proposal_submit_refuses_when_the_draft_left_the_transition_behind() { #[tokio::test(flavor = "multi_thread")] async fn proposal_status_read_and_observation_agree() { let mock = Mock::start("proposal", false).await; - mock.push(support::mutation_json( - StatusCode::OK, - proposal("submitted", 3), - )); - mock.push(support::mutation_json( - StatusCode::OK, - proposal("submitted", 3), - )); + mock.push(current_proposal("submitted", 3, "official")); + mock.push(current_proposal("submitted", 3, "official")); let summary = mock .connector .reads() @@ -680,7 +675,7 @@ async fn proposal_submit_recovery_past_the_receipt_horizon_is_uncertain() { // exchange answers that the key's receipt expired: whether the first // attempt committed is not proven either way. let mock = Mock::start("proposal", false).await; - mock.push(support::mutation_json(StatusCode::OK, proposal("draft", 2))); + mock.push(current_proposal("draft", 2, "party")); mock.push(problem(BRegProblemCode::IdempotencyExpired)); let prepared = mock .connector diff --git a/crates/registry-breg-client-node/__test__/action-refusals.test.js b/crates/registry-breg-client-node/__test__/action-refusals.test.js index 0f40eb7460..ea9996a92e 100644 --- a/crates/registry-breg-client-node/__test__/action-refusals.test.js +++ b/crates/registry-breg-client-node/__test__/action-refusals.test.js @@ -137,7 +137,10 @@ test('the typed idempotency key reuse problem uses the current wire code', async code: 'idempotency.conflict', traceId: TRACE_ID, }); assert.equal(retired.kind, 'problem'); - assert.equal(retired.code, undefined); + assert.equal(retired.code, 'idempotency.conflict'); + assert.equal(retired.problemType, 'https://id.registrystack.org/problems/registry-breg/idempotency/conflict'); + assert.equal(retired.status, 409); + assert.equal(retired.outcomeUnknown, false); }); test('row-local constraints expose bounded identifiers without default rendering', async () => { diff --git a/crates/registry-breg-client-node/__test__/additions.test.js b/crates/registry-breg-client-node/__test__/additions.test.js index 7803220f31..07f9c8daed 100644 --- a/crates/registry-breg-client-node/__test__/additions.test.js +++ b/crates/registry-breg-client-node/__test__/additions.test.js @@ -13,7 +13,7 @@ test('additions preserve the submitted version and use exact binary exchanges', const metadata = { id: 'additions', version: '1', revision, metadataVersion: '2', recordTypes: [], operations: [], actions: [], proposals: {actions: [{actionId: 'correct', accessProfile: 'writer', operations: ['get'], readableInputs: [], readableContextFields: []}], get: {method: 'GET', path: '/v1/proposals/{proposal_id}', accessProfiles: ['writer']}} }; - const document = {id, actionId: 'correct', actionRevision: revision, submissionVersion: 1, revision: 2, state: 'submitted', effectDigest: revision, links: {}, + const document = {id, actionId: 'correct', actionRevision: revision, submissionVersion: 1, revision: 2, state: 'submitted', turn: 'official', effectDigest: revision, links: {}, additions: {other: {id: 'other', maximumBytes: 64, maximumCount: 2, contentTypes: ['text/plain'], classification: 'restricted', items: [], links: {add: {method: 'POST', path: `/v1/proposals/${id}/additions/other`, accessProfile: 'writer', operation: 'add', ifMatch: '"condition"'}}}}}; const formId = 'details'; @@ -34,7 +34,7 @@ test('additions preserve the submitted version and use exact binary exchanges', } if (request.url.includes(threadPath)) { response.setHeader('content-type', 'application/json'); response.setHeader('vary', 'authorization, accept'); - if (request.method === 'GET') return response.end(JSON.stringify({items: document.messages.items})); + if (request.method === 'GET') return response.end(JSON.stringify({items: document.messages.items, links: {}})); if (!request.url.includes(threadPath + '/read')) { const {text} = JSON.parse(requests.at(-1).body.toString()); document.revision++; @@ -107,7 +107,9 @@ test('additions preserve the submitted version and use exact binary exchanges', const delivered = await client.sendProposalMessage(current, 'literal', 'send-one'); assert.equal(JSON.parse(delivered.documentJson).messages.items[0].text, 'literal'); assert.equal(requests.at(-1).headers['idempotency-key'], 'send-one'); - const page = await client.listProposalMessages(delivered, null, 2); + const page = await client.listProposalMessages(delivered, '7', 2); + assert.deepEqual(Object.fromEntries(new URL(requests.at(-1).url, 'http://localhost').searchParams), + {accessProfile: 'writer', limit: '2', cursor: '7'}); assert.equal(page.value.items[0].id, messageId); await client.markProposalMessagesRead(delivered, messageId); assert.deepEqual(JSON.parse(requests.at(-1).body.toString()), {through: messageId}); diff --git a/crates/registry-breg-client-node/__test__/asks.test.js b/crates/registry-breg-client-node/__test__/asks.test.js index 934976e112..16ece18c04 100644 --- a/crates/registry-breg-client-node/__test__/asks.test.js +++ b/crates/registry-breg-client-node/__test__/asks.test.js @@ -11,7 +11,7 @@ test('answers use the promoted ask link, exact body, ETag and caller key', async const metadata = {id: 'asks', version: '1', revision: digest, metadataVersion: '2', recordTypes: [], operations: [], actions: [], proposals: {actions: [{actionId: 'correct', accessProfile: 'author', operations: ['get', 'answer'], readableInputs: [], readableContextFields: []}], get: {method: 'GET', path: '/v1/proposals/{proposal_id}', accessProfiles: ['author']}}}; - const document = {id, actionId: 'correct', actionRevision: digest, submissionVersion: 1, revision: 2, state: 'submitted', effectDigest: digest, links: {}, + const document = {id, actionId: 'correct', actionRevision: digest, submissionVersion: 1, revision: 2, state: 'submitted', turn: 'official', effectDigest: digest, links: {}, asks: [{id: ask, text: 'Why?', wants: [{kind: 'answer'}], askedAt: '2026-11-27T00:00:00Z', state: 'open', links: { answer: {method: 'POST', path: `/v1/proposals/${id}/asks/${ask}/answer`, accessProfile: 'author', operation: 'answer', ifMatch: '"condition"', availability: {available: true, observedRevision: 2}}}}]}; const requests = []; diff --git a/crates/registry-breg-client-node/__test__/attachments.test.js b/crates/registry-breg-client-node/__test__/attachments.test.js index bd50b99d22..370f33ab42 100644 --- a/crates/registry-breg-client-node/__test__/attachments.test.js +++ b/crates/registry-breg-client-node/__test__/attachments.test.js @@ -23,6 +23,7 @@ async function harness(mutateReceipt) { else delete value.attachments[slot].value; if(mutateReceipt)mutateReceipt(value,request.method); } + if(request.method==='POST'&&request.url.startsWith('/v1/actions/'))response.statusCode=201; response.setHeader('content-type','application/json');response.setHeader('vary','authorization, accept');response.end(JSON.stringify(value)); }); await new Promise(resolve=>server.listen(0,'127.0.0.1',resolve)); diff --git a/crates/registry-breg-client-node/__test__/binding.test.js b/crates/registry-breg-client-node/__test__/binding.test.js index e92a6ae571..1ceee0cfc0 100644 --- a/crates/registry-breg-client-node/__test__/binding.test.js +++ b/crates/registry-breg-client-node/__test__/binding.test.js @@ -303,7 +303,8 @@ test('unknown problem codes fall back to HTTP status semantics', async () => { assert.equal(error.kind, 'problem'); assert.equal(error.status, status); assert.equal(error.traceId, TRACE_ID); - assert.equal(error.code, undefined); + assert.equal(error.code, 'future.refused'); + assert.equal(error.problemType, 'https://id.registrystack.org/problems/registry-breg/future/refused'); assert.equal('planRefusal' in error, false); assert.equal(error.refusalCode, undefined); assert.equal(error.reasonCode, undefined); 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..9580c5c720 100644 --- a/crates/registry-breg-client-node/__test__/exact-json.test.js +++ b/crates/registry-breg-client-node/__test__/exact-json.test.js @@ -107,7 +107,7 @@ test('native JSON methods preserve values, metadata, cursors and mutation precon if (path.endsWith(':batch')) { const revision = request.headers['idempotency-key'] === 'exact-batch' ? '9007199254740992' : '2'; const operation = JSON.parse(body).items[0].operation; - return response.end(`{"snapshot":"breg1_${applicationId}","results":[{"operation":"${operation}","recordId":"${id}","revisionIdentifier":"${revision}","etag":"\\"breg-record-000000000002\\"","domainData":{"wide":9007199254740992}}]}`); + return response.end(`{"snapshot":"breg1_${applicationId}","results":[{"operation":"${operation}","recordId":"${id}","revisionIdentifier":"${revision}","etag":"\\"breg-record-000000000002\\"","domainData":{"wide":9007199254740992},"futureItem":null}],"futureBatch":true}`); } response.setHeader('link','; rel="profile", ; rel="describedby"'); response.setHeader('etag','"breg-record-000000000001"'); @@ -205,13 +205,17 @@ 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.ok(!Object.hasOwn(batchResult.value, 'futureBatch')); + assert.ok(!Object.hasOwn(batchResult.value.results[0], 'futureItem')); 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 +225,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); @@ -266,7 +271,7 @@ test('native Proposal objects refuse unsafe values and preserve protected edit r const requests = []; const revision = `sha256:${'a'.repeat(64)}`; const proposal = { - id, actionId: 'correct', actionRevision: revision, submissionVersion: 1, revision: 2, state: 'draft', + id, actionId: 'correct', actionRevision: revision, submissionVersion: 1, revision: 2, state: 'draft', turn: 'party', input: {wide: 9007199254740992, decimal: '12.3400', nullable: null}, links: { self: {method: 'GET', path: `/v1/proposals/${id}`, accessProfile: profile, operation: 'get'}, diff --git a/crates/registry-breg-client-node/__test__/facade.test-d.ts b/crates/registry-breg-client-node/__test__/facade.test-d.ts index 863ba4de1c..052ffd53eb 100644 --- a/crates/registry-breg-client-node/__test__/facade.test-d.ts +++ b/crates/registry-breg-client-node/__test__/facade.test-d.ts @@ -328,6 +328,44 @@ function mayHaveTakenEffect(error: BaseRegistryClientError): boolean { } void mayHaveTakenEffect +client.markProposalMessagesRead(proposal, proposal.identifier).then(value => { + const marked: BRegProposal | null = value + marked?.identifier.toUpperCase() +}) +const messageBinding = metadata.selectProposalReviewContext('reviewer', 'correct') +client.readProposalReviewById(messageBinding, proposal.identifier).then(async ({value}) => { + const sent = (await client.sendProposalMessageFromReview(messageBinding, value, 'Reply', 'reply-key')).value + const marked = (await client.markProposalMessagesReadFromReview(messageBinding, value, proposal.identifier)).value + sent satisfies import('..').BRegProposalDocument | import('..').BRegProposalReviewDocument | import('..').BRegProposalMessages + marked satisfies typeof sent | null + // @ts-expect-error A Mark Read reply can be bodyless. + marked satisfies typeof sent + if ('subject' in sent && sent.policy) { + const policy = sent.policy + policy.id.toUpperCase() + // @ts-expect-error A frozen selection may carry the policy ID alone. + policy.version.toUpperCase() + if (policy.version !== undefined) { + policy.version.toUpperCase() + policy.digest.toUpperCase() + } else { + policy.digest satisfies undefined + } + } +}) + +type ReviewPolicy = NonNullable +const idOnlyPolicy: ReviewPolicy = {id: 'case-review'} +const pinnedPolicy: ReviewPolicy = {id: 'case-review', version: '2', digest: 'sha256:example'} +void idOnlyPolicy +void pinnedPolicy +// @ts-expect-error A version requires a digest. +const missingPolicyDigest: ReviewPolicy = {id: 'case-review', version: '2'} +// @ts-expect-error A digest requires a version. +const missingPolicyVersion: ReviewPolicy = {id: 'case-review', digest: 'sha256:example'} +void missingPolicyDigest +void missingPolicyVersion + client.readProposalReviewStatus(proposal).then(outcome => { const acceptedRequestId: string | undefined = outcome.value.requestId acceptedRequestId?.toUpperCase() diff --git a/crates/registry-breg-client-node/__test__/ingestion.test.js b/crates/registry-breg-client-node/__test__/ingestion.test.js index f2f66c22c5..e9660bcbd8 100644 --- a/crates/registry-breg-client-node/__test__/ingestion.test.js +++ b/crates/registry-breg-client-node/__test__/ingestion.test.js @@ -3,6 +3,8 @@ const assert = require('node:assert/strict'); const crypto = require('node:crypto'); const http = require('node:http'); +const { readFileSync } = require('node:fs'); +const { join } = require('node:path'); const { after, before, test } = require('node:test'); const { @@ -63,6 +65,13 @@ function receiptWire() { }; } +const receiptBytes = readFileSync(join(__dirname, '../../registry-breg-client/tests/fixtures/ordinary-ingestion-receipt.json')); +const malformedReceipts = { + duplicate: receiptBytes.toString().replace('"marker": 1', '"marker": 1, "marker": 2'), + missing: receiptBytes.toString().replace('"erased": false,', ''), + mistyped: receiptBytes.toString().replace('"replayed": true', '"replayed": "true"'), +}; + let server; let baseUrl; const seen = []; @@ -75,21 +84,25 @@ 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) => { + const answerBytes = (status, bytes) => { response.setHeader('traceparent', TRACEPARENT); response.setHeader('content-type', 'application/json'); response.setHeader('cache-control', 'no-store'); response.setHeader('vary', 'authorization, accept'); response.statusCode = status; - response.end(JSON.stringify(document)); + response.end(bytes); + }; + const answer = (status, document) => { + answerBytes(status, JSON.stringify(document)); }; if (request.method === 'POST' && path.endsWith('/v1/records/people/ingestion-runs')) { return answer(201, { run: runWire() }); } if (request.method === 'GET' && path.includes('/chunks/0/receipt')) { - return answer(200, { receipt: receiptWire() }); + const profile = new URL(request.url, 'http://localhost').searchParams.get('accessProfile'); + return answerBytes(200, malformedReceipts[profile] ?? receiptBytes); } if (request.method === 'GET' && /ingestion-runs\/[0-9a-f-]+$/.test(path)) { return answer(200, { run: runWire({ status: 'cancelled', nextChunkIndex: 1 }) }); @@ -331,8 +344,12 @@ test('submitIngestionChunk sends the encoded chunk under the run profile', async test('ingestionChunkReceipt reads one retained receipt and reports an erased one', async () => { const client = new BaseRegistryClient({ baseUrl }); + const before = seen.length; const retained = await client.ingestionChunkReceipt('people', RUN_ID, 0, 'importer.v1'); - assert.equal(retained.value.replayed, false); + const expected = { ...receiptWire(), replayed: true }; + expected.batch.results[0].futureItem = true; + assert.deepEqual(retained.value, expected); + assert.equal(retained.value.replayed, true); assert.equal(retained.value.batch.results.length, 1); assert.equal(seen.at(-1).url, `/v1/records/people/ingestion-runs/${RUN_ID}/chunks/0/receipt?accessProfile=importer.v1`); await assert.rejects(client.ingestionChunkReceipt('people', RUN_ID, 1, 'importer.v1'), (error) => ( @@ -341,4 +358,60 @@ test('ingestionChunkReceipt reads one retained receipt and reports an erased one && error.code === 'ingestion.receipt-erased' && error.status === 410 )); + for (const profile of Object.keys(malformedReceipts)) { + await assert.rejects(client.ingestionChunkReceipt('people', RUN_ID, 0, profile), (error) => ( + error instanceof BaseRegistryClientError && error.kind === 'protocol' + )); + } + assert.equal(seen.length - before, 5); +}); + +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/__test__/proposal-exact-json.test.js b/crates/registry-breg-client-node/__test__/proposal-exact-json.test.js index e99796ef71..3eb4fba0e5 100644 --- a/crates/registry-breg-client-node/__test__/proposal-exact-json.test.js +++ b/crates/registry-breg-client-node/__test__/proposal-exact-json.test.js @@ -11,7 +11,7 @@ const metadata = {id: 'proposal-json', version: '1', revision, metadataVersion: proposals: {method: 'GET', path: '/v1/proposals', accessProfiles: ['author'], actions: [{actionId: 'correct', accessProfile: 'author', operations: ['get', 'list'], readableInputs: [], readableContextFields: []}], get: {method: 'GET', path: '/v1/proposals/{proposal_id}', accessProfiles: ['author']}}}; -const proposal = {id, actionId: 'correct', actionRevision: revision, submissionVersion: 1, revision: 1, state: 'draft', links: { +const proposal = {id, actionId: 'correct', actionRevision: revision, submissionVersion: 1, revision: 1, state: 'draft', turn: 'party', links: { self: {method: 'GET', path: `/v1/proposals/${id}`, accessProfile: 'author', operation: 'get'}, edit: {method: 'POST', path: `/v1/proposals/${id}/edit`, accessProfile: 'author', operation: 'edit', ifMatch: '"draft-condition"'}, }}; diff --git a/crates/registry-breg-client-node/__test__/proposal-input-boundary.test.js b/crates/registry-breg-client-node/__test__/proposal-input-boundary.test.js index b59c6560dc..d04a3121da 100644 --- a/crates/registry-breg-client-node/__test__/proposal-input-boundary.test.js +++ b/crates/registry-breg-client-node/__test__/proposal-input-boundary.test.js @@ -40,7 +40,7 @@ test('Proposal input canonical bound is preserved through native preparation and const get = (await client.registryContract('writer')).selectProposalGet('writer'); for (const [operation, state] of [['edit', 'draft'], ['revise', 'submitted'], ['rebase', 'draft'], ['rebase', 'submitted']]) { document = {id, actionId: 'correct', actionRevision: revision, submissionVersion: 1, revision: 2, - state, ...(state === 'submitted' ? {effectDigest: revision} : {}), links: { + state, turn: state === 'draft' ? 'party' : 'official', ...(state === 'submitted' ? {effectDigest: revision} : {}), links: { self: {method: 'GET', path: `/v1/proposals/${id}`, accessProfile: 'writer', operation: 'get'}, [operation]: {method: 'POST', path: `/v1/proposals/${id}/${operation}`, accessProfile: 'writer', operation, ifMatch: '"condition"'}, @@ -61,7 +61,7 @@ test('Proposal input canonical bound is preserved through native preparation and assert.throws(() => BRegPreparedProposal.fromBytes(Buffer.from(JSON.stringify(invalid))), error => error.kind === 'invalid-request'); assert.equal(requests, before); - document = {...document, state: 'draft', revision: 3, submissionVersion: state === 'submitted' ? 2 : 1}; + document = {...document, state: 'draft', turn: 'party', revision: 3, submissionVersion: state === 'submitted' ? 2 : 1}; delete document.effectDigest; await client.executeProposal(recovered); assert.equal(requests, before + 1); diff --git a/crates/registry-breg-client-node/__test__/proposal-response-tolerance.test.js b/crates/registry-breg-client-node/__test__/proposal-response-tolerance.test.js new file mode 100644 index 0000000000..e5217d001d --- /dev/null +++ b/crates/registry-breg-client-node/__test__/proposal-response-tolerance.test.js @@ -0,0 +1,224 @@ +'use strict'; +const assert = require('node:assert/strict'); +const http = require('node:http'); +const { test } = require('node:test'); +const { inspect } = require('node:util'); +const { BaseRegistryClient, BaseRegistryClientError } = require('..'); +const fixtures = require('../../registry-breg-client/tests/fixtures/proposal-response-tolerance.json'); + +test('Proposal Get decodes the shared raw response fixtures', async t => { + let fixture; + let promoted; + const server = http.createServer((request, response) => { + const metadata = request.url.includes('/v1/registry'); + response.statusCode = metadata ? 200 : fixture.status; + if (response.statusCode !== 204) response.setHeader('content-type', response.statusCode < 300 ? 'application/json' : 'application/problem+json'); + response.setHeader('traceparent', '00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01'); + response.setHeader('cache-control', 'no-store'); + response.setHeader('vary', 'authorization, accept'); + if (metadata) return response.end(JSON.stringify(fixtures.metadata)); + if (fixture.route === 'promoted' && !promoted) { + promoted = true; + return response.end(fixtures.heldProposal); + } + if (fixture.route === 'page' && !request.url.includes('/messages?')) { + response.statusCode = 200; + response.setHeader('content-type', 'application/json'); + return response.end(fixtures.heldProposal); + } + if (fixture.route === 'mark' && request.method === 'GET') { + response.statusCode = 200; + response.setHeader('content-type', 'application/json'); + return response.end(fixtures.heldProposal); + } + if (['promotedContext', 'promotedStatus'].includes(fixture.route) + && request.url.split('?')[0].endsWith(fixtures.id)) return response.end(fixtures.heldProposal); + if (['send', 'reviewMark'].includes(fixture.route) && request.method === 'GET') { + response.statusCode = 200; + response.setHeader('content-type', 'application/json'); + return response.end(fixtures.heldReview); + } + if (fixture.headerFault === 'media') response.setHeader('content-type', 'application/json'); + if (fixture.headerFault === 'framing') response.setHeader('content-length', '1'); + if (fixture.headerFault === 'cache') response.removeHeader('cache-control'); + if (fixture.headerFault === 'trace') response.setHeader('traceparent', 'invalid'); + response.end(fixture.body); + }); + await new Promise(resolve => server.listen(0, '127.0.0.1', resolve)); + try { + const client = new BaseRegistryClient({baseUrl: `http://127.0.0.1:${server.address().port}/`}); + const contract = await client.registryContract('reader'); + const get = contract.selectProposalGet('reader'); + const review = contract.selectProposalReviewContext('reader', 'correct'); + const exercise = async () => { + if (fixture.route === 'list') { + return JSON.parse((await client.listProposals(contract.selectProposals('reader'), {})).items[0].documentJson); + } + if (fixture.route === 'promoted') { + const held = await client.getProposal(get, fixtures.id); + return JSON.parse((await client.readProposal(held)).documentJson); + } + if (fixture.route === 'page') { + const held = await client.getProposal(get, fixtures.id); + return (await client.listProposalMessages(held, null, 2)).value; + } + if (fixture.route === 'batch') return (await client.readProposalReviewContextBatch(review, [fixtures.id])).value; + if (fixture.route === 'mark') { + return client.markProposalMessagesRead(await client.getProposal(get, fixtures.id), '00000000-0000-4000-8000-000000000002'); + } + if (fixture.route === 'promotedContext' || fixture.route === 'promotedStatus') { + const held = await client.getProposal(get, fixtures.id); + return (fixture.route === 'promotedContext' + ? await client.readProposalReviewContext(held) : await client.readProposalReviewStatus(held)).value; + } + if (fixture.route === 'status') { + const status = contract.selectProposalReviewStatus('reader', 'correct'); + return (await client.readProposalReviewById(status, fixtures.id)).value; + } + if (fixture.route === 'context') return (await client.readProposalReviewById(review, fixtures.id)).value; + if (fixture.route === 'reviewMark') { + const held = (await client.readProposalReviewById(review, fixtures.id)).value; + return client.markProposalMessagesReadFromReview(review, held, '00000000-0000-4000-8000-000000000002'); + } + if (fixture.route === 'send') { + const held = (await client.readProposalReviewById(review, fixtures.id)).value; + return (await client.sendProposalMessageFromReview(review, held, 'Synthetic reply', 'response-fixture')).value; + } + return JSON.parse((await client.getProposal(get, fixtures.id)).documentJson); + }; + for (fixture of fixtures.cases) await t.test(fixture.name, async () => { + promoted = false; + const result = exercise(); + if (fixture.name === 'additive') { + const document = await result; + assert.equal(document.futureMember, undefined); + assert.equal(document.links['future-relation'], undefined); + assert.equal(document.links.self.futureMember, undefined); + const entry = document.additionalForms.extra.items[0]; + assert.equal(entry.input.futureMember, 'Declared input'); + assert.equal(entry.futureMember, undefined); + assert.equal(document.messages.items[0].futureMember, undefined); + return; + } + if (fixture.accept && fixture.status === 204) { + const outcome = await result; + if (fixture.route === 'mark') assert.equal(outcome, null); + else { + assert.equal(outcome.kind, 'complete'); + assert.equal(outcome.value, null); + assert.equal(outcome.traceId, '4bf92f3577b34da6a3ce929d0e0e4736'); + } + return; + } + if (fixture.accept && fixture.status === 200) { + const document = await result; + if (fixture.route !== 'mark' && fixture.name.endsWith('CurrentTurn')) { + assert.equal(document.turn, 'official'); + assert.equal(document.futureMember, undefined); + } + if (fixture.name.endsWith('KeepsForms')) assert.deepEqual(document.context.additionalForms, {extra: 'extra'}); + if (fixture.name.startsWith('batchReader')) { + const thread = document[0].context.messages; + assert.equal(thread.unread, 1); + const expected = {batchReaderOfficial: 'official', batchReaderParty: 'party'}[fixture.name]; + assert.equal(thread.readerSide, expected); + } + if (fixture.name === 'validCitedForm') { + const entry = document.context.asks[0].answer.formEntries[0]; + assert.equal(entry.input.futureMember, 'Declared input'); + assert.equal(entry.futureMember, undefined); + } + if (fixture.name.endsWith('Forms8')) { + const forms = (fixture.route === 'batch' ? document[0] : document).context.additionalForms; + assert.equal(Object.keys(forms).length, 8); + assert.equal(forms['form-8'], 'form-8'); + } + if (fixture.route === 'reviewMark') { + const member = {reviewMarkReviewReply: 'context', reviewMarkProposalReply: 'state', reviewMarkThreadReply: 'count'}[fixture.name]; + assert.ok(Object.hasOwn(document.value, member)); + } + if (['threadUnavailablePair', 'pageThreadUnavailablePair'].includes(fixture.name)) { + assert.deepEqual(document.links.message.availability, { + available: false, observedRevision: 3, reason: 'limit-reached', recovery: 'receipt-only', + }); + } + if (fixture.name === 'reviewReplyWithBrokenOuterThread') { + assert.ok(document.context.messages); + assert.equal(document.count, undefined); + } + if (fixture.name === 'reviewSendIdOnlyPolicy') { + assert.deepEqual(document.policy, {id: 'case-review'}); + } + if (fixture.name === 'reviewSendPinnedPolicy') { + assert.deepEqual(document.policy, JSON.parse(fixture.body).policy); + } + if (fixture.name === 'proposalReplyWithUnusedCounts') { + assert.equal(document.state, 'submitted'); + assert.equal(document.count, undefined); + assert.equal(document.unread, undefined); + } + if (fixture.name === 'proposalReplyWithUnusedContext') assert.equal(document.context, undefined); + if (fixture.name === 'threadReplyWithUnusedAction') assert.equal(document.actionId, undefined); + if (fixture.name === 'reviewReplyWithUnusedState') assert.equal(document.state, undefined); + if (fixture.name === 'emptyPageLinks') assert.deepEqual(document.links, {}); + return; + } + await assert.rejects(result, error => { + assert.ok(error instanceof BaseRegistryClientError); + if (fixture.name.startsWith('threadProblem')) { + const problem = JSON.parse(fixture.body); + assert.equal(error.status, 400); + assert.equal(error.traceId, problem.traceId); + assert.equal(error.kind, fixture.accept ? 'problem' : 'protocol'); + assert.equal(error.code, fixture.accept ? problem.code : 'problem'); + assert.equal(error.fieldPath, fixture.accept ? problem.fieldPath : undefined); + } else if (fixture.name.startsWith('unknown') || fixture.name.startsWith('futureSuffix')) { + const {code, type} = JSON.parse(fixture.body); + assert.equal(error.kind, 'problem'); + assert.equal(error.status, fixture.status); + assert.equal(error.code, code); + assert.equal(error.problemType, type); + assert.equal(error.traceId, '4bf92f3577b34da6a3ce929d0e0e4736'); + assert.equal(error.outcomeUnknown, fixture.status >= 500); + assert.ok(!inspect(error).includes(code)); + assert.doesNotMatch(inspect(error), /future\.refused|https:\/\/|Synthetic|Reworded/); + } else if (fixture.name === 'legacyPlanRefusal') { + assert.equal(error.kind, 'problem'); + assert.equal(error.status, 400); + assert.equal(error.code, undefined); + assert.equal(error.problemType, undefined); + assert.equal(error.outcomeUnknown, false); + } else if (fixture.name === 'rewordedKnown') { + assert.equal(error.kind, 'not-found'); + assert.equal(error.status, 404); + assert.equal(error.code, 'resource.not-found'); + } else if (fixture.status === 204) { + assert.equal(error.kind, 'protocol'); + assert.equal(error.code, fixture.failure); + assert.equal(error.status, 204); + assert.equal(error.traceId, fixture.headerFault === 'trace' ? undefined : '4bf92f3577b34da6a3ce929d0e0e4736'); + } else if (fixture.status === 201) { + assert.equal(error.kind, 'protocol'); + assert.equal(error.code, 'status'); + assert.equal(error.status, 201); + assert.equal(error.traceId, '4bf92f3577b34da6a3ce929d0e0e4736'); + } else if (['context', 'batch', 'promotedContext', 'status', 'promotedStatus'].includes(fixture.route)) { + assert.equal(error.kind, 'invalid-request'); + assert.equal(error.outcomeUnknown, false); + } else if (fixture.status !== 200) { + assert.equal(error.kind, 'protocol'); + assert.equal(error.code, 'problem'); + } else { + assert.equal(error.kind, 'protocol'); + assert.equal(error.code, 'body'); + assert.equal(error.status, 200); + assert.equal(error.traceId, '4bf92f3577b34da6a3ce929d0e0e4736'); + assert.equal(error.outcomeUnknown, true); + } + return true; + }); + }); + } finally { + await new Promise(resolve => server.close(resolve)); + } +}); diff --git a/crates/registry-breg-client-node/__test__/proposal-results.test.js b/crates/registry-breg-client-node/__test__/proposal-results.test.js index 45b58126ad..60a1d38348 100644 --- a/crates/registry-breg-client-node/__test__/proposal-results.test.js +++ b/crates/registry-breg-client-node/__test__/proposal-results.test.js @@ -49,7 +49,10 @@ test('Proposal response boundaries preserve disclosure and exact Action revision } response.writeHead(replyStatus, {'content-type': replyContentType, 'cache-control': 'no-store', 'vary': 'authorization, accept', traceparent: '00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01'}); - response.end(JSON.stringify(request.url.startsWith('/v1/registry') ? metadata : value)); + const isProposalGet = request.method === 'GET' && request.url.split('?')[0] === `/v1/proposals/${id}`; + const turn = {draft: 'party', submitted: 'official', applied: 'nobody', rejected: 'nobody', cancelled: 'nobody'}[value.state]; + const served = isProposalGet && turn && value.turn === undefined ? {...value, turn} : value; + response.end(JSON.stringify(request.url.startsWith('/v1/registry') ? metadata : served)); }); await new Promise(resolve => server.listen(0, '127.0.0.1', resolve)); try { @@ -93,7 +96,7 @@ test('Proposal response boundaries preserve disclosure and exact Action revision value.links.apply.availability.reason = reason; value.applicationStatus.recovery = recovery; value.links.apply.availability.recovery = recovery; - await assert.rejects(client.getProposal(binding, id), error => error.kind === 'invalid-request', `${reason}/${recovery}`); + await assert.rejects(client.getProposal(binding, id), error => error.kind === 'protocol', `${reason}/${recovery}`); } }); @@ -146,14 +149,18 @@ test('Proposal response boundaries preserve disclosure and exact Action revision item => {item.application.effectDigest = 'sha256:UPPERCASE';}, item => {item.application.resultLinks[0].revision = 0;}, item => {item.application.resultLinks[0].recordId = 'not-a-uuid';}, - item => {item.application.actorReference = 'private-canary';}, - item => {item.application.reason = 'private-canary';}, - item => {item.application.resultLinks[0].href = 'https://elsewhere.invalid/private';}, ]) { value = document(); mutate(value); await assert.rejects(client.getProposal(binding, id), error => ['invalid-request', 'protocol'].includes(error.kind)); } + value = document(); + value.application.actorReference = 'private-canary'; + value.application.reason = 'private-canary'; + value.application.resultLinks[0].href = 'https://elsewhere.invalid/private'; + const projected = JSON.parse((await client.getProposal(binding, id)).documentJson); + assert.deepEqual(projected.application, document().application); + await t.test('application identity is canonical and exact receipt recovery survives validation', async () => { value = document(); value.state = 'submitted'; delete value.application; value.links.apply = {method: 'POST', path: `/v1/proposals/${id}/apply`, accessProfile: 'reader', operation: 'apply', ifMatch: '"apply-condition"'}; @@ -166,7 +173,7 @@ test('Proposal response boundaries preserve disclosure and exact Action revision receipt.links.apply.availability = {available: false, observedRevision: 9, reason: 'already-applied', recovery: 'receipt-only'}; for (const applicationId of [canonical.toUpperCase(), canonical.replaceAll('-', ''), '00000000-0000-0000-0000-000000000000']) { value = structuredClone(receipt); value.application.applicationId = applicationId; - await assert.rejects(client.getProposal(binding, id), error => error.kind === 'invalid-request'); + await assert.rejects(client.getProposal(binding, id), error => error.kind === 'protocol'); await assert.rejects(client.executeProposal(attempt), error => error.kind === 'protocol' && error.outcomeUnknown); } value = receipt; @@ -192,7 +199,7 @@ test('Proposal response boundaries preserve disclosure and exact Action revision const availability = {available: false, observedRevision: 8, reason: 'stale-revision', recovery: 'receipt-only'}; delete availability[missing]; value.attachments.support.links.upload.availability = availability; - await assert.rejects(client.getProposal(binding, id), error => error.kind === 'invalid-request'); + await assert.rejects(client.getProposal(binding, id), error => error.kind === 'protocol'); value.revision = availability.observedRevision = 9; await assert.rejects(client.executeProposal(attempt), error => error.kind === 'protocol' && error.outcomeUnknown); } @@ -212,7 +219,7 @@ test('Proposal response boundaries preserve disclosure and exact Action revision for (const recordId of [canonical.toUpperCase(), canonical.replaceAll('-', '')]) { value = document(); value.application.resultLinks[0].recordId = recordId; const count = requests.length; - await assert.rejects(client.getProposal(binding, id), error => error.kind === 'invalid-request'); + await assert.rejects(client.getProposal(binding, id), error => error.kind === 'protocol'); assert.equal(requests.length, count + 1, 'validate the actual received result reference'); } }); @@ -243,16 +250,16 @@ test('Proposal response boundaries preserve disclosure and exact Action revision value = document(); value.state = state; value.submissionVersion = 0; delete value.application; if (state === 'draft') delete value.effectDigest; - await assert.rejects(client.getProposal(binding, id), error => error.kind === 'invalid-request'); + await assert.rejects(client.getProposal(binding, id), error => error.kind === 'protocol'); } value = document(); value.state = 'submitted'; delete value.application; delete value.effectDigest; - await assert.rejects(client.getProposal(binding, id), error => error.kind === 'invalid-request'); + await assert.rejects(client.getProposal(binding, id), error => error.kind === 'protocol'); value = document(); value.state = 'draft'; delete value.application; - await assert.rejects(client.getProposal(binding, id), error => error.kind === 'invalid-request'); + await assert.rejects(client.getProposal(binding, id), error => error.kind === 'protocol'); delete value.effectDigest; assert.equal(JSON.parse((await client.getProposal(binding, id)).documentJson).state, 'draft'); value = document(); delete value.application; - await assert.rejects(client.getProposal(binding, id), error => error.kind === 'invalid-request'); + await assert.rejects(client.getProposal(binding, id), error => error.kind === 'protocol'); }); await t.test('Review status preserves pending, terminal and expired evidence and Context excludes results', async () => { value = document(); value.state = 'submitted'; delete value.application; @@ -471,7 +478,7 @@ test('Proposal response boundaries preserve disclosure and exact Action revision const disclosed = structuredClone(value); for (const uploadedAt of [undefined, 'private-canary', '2026-10-15']) { value = structuredClone(disclosed); value.attachments.support.value.uploadedAt = uploadedAt; - await assert.rejects(client.getProposal(binding, id), error => error.kind === 'invalid-request' && !error.message.includes('private-canary')); + await assert.rejects(client.getProposal(binding, id), error => error.kind === 'protocol' && !error.message.includes('private-canary')); } value = disclosed; const retained = await client.getProposal(binding, id); @@ -538,10 +545,10 @@ test('Proposal turn, decision and the submission read decode exactly', async () error => error.kind === 'problem' && error.code === 'proposal.submission-expired'); await assert.rejects(client.readProposalSubmission(current, 0), error => error.kind === 'invalid-request'); proposal.decision = {...proposal.decision, publicReason: 'x'.repeat(2001)}; - await assert.rejects(client.getProposal(binding, id), error => error.kind === 'invalid-request'); + await assert.rejects(client.getProposal(binding, id), error => error.kind === 'protocol'); proposal.decision = {status: 'rejected', decidedAt: '2026-10-01T10:00:00.000000Z'}; proposal.turn = 'someone'; - await assert.rejects(client.getProposal(binding, id), error => error.kind === 'invalid-request'); + await assert.rejects(client.getProposal(binding, id), error => error.kind === 'protocol'); } finally { server.close(); } diff --git a/crates/registry-breg-client-node/__test__/proposals.test.js b/crates/registry-breg-client-node/__test__/proposals.test.js index 6069f44aac..1382446636 100644 --- a/crates/registry-breg-client-node/__test__/proposals.test.js +++ b/crates/registry-breg-client-node/__test__/proposals.test.js @@ -22,7 +22,7 @@ const metadata = { requiresIdempotencyKey: true, inputSchema: 'action-correct-invoke-input', responseSchema: 'action-correct-invoke-response'}}, bounds: {maximumTargets: 16, maximumFieldMutations: 128, maximumSnapshotBytes: 2097152}}], }; -const proposal = {id, actionId: 'correct', actionRevision: revision, submissionVersion: 1, revision: 1, state: 'draft', partyRole: 'owner', links: { +const proposal = {id, actionId: 'correct', actionRevision: revision, submissionVersion: 1, revision: 1, state: 'draft', turn: 'party', partyRole: 'owner', links: { self: {method: 'GET', path: `/v1/proposals/${id}`, accessProfile: 'author', operation: 'get'}, edit: {method: 'POST', path: `/v1/proposals/${id}/edit`, accessProfile: 'author', operation: 'edit', ifMatch: '"draft-condition"'}, submit: {method: 'POST', path: `/v1/proposals/${id}/submit`, accessProfile: 'author', operation: 'submit', ifMatch: '"draft-condition"'}, @@ -57,10 +57,10 @@ test('Proposal status is a closed served value and application-pending requires }}; assert.equal(JSON.parse((await client.getProposal(binding, id)).documentJson).links.revise.availability.reason, 'application-pending'); document.links.revise.availability.recovery = 'retry'; - await assert.rejects(client.getProposal(binding, id), error => error.kind === 'invalid-request'); + await assert.rejects(client.getProposal(binding, id), error => error.kind === 'protocol'); for (const status of ['unknown', null, false, 1]) { document = {...proposal, status}; - await assert.rejects(client.getProposal(binding, id), error => error.kind === 'invalid-request'); + await assert.rejects(client.getProposal(binding, id), error => error.kind === 'protocol'); } document = proposal; assert.equal(JSON.parse((await client.getProposal(binding, id)).documentJson).status, undefined); @@ -79,6 +79,7 @@ test('proposal object methods preserve exact bodies and refuse JSON strings befo if (request.url.startsWith('/tenant/v1/registry')) return response.end(JSON.stringify(metadata)); if (request.url.startsWith('/tenant/v1/proposals?')) return response.end(JSON.stringify({items: [proposal]})); if (request.url.includes('/submit?')) return response.end(JSON.stringify({...proposal, revision: 2, state: 'submitted', effectDigest: revision})); + if (request.url.startsWith('/tenant/v1/actions/')) response.statusCode = 201; response.end(JSON.stringify(proposal)); }); await new Promise(resolve => server.listen(0, '127.0.0.1', resolve)); @@ -284,6 +285,7 @@ test('Proposal Start accepts exact Draft replay and refuses otherwise valid term assert.deepEqual(requests.at(-1), requests.at(-2)); for (const state of ['submitted', 'applied', 'cancelled']) { value = structuredClone(proposal); value.state = state; value.submissionVersion = 1; value.links = {self: value.links.self}; + value.turn = state === 'submitted' ? 'official' : 'nobody'; if (state === 'submitted') value.effectDigest = revision; assert.equal(JSON.parse((await client.getProposal(get, id)).documentJson).state, state, 'ordinary reads permit this representation'); const count = requests.length; @@ -342,6 +344,7 @@ test('Proposal responseEtag observes only its individual HTTP response and never response.setHeader('vary', 'authorization, accept'); response.setHeader('traceparent', '00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01'); if (request.url.startsWith('/v1/registry')) return response.end(JSON.stringify(metadata)); + if (request.url.startsWith('/v1/actions/')) response.statusCode = 201; if (observed !== null) response.setHeader('etag', observed); response.end(JSON.stringify(request.url.startsWith('/v1/proposals?') ? {items: [proposal]} : request.url.includes('/submit?') ? {...proposal, revision: 2, state: 'submitted', effectDigest: revision} : proposal)); @@ -392,7 +395,7 @@ for (const operation of ['recovered-start', 'upload', 'delete']) { value.revision++; Object.assign(value.attachments[slot].value, { sha256: createHash('sha256').update(body).digest('hex'), contentType: request.headers['content-type'], byteSize: body.length }); } else if (request.method === 'DELETE') { value.revision++; delete value.attachments[slot].value; } - response.writeHead(200, { 'content-type': 'application/json', 'cache-control': 'no-store', vary: 'authorization, accept', + response.writeHead(request.url.startsWith('/v1/actions/') ? 201 : 200, { 'content-type': 'application/json', 'cache-control': 'no-store', vary: 'authorization, accept', traceparent: '00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01', ...(!request.url.startsWith('/v1/registry') && observed !== null ? { etag: observed } : {}) }); response.end(JSON.stringify(value)); diff --git a/crates/registry-breg-client-node/__test__/read-cancellation.test.js b/crates/registry-breg-client-node/__test__/read-cancellation.test.js index 41e641b9d3..585118bea8 100644 --- a/crates/registry-breg-client-node/__test__/read-cancellation.test.js +++ b/crates/registry-breg-client-node/__test__/read-cancellation.test.js @@ -196,7 +196,7 @@ test('metadata-bound proposal get/list cancellation preserves opaque bindings an get: { method: 'GET', path: '/v1/proposals/{proposal_id}', accessProfiles: ['reader'] } } }; const reads = []; let hold = true, observed = '\"breg-cancel-compatible-response\"'; - const proposal = { id, actionId: 'correct', actionRevision: revision, submissionVersion: 1, revision: 1, state: 'draft', + const proposal = { id, actionId: 'correct', actionRevision: revision, submissionVersion: 1, revision: 1, state: 'draft', turn: 'party', links: { self: { method: 'GET', path: `/v1/proposals/${id}`, accessProfile: 'reader', operation: 'get' } } }; const server = http.createServer((request, response) => { response.setHeader('content-type', 'application/json'); response.setHeader('traceparent', traceparent); @@ -206,7 +206,7 @@ test('metadata-bound proposal get/list cancellation preserves opaque bindings an response.on('close', () => { entry.closed = true; }); if (!hold) { if (observed !== null) response.setHeader('etag', observed); - response.end(JSON.stringify(request.url.split('?')[0] === '/v1/proposals' ? { items: [proposal], nextCursor: null } : proposal)); + response.end(JSON.stringify(request.url.split('?')[0] === '/v1/proposals' ? { items: [proposal] } : proposal)); } }); await new Promise(resolve => server.listen(0, '127.0.0.1', resolve)); diff --git a/crates/registry-breg-client-node/__test__/review-messages.test.js b/crates/registry-breg-client-node/__test__/review-messages.test.js index 1264878da1..f320e1c172 100644 --- a/crates/registry-breg-client-node/__test__/review-messages.test.js +++ b/crates/registry-breg-client-node/__test__/review-messages.test.js @@ -45,6 +45,9 @@ test('a review-context thread write accepts each answer BReg gives a reviewer', response.setHeader('vary', 'authorization, accept'); response.setHeader('content-type', 'application/json'); if (request.url.includes('/registry?')) return response.end(JSON.stringify(metadata)); + if (request.method === 'GET' && request.url.includes(threadPath)) { + return response.end(JSON.stringify({items: [party], links: {}})); + } if (request.method === 'GET') return response.end(JSON.stringify(context([party]))); observed += 1; const items = [mine(JSON.parse(requests.at(-1).body.toString()).text), party]; @@ -56,6 +59,11 @@ test('a review-context thread write accepts each answer BReg gives a reviewer', const client = new BaseRegistryClient({ baseUrl: `http://127.0.0.1:${server.address().port}/tenant/` }); const contract = await client.registryContract('reviewer'); const binding = contract.selectProposalReviewContext('reviewer', 'correct'); + const first = (await client.readProposalReviewById(binding, id)).value; + const page = await client.listProposalMessagesFromReview(binding, first, '7', 2); + assert.equal(page.value.items[0].id, question); + assert.deepEqual(Object.fromEntries(new URL(requests.at(-1).url, 'http://localhost').searchParams), + {accessProfile: 'reviewer', limit: '2', cursor: '7'}); for (const [kind, member] of [['review', value => value.context.messages], ['proposal', value => value.messages], ['thread', value => value]]) { answer = kind; diff --git a/crates/registry-breg-client-node/client.d.ts b/crates/registry-breg-client-node/client.d.ts index 95b4efadfd..cb00a57a8d 100644 --- a/crates/registry-breg-client-node/client.d.ts +++ b/crates/registry-breg-client-node/client.d.ts @@ -890,6 +890,7 @@ export type BRegConstraintViolation = { export interface BaseRegistryClientFailure extends Error { readonly kind: string readonly code?: string + readonly problemType?: string readonly refusalCode?: string readonly reasonCode?: string readonly guardReason?: string @@ -918,6 +919,7 @@ export interface BaseRegistryClientFailure extends Error { export declare class BaseRegistryClientError extends Error implements BaseRegistryClientFailure { readonly kind: string readonly code?: string + readonly problemType?: string readonly refusalCode?: string readonly reasonCode?: string readonly guardReason?: string @@ -1023,11 +1025,11 @@ export declare class BaseRegistryClient { answerProposalAsk(proposal: BRegProposal, askId: string, body: BRegProposalAnswerRequest, key: string): Promise downloadProposalAddition(proposal: BRegProposal, addition: string): Promise sendProposalMessage(proposal: BRegProposal, text: string, key: string): Promise - listProposalMessages(proposal: BRegProposal, after?: string | null, limit?: number): Promise - markProposalMessagesRead(proposal: BRegProposal, through: string): Promise + listProposalMessages(proposal: BRegProposal, cursor?: string | null, limit?: number): Promise + markProposalMessagesRead(proposal: BRegProposal, through: string): Promise sendProposalMessageFromReview(binding: BRegProposalReviewBinding, context: BRegProposalReviewDocument, text: string, key: string): Promise - listProposalMessagesFromReview(binding: BRegProposalReviewBinding, context: BRegProposalReviewDocument, after?: string | null, limit?: number): Promise - markProposalMessagesReadFromReview(binding: BRegProposalReviewBinding, context: BRegProposalReviewDocument, through: string): Promise + listProposalMessagesFromReview(binding: BRegProposalReviewBinding, context: BRegProposalReviewDocument, cursor?: string | null, limit?: number): Promise + markProposalMessagesReadFromReview(binding: BRegProposalReviewBinding, context: BRegProposalReviewDocument, through: string): Promise addProposalFormEntry(proposal: BRegProposal, formId: string, input: JsonObject, key: string): Promise addProposalAddition(proposal: BRegProposal, slot: string, contentType: string, bytes: Buffer, key: string): Promise readProposalReviewStatus(proposal: BRegProposal, request?: ReadRequestOptions): Promise> @@ -1046,14 +1048,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 @@ -1123,12 +1125,18 @@ export interface BRegProposalMessages { } export interface BRegProposalMessagePage { readonly items: ReadonlyArray; readonly nextCursor?: string; + readonly links: Readonly>>; } export interface BRegMessagePageOutcome { readonly kind: 'complete'; readonly value: BRegProposalMessagePage; readonly traceId: string; } +export type BRegReviewMessageValue = BRegProposalDocument | BRegProposalReviewDocument | BRegProposalMessages export interface BRegReviewMessageOutcome { - readonly kind: 'complete'; readonly value: BRegProposalReviewDocument; + readonly kind: 'complete'; readonly value: BRegReviewMessageValue; + readonly traceId: string; readonly etag?: string; +} +export interface BRegReviewMarkReadOutcome { + readonly kind: 'complete'; readonly value: BRegReviewMessageValue | null; readonly traceId: string; readonly etag?: string; } export interface BRegProposalReviewDocument { @@ -1141,7 +1149,11 @@ export interface BRegProposalReviewDocument { readonly progressCode?: string /** Status reads only: where the submission stands with the Review provider. `reason` is present exactly when `state` is `failed`. */ readonly handoff?: {readonly state: 'pending' | 'accepted' | 'failed' | 'withdrawn'; readonly reason?: 'remote-refused' | 'producer-identity-mismatch' | 'review-acceptance-changed' | 'review-policy-changed' | 'submission-recovery-expired' | 'operator-closed' | 'unspecified'} - readonly authority?: string; readonly policy?: {readonly id: string; readonly version: string; readonly digest: string} + readonly authority?: string + readonly policy?: {readonly id: string} & ( + | {readonly version?: never; readonly digest?: never} + | {readonly version: string; readonly digest: string} + ) readonly result?: {readonly state: 'pending' | 'approved' | 'rejected' | 'changes-requested' | 'answered' | 'cancelled' | 'superseded' | 'expired'; readonly resultId?: string; readonly completedAt?: string; readonly availableUntil?: string} } /** Who is expected to act next, derived by BReg. */ diff --git a/crates/registry-breg-client-node/client.js b/crates/registry-breg-client-node/client.js index 837311f27c..bf47799ecf 100644 --- a/crates/registry-breg-client-node/client.js +++ b/crates/registry-breg-client-node/client.js @@ -15,10 +15,16 @@ class BaseRegistryClientError extends Error { this.name = 'BaseRegistryClientError'; this.kind = envelope.kind; this.outcomeUnknown = envelope.outcomeUnknown === true; - for (const field of ['code', 'refusalCode', 'reasonCode', 'status', 'traceId', 'transportKind', 'tokenKind']) { + const hasFutureProblem = typeof envelope.problemType === 'string'; + if (!hasFutureProblem && envelope.code !== undefined && envelope.code !== null) { + this.code = envelope.code; + } + for (const field of ['refusalCode', 'reasonCode', 'status', 'traceId', 'transportKind', 'tokenKind']) { if (envelope[field] !== undefined && envelope[field] !== null) this[field] = envelope[field]; } - for (const field of ['fieldPath', 'constraint', 'guardReason']) { + const structured = ['fieldPath', 'constraint', 'guardReason', 'problemType']; + if (hasFutureProblem) structured.push('code'); + for (const field of structured) { if (envelope[field] !== undefined && envelope[field] !== null) { Object.defineProperty(this, field, { value: envelope[field], diff --git a/crates/registry-breg-client-node/index.d.ts b/crates/registry-breg-client-node/index.d.ts index 5857283861..ffa58de3f3 100644 --- a/crates/registry-breg-client-node/index.d.ts +++ b/crates/registry-breg-client-node/index.d.ts @@ -69,10 +69,10 @@ export declare class BaseRegistryClient { readProposalReviewContextBatch(binding: BRegProposalReviewBinding, ids: Array, cancellation?: ReadCancellation | undefined | null): Promise answerProposalAsk(proposal: BRegProposal, askId: string, body: any, key: string): Promise sendProposalMessage(proposal: BRegProposal, text: string, key: string): Promise - listProposalMessages(proposal: BRegProposal, after?: string | undefined | null, limit?: number | undefined | null): Promise - markProposalMessagesRead(proposal: BRegProposal, through: string): Promise + listProposalMessages(proposal: BRegProposal, cursor?: string | undefined | null, limit?: number | undefined | null): Promise + markProposalMessagesRead(proposal: BRegProposal, through: string): Promise sendProposalMessageFromReview(binding: BRegProposalReviewBinding, context: any, text: string, key: string): Promise - listProposalMessagesFromReview(binding: BRegProposalReviewBinding, context: any, after?: string | undefined | null, limit?: number | undefined | null): Promise + listProposalMessagesFromReview(binding: BRegProposalReviewBinding, context: any, cursor?: string | undefined | null, limit?: number | undefined | null): Promise markProposalMessagesReadFromReview(binding: BRegProposalReviewBinding, context: any, through: string): Promise addProposalFormEntry(proposal: BRegProposal, formId: string, input: Record, key: string): Promise addProposalAddition(proposal: BRegProposal, slot: string, contentType: string, bytes: Buffer, key: string): Promise @@ -129,31 +129,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 @@ -190,7 +190,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..55f9abe034 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, @@ -423,7 +423,8 @@ fn client_error(error: BaseRegistryClientError) -> NapiError { let outcome_unknown = error.is_outcome_unknown(); let kind = error.kind(); let status = error.status(); - let code = error.problem_code().map(|value| value.code().to_owned()); + let code = error.problem_code_str().map(str::to_owned); + let problem_type = error.problem_type().map(str::to_owned); let refusal_code = error.refusal_code().map(|value| value.as_str().to_owned()); let reason_code = error.reason_code().map(str::to_owned); let guard_reason = error.guard_reason().map(str::to_owned); @@ -460,6 +461,8 @@ fn client_error(error: BaseRegistryClientError) -> NapiError { BaseRegistryClientError::UnrecognizedProblem { .. } => json!({ "kind": kind, "status": status, + "code": code, + "problemType": problem_type, "traceId": trace_id, "message": "Base Registry Engine refused or failed the request with an unrecognized problem code", }), @@ -1706,6 +1709,9 @@ fn review_message_result( registry_breg_client::BRegProposalMessageOutcome::Thread(thread) => { complete_value(*thread, result.metadata) } + registry_breg_client::BRegProposalMessageOutcome::NoContent => { + complete_value(Value::Null, result.metadata) + } } } @@ -2077,6 +2083,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()) } @@ -3657,14 +3674,14 @@ impl BaseRegistryClient { pub async fn list_proposal_messages( &self, proposal: &Proposal, - after: Option, + cursor: Option, limit: Option, ) -> Result { let result = self .inner .list_proposal_messages( registry_breg_client::BRegProposalMessageTarget::Proposal(&proposal.inner), - after.as_deref(), + cursor.as_deref(), limit.unwrap_or(20), ) .await @@ -3677,7 +3694,7 @@ impl BaseRegistryClient { &self, proposal: &Proposal, through: String, - ) -> Result { + ) -> Result> { let result = self .inner .mark_proposal_messages_read( @@ -3686,7 +3703,13 @@ impl BaseRegistryClient { ) .await .map_err(client_error)?; - proposal_message_result(result) + if matches!( + result.value, + registry_breg_client::BRegProposalMessageOutcome::NoContent + ) { + return Ok(None); + } + proposal_message_result(result).map(Some) } #[napi] @@ -3716,7 +3739,7 @@ impl BaseRegistryClient { &self, binding: &ProposalReviewBinding, context: Value, - after: Option, + cursor: Option, limit: Option, ) -> Result { let document = review_message_document(context)?; @@ -3726,7 +3749,7 @@ impl BaseRegistryClient { }; let result = self .inner - .list_proposal_messages(target, after.as_deref(), limit.unwrap_or(20)) + .list_proposal_messages(target, cursor.as_deref(), limit.unwrap_or(20)) .await .map_err(client_error)?; complete_value(result.value, result.metadata) @@ -4240,13 +4263,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 +4290,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 +4312,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 +4331,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 +4358,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 +4384,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 +4411,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 +4421,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 +4988,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..19b48f1d69 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 @@ -152,6 +152,7 @@ BRegConstraintViolation = BRegCompareConstraintViolation | BRegFieldConstraintVi class BaseRegistryClientError(Exception): kind: str code: str | None + problem_type: str | None refusal_code: str | None reason_code: str | None guard_reason: str | None @@ -333,6 +334,7 @@ BRegProposalMessage = TypedDict('BRegProposalMessage', { class BRegProposalMessagePage(TypedDict): items: list[BRegProposalMessage] nextCursor: NotRequired[str] + links: dict[Literal["message", "markRead", "list"], dict[str, JsonValue]] class BRegMessagePageOutcome(TypedDict): kind: Literal['complete'] value: BRegProposalMessagePage @@ -355,6 +357,40 @@ class BRegProposalReviewDocument(TypedDict): policy: NotRequired[dict[str, JsonValue]] result: NotRequired[dict[str, JsonValue]] +class BRegProposalMessageThread(TypedDict): + count: int + unread: int + readerSide: NotRequired[Literal["party", "official"]] + lastSentAt: NotRequired[str] + items: NotRequired[list[BRegProposalMessage]] + links: NotRequired[dict[Literal["message", "markRead", "list"], dict[str, JsonValue]]] + +class BRegProposalMessageDocument(TypedDict): + id: str + actionId: str + actionRevision: str + submissionVersion: int + revision: int + state: Literal["draft", "submitted", "cancelled", "applied", "rejected"] + links: dict[str, JsonValue] + messages: BRegProposalMessageThread + +BRegReviewMessageValue = BRegProposalMessageDocument | BRegProposalReviewDocument | BRegProposalMessageThread + +class BRegReviewMessageOutcome(TypedDict): + kind: Literal["complete"] + value: BRegReviewMessageValue + trace_id: str + etag: str | None + location: str | None + +class BRegReviewMarkReadOutcome(TypedDict): + kind: Literal["complete"] + value: BRegReviewMessageValue | None + trace_id: str + etag: str | None + location: str | None + class BRegProposalReviewCompleteOutcome(TypedDict): kind: Literal["complete"] value: BRegProposalReviewDocument @@ -711,11 +747,11 @@ class BaseRegistryClient: def answer_proposal_ask(self, proposal: BRegProposal, ask_id: str, body: BRegProposalAnswerRequest, key: str) -> BRegProposal: ... def download_proposal_addition(self, proposal: BRegProposal, addition: str) -> dict[str, Any]: ... def send_proposal_message(self, proposal: BRegProposal, text: str, key: str) -> BRegProposal: ... - def list_proposal_messages(self, proposal: BRegProposal, after: str | None = None, limit: int = 20) -> BRegMessagePageOutcome: ... - def mark_proposal_messages_read(self, proposal: BRegProposal, through: str) -> BRegProposal: ... - def send_proposal_message_from_review(self, binding: BRegProposalReviewBinding, context: BRegProposalReviewDocument, text: str, key: str) -> BRegProposalReviewCompleteOutcome: ... - def list_proposal_messages_from_review(self, binding: BRegProposalReviewBinding, context: BRegProposalReviewDocument, after: str | None = None, limit: int = 20) -> BRegMessagePageOutcome: ... - def mark_proposal_messages_read_from_review(self, binding: BRegProposalReviewBinding, context: BRegProposalReviewDocument, through: str) -> BRegProposalReviewCompleteOutcome: ... + def list_proposal_messages(self, proposal: BRegProposal, cursor: str | None = None, limit: int = 20) -> BRegMessagePageOutcome: ... + def mark_proposal_messages_read(self, proposal: BRegProposal, through: str) -> BRegProposal | None: ... + def send_proposal_message_from_review(self, binding: BRegProposalReviewBinding, context: BRegProposalReviewDocument, text: str, key: str) -> BRegReviewMessageOutcome: ... + def list_proposal_messages_from_review(self, binding: BRegProposalReviewBinding, context: BRegProposalReviewDocument, cursor: str | None = None, limit: int = 20) -> BRegMessagePageOutcome: ... + def mark_proposal_messages_read_from_review(self, binding: BRegProposalReviewBinding, context: BRegProposalReviewDocument, through: str) -> BRegReviewMarkReadOutcome: ... def add_proposal_form_entry(self, proposal: BRegProposal, form_id: str, input: dict[str, JsonValue], key: str) -> BRegProposal: ... def add_proposal_addition(self, proposal: BRegProposal, slot: str, content_type: str, bytes: bytes, key: str) -> BRegProposal: ... def read_proposal_review_status(self, proposal: BRegProposal) -> dict[str, Any]: ... @@ -742,11 +778,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 +796,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 +812,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 +829,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..62459c4290 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, @@ -55,6 +55,7 @@ struct MappedError { kind: &'static str, message: String, code: Option, + problem_type: Option, refusal_code: Option, reason_code: Option, guard_reason: Option, @@ -86,6 +87,9 @@ fn to_py_err(py: Python<'_>, mapped: MappedError) -> PyErr { instance .setattr("code", mapped.code) .expect("fresh exception accepts attributes"); + instance + .setattr("problem_type", mapped.problem_type) + .expect("fresh exception accepts attributes"); instance .setattr("refusal_code", mapped.refusal_code) .expect("fresh exception accepts attributes"); @@ -150,7 +154,8 @@ fn sdk_error(py: Python<'_>, error: RustClientError) -> PyErr { let outcome_unknown = error.is_outcome_unknown(); let mut mapped = MappedError::binding(error.kind(), error.to_string()); mapped.status = error.status(); - mapped.code = error.problem_code().map(|value| value.code().to_owned()); + mapped.code = error.problem_code_str().map(str::to_owned); + mapped.problem_type = error.problem_type().map(str::to_owned); mapped.refusal_code = error.refusal_code().map(|value| value.as_str().to_owned()); mapped.reason_code = error.reason_code().map(str::to_owned); mapped.guard_reason = error.guard_reason().map(str::to_owned); @@ -506,18 +511,28 @@ fn review_message_result<'py>( breg_client_sdk::BRegProposalMessageOutcome::Thread(thread) => { complete_value(py, &*thread, &result.metadata) } + breg_client_sdk::BRegProposalMessageOutcome::NoContent => { + complete_value(py, &Value::Null, &result.metadata) + } } } fn proposal_message_result( py: Python<'_>, - result: breg_client_sdk::BRegComplete, + outcome: breg_client_sdk::BRegProposalMessageOutcome, + etag: Option<&BRegEtag>, ) -> PyResult { - let breg_client_sdk::BRegProposalMessageOutcome::Proposal(inner) = result.value else { - return Err(invalid(py, "Expected a Proposal message response")); + let breg_client_sdk::BRegProposalMessageOutcome::Proposal(inner) = outcome else { + return Err(to_py_err( + py, + MappedError { + outcome_unknown: true, + ..MappedError::binding("protocol", "Expected a Proposal message response") + }, + )); }; Ok(Proposal { - response_etag: result.metadata.etag().map(|etag| etag.as_str().to_owned()), + response_etag: etag.map(|etag| etag.as_str().to_owned()), inner: *inner, }) } @@ -793,6 +808,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()) } @@ -3133,15 +3162,15 @@ impl BaseRegistryClient { )) }) .map_err(|error| sdk_error(py, error))?; - proposal_message_result(py, result) + proposal_message_result(py, result.value, result.metadata.etag()) } - #[pyo3(signature = (proposal, after=None, limit=20))] + #[pyo3(signature = (proposal, cursor=None, limit=20))] fn list_proposal_messages<'py>( &self, py: Python<'py>, proposal: PyRef<'_, Proposal>, - after: Option<&str>, + cursor: Option<&str>, limit: u8, ) -> PyResult> { let proposal = proposal.inner.clone(); @@ -3149,7 +3178,7 @@ impl BaseRegistryClient { .detach(|| { self.runtime.block_on(self.inner.list_proposal_messages( breg_client_sdk::BRegProposalMessageTarget::Proposal(&proposal), - after, + cursor, limit, )) }) @@ -3162,7 +3191,7 @@ impl BaseRegistryClient { py: Python<'_>, proposal: PyRef<'_, Proposal>, through: &str, - ) -> PyResult { + ) -> PyResult> { let proposal = proposal.inner.clone(); let result = py .detach(|| { @@ -3173,7 +3202,13 @@ impl BaseRegistryClient { )) }) .map_err(|error| sdk_error(py, error))?; - proposal_message_result(py, result) + if matches!( + result.value, + breg_client_sdk::BRegProposalMessageOutcome::NoContent + ) { + return Ok(None); + } + proposal_message_result(py, result.value, result.metadata.etag()).map(Some) } fn send_proposal_message_from_review<'py>( @@ -3200,13 +3235,13 @@ impl BaseRegistryClient { review_message_result(py, result) } - #[pyo3(signature = (binding, context, after=None, limit=20))] + #[pyo3(signature = (binding, context, cursor=None, limit=20))] fn list_proposal_messages_from_review<'py>( &self, py: Python<'py>, binding: PyRef<'_, ProposalReviewBinding>, context: &Bound<'_, PyAny>, - after: Option<&str>, + cursor: Option<&str>, limit: u8, ) -> PyResult> { let document = review_message_document(py, context)?; @@ -3218,7 +3253,7 @@ impl BaseRegistryClient { let result = py .detach(|| { self.runtime - .block_on(self.inner.list_proposal_messages(target, after, limit)) + .block_on(self.inner.list_proposal_messages(target, cursor, limit)) }) .map_err(|error| sdk_error(py, error))?; complete_value(py, &result.value, &result.metadata) @@ -3641,7 +3676,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 +3685,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 +3696,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 +3710,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 +3745,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 +3792,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 +3801,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 +3850,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 +3859,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) @@ -3891,3 +3964,31 @@ fn registry_breg_client(module: &Bound<'_, PyModule>) -> PyResult<()> { module.add("__version__", env!("CARGO_PKG_VERSION"))?; Ok(()) } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn unexpected_proposal_message_outcome_is_a_protocol_error() { + Python::attach(|py| { + let Err(error) = proposal_message_result( + py, + breg_client_sdk::BRegProposalMessageOutcome::NoContent, + None, + ) else { + panic!("a Proposal-only conversion must reject NoContent"); + }; + assert!(error.is_instance_of::(py)); + let kind: String = error.value(py).getattr("kind").unwrap().extract().unwrap(); + assert_eq!(kind, "protocol"); + let outcome_unknown: bool = error + .value(py) + .getattr("outcome_unknown") + .unwrap() + .extract() + .unwrap(); + assert!(outcome_unknown); + }); + } +} diff --git a/crates/registry-breg-client-py/tests/python/test_action_refusals.py b/crates/registry-breg-client-py/tests/python/test_action_refusals.py index b32ec410a5..901ad906ff 100644 --- a/crates/registry-breg-client-py/tests/python/test_action_refusals.py +++ b/crates/registry-breg-client-py/tests/python/test_action_refusals.py @@ -170,7 +170,10 @@ def test_the_typed_idempotency_key_reuse_problem_uses_the_current_wire_code(self } ) self.assertEqual(retired.kind, "problem") - self.assertIsNone(retired.code) + self.assertEqual(retired.code, "idempotency.conflict") + self.assertEqual(retired.problem_type, "https://id.registrystack.org/problems/registry-breg/idempotency/conflict") + self.assertEqual(retired.status, 409) + self.assertFalse(retired.outcome_unknown) def test_a_refusal_outside_the_published_bounds_fails_closed(self) -> None: silent = refusal() diff --git a/crates/registry-breg-client-py/tests/python/test_additions.py b/crates/registry-breg-client-py/tests/python/test_additions.py index 3995ae6e1f..46870e76a1 100644 --- a/crates/registry-breg-client-py/tests/python/test_additions.py +++ b/crates/registry-breg-client-py/tests/python/test_additions.py @@ -26,7 +26,7 @@ def test_addition_and_download_keep_the_exact_submission(self): 'actions': [{'actionId': 'correct', 'accessProfile': 'writer', 'operations': ['get'], 'readableInputs': [], 'readableContextFields': []}], 'get': {'method': 'GET', 'path': '/v1/proposals/{proposal_id}', 'accessProfiles': ['writer']}}} document = {'id': proposal_id, 'actionId': 'correct', 'actionRevision': revision, 'submissionVersion': 1, - 'revision': 2, 'state': 'submitted', 'effectDigest': revision, 'links': {}, 'additions': {'other': { + 'revision': 2, 'state': 'submitted', 'turn': 'official', 'effectDigest': revision, 'links': {}, 'additions': {'other': { 'id': 'other', 'maximumBytes': 64, 'maximumCount': 2, 'contentTypes': ['text/plain'], 'classification': 'restricted', 'items': [], 'links': {'add': {'method': 'POST', 'path': f'/v1/proposals/{proposal_id}/additions/other', 'accessProfile': 'writer', 'operation': 'add', 'ifMatch': '"condition"'}}}}} @@ -35,7 +35,7 @@ class Handler(BaseHTTPRequestHandler): def do_GET(self): requests.append(('GET', self.path, dict(self.headers), b'')) if thread_path in self.path: - self.respond(json.dumps({'items': document['messages']['items']}).encode()) + self.respond(json.dumps({'items': document['messages']['items'], 'links': {}}).encode()) elif f'/additions/{addition_id}?' in self.path: self.respond(content, 'text/plain', True) else: @@ -141,7 +141,8 @@ def thread_link(method, tail=''): current = client.get_proposal(contract.select_proposal_get('writer'), proposal_id) delivered = client.send_proposal_message(current, 'literal', 'send-one') self.assertEqual(delivered.document['messages']['items'][0]['text'], 'literal') - page = client.list_proposal_messages(delivered, limit=2) + page = client.list_proposal_messages(delivered, cursor='7', limit=2) + self.assertEqual(requests[-1][1], f'/tenant{thread_path}?accessProfile=writer&limit=2&cursor=7') self.assertEqual(page['value']['items'][0]['id'], message_id) client.mark_proposal_messages_read(delivered, message_id) self.assertEqual(json.loads(requests[-1][3]), {'through': message_id}) diff --git a/crates/registry-breg-client-py/tests/python/test_asks.py b/crates/registry-breg-client-py/tests/python/test_asks.py index 7352362cf8..9c409268dc 100644 --- a/crates/registry-breg-client-py/tests/python/test_asks.py +++ b/crates/registry-breg-client-py/tests/python/test_asks.py @@ -17,7 +17,7 @@ def test_answer_uses_the_promoted_ask_etag_and_caller_key(self): metadata = {'id': 'asks', 'version': '1', 'revision': digest, 'metadataVersion': '2', 'recordTypes': [], 'operations': [], 'actions': [], 'proposals': {'actions': [{'actionId': 'correct', 'accessProfile': 'author', 'operations': ['get', 'answer'], 'readableInputs': [], 'readableContextFields': []}], 'get': {'method': 'GET', 'path': '/v1/proposals/{proposal_id}', 'accessProfiles': ['author']}}} - document = {'id': proposal, 'actionId': 'correct', 'actionRevision': digest, 'submissionVersion': 1, 'revision': 2, 'state': 'submitted', 'effectDigest': digest, 'links': {}, + document = {'id': proposal, 'actionId': 'correct', 'actionRevision': digest, 'submissionVersion': 1, 'revision': 2, 'state': 'submitted', 'turn': 'official', 'effectDigest': digest, 'links': {}, 'asks': [{'id': ask, 'text': 'Why?', 'wants': [{'kind': 'answer'}], 'askedAt': '2026-11-27T00:00:00Z', 'state': 'open', 'links': { 'answer': {'method': 'POST', 'path': f'/v1/proposals/{proposal}/asks/{ask}/answer', 'accessProfile': 'author', 'operation': 'answer', 'ifMatch': '"condition"', 'availability': {'available': True, 'observedRevision': 2}}}}]} requests = [] diff --git a/crates/registry-breg-client-py/tests/python/test_attachments.py b/crates/registry-breg-client-py/tests/python/test_attachments.py index cfe00e80e5..63921650cb 100644 --- a/crates/registry-breg-client-py/tests/python/test_attachments.py +++ b/crates/registry-breg-client-py/tests/python/test_attachments.py @@ -29,7 +29,7 @@ def respond(self): else:value['attachments'][SLOT].pop('value',None) if owner.mutate_receipt:owner.mutate_receipt(value) payload=CONTENT if binary else json.dumps(value).encode() - self.send_response(200);self.send_header('content-type','application/pdf' if binary else 'application/json');self.send_header('cache-control','no-store');self.send_header('vary','authorization' if binary else 'authorization, accept');self.send_header('traceparent','00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01');self.send_header('content-length',str(len(payload))) + self.send_response(201 if self.command=='POST' and self.path.startswith('/v1/actions/') else 200);self.send_header('content-type','application/pdf' if binary else 'application/json');self.send_header('cache-control','no-store');self.send_header('vary','authorization' if binary else 'authorization, accept');self.send_header('traceparent','00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01');self.send_header('content-length',str(len(payload))) if binary:self.send_header('content-disposition','attachment');self.send_header('x-content-type-options','nosniff') self.end_headers();self.wfile.write(payload) do_GET=respond diff --git a/crates/registry-breg-client-py/tests/python/test_errors.py b/crates/registry-breg-client-py/tests/python/test_errors.py index 3a907f9ba2..3f6e9cdda4 100644 --- a/crates/registry-breg-client-py/tests/python/test_errors.py +++ b/crates/registry-breg-client-py/tests/python/test_errors.py @@ -134,7 +134,8 @@ def test_unknown_problem_codes_fall_back_to_http_status_semantics(self) -> None: self.assertEqual(error.kind, "problem") self.assertEqual(error.status, status) self.assertEqual(error.trace_id, TRACE_ID) - self.assertIsNone(error.code) + self.assertEqual(error.code, "future.refused") + self.assertEqual(error.problem_type, "https://id.registrystack.org/problems/registry-breg/future/refused") self.assertFalse(hasattr(error, "plan_refusal")) self.assertIsNone(error.refusal_code) self.assertIsNone(error.reason_code) 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..89a3f92b5d 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,11 +1,13 @@ """Exercise the durable ingestion-run surface through the Python binding.""" +import base64 import hashlib import json import re import threading import unittest from http.server import BaseHTTPRequestHandler, HTTPServer +from pathlib import Path from urllib.parse import parse_qsl, urlsplit from bootstrap import ensure_built @@ -92,9 +94,22 @@ def receipt_wire() -> dict: } +RECEIPT_BYTES = ( + Path(__file__).resolve().parents[3] + / "registry-breg-client/tests/fixtures/ordinary-ingestion-receipt.json" +).read_bytes() +MALFORMED_RECEIPTS = { + "duplicate": RECEIPT_BYTES.replace(b'"marker": 1', b'"marker": 1, "marker": 2'), + "missing": RECEIPT_BYTES.replace(b'"erased": false,', b""), + "mistyped": RECEIPT_BYTES.replace(b'"replayed": true', b'"replayed": "true"'), +} + + class IngestionRunTests(unittest.TestCase): def setUp(self) -> None: self.requests = [] + self.access_reasons = [] + access_reasons = self.access_reasons requests = self.requests class Handler(BaseHTTPRequestHandler): @@ -102,7 +117,8 @@ def do_GET(self) -> None: # noqa: N802 self.record(b"") path = self.path.split("?")[0] if "/chunks/0/receipt" in path: - self.answer(200, {"receipt": receipt_wire()}) + profile = dict(parse_qsl(urlsplit(self.path).query)).get("accessProfile") + self.answer_bytes(200, MALFORMED_RECEIPTS.get(profile, RECEIPT_BYTES)) elif re.search(r"/ingestion-runs/[0-9a-f-]+$", path): self.answer(200, {"run": run_wire(status="cancelled")}) elif "/chunks/1/receipt" in path: @@ -150,12 +166,15 @@ 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) ) def answer(self, status: int, document: dict) -> None: - body = json.dumps(document, separators=(",", ":")).encode() + self.answer_bytes(status, json.dumps(document, separators=(",", ":")).encode()) + + def answer_bytes(self, status: int, body: bytes) -> None: self.send_response(status) self.send_header("content-type", "application/json") self.send_header("traceparent", TRACEPARENT) @@ -373,7 +392,10 @@ def test_submit_ingestion_chunk_returns_run_and_receipt(self) -> None: def test_chunk_receipt_reads_one_retained_and_reports_one_erased(self) -> None: retained = self.client.ingestion_chunk_receipt("people", RUN_ID, 0, "importer.v1") - self.assertIs(retained["value"]["replayed"], False) + expected = dict(receipt_wire(), replayed=True) + expected["batch"]["results"][0]["futureItem"] = True + self.assertEqual(retained["value"], expected) + self.assertIs(retained["value"]["replayed"], True) self.assertEqual(len(retained["value"]["batch"]["results"]), 1) self.assertTrue( self.requests[-1][1].endswith( @@ -386,6 +408,50 @@ def test_chunk_receipt_reads_one_retained_and_reports_one_erased(self) -> None: self.assertEqual(raised.exception.kind, "problem") self.assertEqual(raised.exception.code, "ingestion.receipt-erased") self.assertEqual(raised.exception.status, 410) + for profile in MALFORMED_RECEIPTS: + with self.subTest(profile=profile): + with self.assertRaises(BaseRegistryClientError) as malformed: + self.client.ingestion_chunk_receipt("people", RUN_ID, 0, profile) + self.assertEqual(malformed.exception.kind, "protocol") + self.assertEqual(len(self.requests), 5) + + 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__": 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..585d54f7f9 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 @@ -375,6 +375,7 @@ def do_POST(self) -> None: # noqa: N802 self.respond( { "snapshot": SNAPSHOT, + "futureBatch": True, "results": [ { "operation": json.loads(body)["items"][0]["operation"], @@ -382,6 +383,7 @@ def do_POST(self) -> None: # noqa: N802 "revisionIdentifier": "1", "etag": ETAG, "domainData": {"legalName": "Batch Ltd"}, + "futureItem": None, } ], }, @@ -691,6 +693,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", @@ -699,6 +702,7 @@ def test_tombstone_and_batch_use_exact_conditions_and_context(self) -> None: }, ) self.assertEqual(receipt["value"]["snapshot"], SNAPSHOT) + self.assertNotIn("futureBatch", receipt["value"]) self.assertEqual( receipt["value"]["results"][0], { @@ -712,6 +716,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 +736,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-py/tests/python/test_proposal_input_boundary.py b/crates/registry-breg-client-py/tests/python/test_proposal_input_boundary.py index 9b5ba8a13c..f4df4b0ad2 100644 --- a/crates/registry-breg-client-py/tests/python/test_proposal_input_boundary.py +++ b/crates/registry-breg-client-py/tests/python/test_proposal_input_boundary.py @@ -67,7 +67,8 @@ def log_message(self, *args): ('rebase', 'draft'), ('rebase', 'submitted')]: with self.subTest(operation=operation, state=state): document = {'id': ID, 'actionId': 'correct', 'actionRevision': REVISION, - 'submissionVersion': 1, 'revision': 2, 'state': state, 'links': { + 'submissionVersion': 1, 'revision': 2, 'state': state, + 'turn': 'party' if state == 'draft' else 'official', 'links': { 'self': {'method': 'GET', 'path': f'/v1/proposals/{ID}', 'accessProfile': 'writer', 'operation': 'get'}, operation: {'method': 'POST', 'path': f'/v1/proposals/{ID}/{operation}', @@ -92,7 +93,7 @@ def log_message(self, *args): with self.assertRaises(BaseRegistryClientError): BRegPreparedProposal.from_bytes(json.dumps(invalid).encode()) self.assertEqual(len(requests), before) - document.update(state='draft', revision=3, submissionVersion=2 if state == 'submitted' else 1) + document.update(state='draft', turn='party', revision=3, submissionVersion=2 if state == 'submitted' else 1) document.pop('effectDigest', None) client.execute_proposal(recovered) self.assertEqual(len(requests), before + 1) diff --git a/crates/registry-breg-client-py/tests/python/test_proposal_response_tolerance.py b/crates/registry-breg-client-py/tests/python/test_proposal_response_tolerance.py new file mode 100644 index 0000000000..303a43f2f1 --- /dev/null +++ b/crates/registry-breg-client-py/tests/python/test_proposal_response_tolerance.py @@ -0,0 +1,245 @@ +"""Shared raw response fixtures through public Proposal Get.""" +import json +import threading +import unittest +from http.server import BaseHTTPRequestHandler, HTTPServer +from pathlib import Path + +from bootstrap import ensure_built + +ensure_built() + +from registry_breg_client import BaseRegistryClient, BaseRegistryClientError + +FIXTURES = json.loads( + (Path(__file__).resolve().parents[3] + / 'registry-breg-client/tests/fixtures/proposal-response-tolerance.json').read_text() +) + + +class ProposalResponseToleranceTests(unittest.TestCase): + def test_proposal_get_decodes_shared_raw_responses(self): + class Handler(BaseHTTPRequestHandler): + def do_GET(self): + nonlocal promoted + metadata = '/v1/registry' in self.path + status = 200 if metadata else fixture['status'] + if metadata: + body = json.dumps(FIXTURES['metadata']) + elif fixture.get('route') == 'promoted' and not promoted: + promoted = True + body = FIXTURES['heldProposal'] + elif fixture.get('route') == 'page' and '/messages?' not in self.path: + status, body = 200, FIXTURES['heldProposal'] + elif fixture.get('route') == 'mark' and self.command == 'GET': + status, body = 200, FIXTURES['heldProposal'] + elif (fixture.get('route') in ('promotedContext', 'promotedStatus') + and self.path.split('?')[0].endswith(FIXTURES['id'])): + body = FIXTURES['heldProposal'] + elif fixture.get('route') in ('send', 'reviewMark') and self.command == 'GET': + status, body = 200, FIXTURES['heldReview'] + else: + body = fixture['body'] + self.send_response(status) + fault = fixture.get('headerFault') if status == 204 else None + if status != 204 or fault == 'media': + self.send_header('content-type', 'application/json' if status < 300 else 'application/problem+json') + trace = '00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01' + self.send_header('traceparent', 'invalid' if fault == 'trace' else trace) + if fault != 'cache': + self.send_header('cache-control', 'no-store') + if fault == 'framing': + self.send_header('content-length', '1') + self.send_header('vary', 'authorization, accept') + self.end_headers() + self.wfile.write(body.encode()) + + def do_POST(self): + self.rfile.read(int(self.headers['content-length'])) + self.do_GET() + + def log_message(self, *_args): + return + + with HTTPServer(('127.0.0.1', 0), Handler) as server: + thread = threading.Thread(target=server.serve_forever) + thread.start() + try: + client = BaseRegistryClient(f'http://127.0.0.1:{server.server_port}/') + contract = client.registry_contract('reader') + get = contract.select_proposal_get('reader') + review = contract.select_proposal_review_context('reader', 'correct') + + def exercise(): + if fixture.get('route') == 'list': + return client.list_proposals(contract.select_proposals('reader'), {}).items[0].document + if fixture.get('route') == 'promoted': + held = client.get_proposal(get, FIXTURES['id']) + return client.read_proposal(held).document + if fixture.get('route') == 'page': + held = client.get_proposal(get, FIXTURES['id']) + return client.list_proposal_messages(held, limit=2)['value'] + if fixture.get('route') == 'batch': + return client.read_proposal_review_context_batch(review, [FIXTURES['id']])['value'] + if fixture.get('route') == 'mark': + held = client.get_proposal(get, FIXTURES['id']) + return client.mark_proposal_messages_read(held, '00000000-0000-4000-8000-000000000002') + if fixture.get('route') in ('promotedContext', 'promotedStatus'): + held = client.get_proposal(get, FIXTURES['id']) + if fixture['route'] == 'promotedContext': + return client.read_proposal_review_context(held)['value'] + return client.read_proposal_review_status(held)['value'] + if fixture.get('route') == 'status': + status = contract.select_proposal_review_status('reader', 'correct') + return client.read_proposal_review_by_id(status, FIXTURES['id'])['value'] + if fixture.get('route') == 'context': + return client.read_proposal_review_by_id(review, FIXTURES['id'])['value'] + if fixture.get('route') == 'reviewMark': + held = client.read_proposal_review_by_id(review, FIXTURES['id'])['value'] + return client.mark_proposal_messages_read_from_review( + review, held, '00000000-0000-4000-8000-000000000002', + ) + if fixture.get('route') == 'send': + held = client.read_proposal_review_by_id(review, FIXTURES['id'])['value'] + return client.send_proposal_message_from_review( + review, held, 'Synthetic reply', 'response-fixture', + )['value'] + return client.get_proposal(get, FIXTURES['id']).document + + for fixture in FIXTURES['cases']: + promoted = False + with self.subTest(case=fixture['name']): + if fixture['name'] == 'additive': + document = exercise() + self.assertNotIn('futureMember', document) + self.assertNotIn('future-relation', document['links']) + self.assertNotIn('futureMember', document['links']['self']) + entry = document['additionalForms']['extra']['items'][0] + self.assertEqual(entry['input']['futureMember'], 'Declared input') + self.assertNotIn('futureMember', entry) + self.assertNotIn('futureMember', document['messages']['items'][0]) + continue + if fixture.get('accept') and fixture['status'] == 204: + outcome = exercise() + if fixture.get('route') == 'mark': + self.assertIsNone(outcome) + else: + self.assertEqual(outcome['kind'], 'complete') + self.assertIsNone(outcome['value']) + self.assertEqual(outcome['trace_id'], '4bf92f3577b34da6a3ce929d0e0e4736') + continue + if fixture.get('accept') and fixture['status'] == 200: + document = exercise() + if fixture.get('route') != 'mark' and fixture['name'].endswith('CurrentTurn'): + self.assertEqual(document['turn'], 'official') + self.assertNotIn('futureMember', document) + if fixture['name'].endswith('KeepsForms'): + self.assertEqual(document['context']['additionalForms'], {'extra': 'extra'}) + if fixture['name'].startswith('batchReader'): + summary = document[0]['context']['messages'] + self.assertEqual(summary['unread'], 1) + expected = {'batchReaderOfficial': 'official', 'batchReaderParty': 'party'} + if fixture['name'] in expected: + self.assertEqual(summary['readerSide'], expected[fixture['name']]) + else: + self.assertNotIn('readerSide', summary) + if fixture['name'] == 'validCitedForm': + entry = document['context']['asks'][0]['answer']['formEntries'][0] + self.assertEqual(entry['input']['futureMember'], 'Declared input') + self.assertNotIn('futureMember', entry) + if fixture['name'].endswith('Forms8'): + review_document = document[0] if fixture.get('route') == 'batch' else document + forms = review_document['context']['additionalForms'] + self.assertEqual(len(forms), 8) + self.assertEqual(forms['form-8'], 'form-8') + if fixture.get('route') == 'reviewMark': + member = { + 'reviewMarkReviewReply': 'context', + 'reviewMarkProposalReply': 'state', + 'reviewMarkThreadReply': 'count', + }[fixture['name']] + self.assertIn(member, document['value']) + if fixture['name'] in ('threadUnavailablePair', 'pageThreadUnavailablePair'): + self.assertEqual(document['links']['message']['availability'], { + 'available': False, 'observedRevision': 3, + 'reason': 'limit-reached', 'recovery': 'receipt-only', + }) + if fixture['name'] == 'reviewReplyWithBrokenOuterThread': + self.assertIn('messages', document['context']) + self.assertNotIn('count', document) + if fixture['name'] == 'reviewSendIdOnlyPolicy': + self.assertEqual(document['policy'], {'id': 'case-review'}) + if fixture['name'] == 'reviewSendPinnedPolicy': + self.assertEqual(document['policy'], json.loads(fixture['body'])['policy']) + if fixture['name'] == 'proposalReplyWithUnusedCounts': + self.assertEqual(document['state'], 'submitted') + self.assertNotIn('count', document) + self.assertNotIn('unread', document) + if fixture['name'] == 'proposalReplyWithUnusedContext': + self.assertNotIn('context', document) + if fixture['name'] == 'threadReplyWithUnusedAction': + self.assertNotIn('actionId', document) + if fixture['name'] == 'reviewReplyWithUnusedState': + self.assertNotIn('state', document) + if fixture['name'] == 'emptyPageLinks': + self.assertEqual(document['links'], {}) + continue + with self.assertRaises(BaseRegistryClientError) as raised: + exercise() + error = raised.exception + if fixture['name'].startswith('threadProblem'): + problem = json.loads(fixture['body']) + accepted = fixture.get('accept', False) + self.assertEqual(error.status, 400) + self.assertEqual(error.trace_id, problem['traceId']) + self.assertEqual(error.kind, 'problem' if accepted else 'protocol') + self.assertEqual(error.code, problem['code'] if accepted else 'problem') + self.assertEqual(error.field_path, problem['fieldPath'] if accepted else None) + elif fixture['name'].startswith(('unknown', 'futureSuffix')): + problem = json.loads(fixture['body']) + self.assertEqual(error.kind, 'problem') + self.assertEqual(error.status, fixture['status']) + self.assertEqual(error.code, problem['code']) + self.assertEqual(error.problem_type, problem['type']) + self.assertEqual(error.trace_id, '4bf92f3577b34da6a3ce929d0e0e4736') + self.assertEqual(error.outcome_unknown, fixture['status'] >= 500) + self.assertNotIn(problem['code'], f'{error!s} {error!r}') + self.assertNotRegex(f'{error!s} {error!r}', r'future\.refused|https://|Synthetic|Reworded') + elif fixture['name'] == 'legacyPlanRefusal': + self.assertEqual(error.kind, 'problem') + self.assertEqual(error.status, 400) + self.assertIsNone(error.code) + self.assertIsNone(getattr(error, 'problem_type', None)) + self.assertFalse(error.outcome_unknown) + elif fixture['name'] == 'rewordedKnown': + self.assertEqual(error.kind, 'not-found') + self.assertEqual(error.status, 404) + self.assertEqual(error.code, 'resource.not-found') + elif fixture['status'] == 204: + self.assertEqual(error.kind, 'protocol') + self.assertEqual(error.code, fixture['failure']) + self.assertEqual(error.status, 204) + self.assertEqual( + error.trace_id, + None if fixture.get('headerFault') == 'trace' else '4bf92f3577b34da6a3ce929d0e0e4736', + ) + elif fixture['status'] == 201: + self.assertEqual(error.kind, 'protocol') + self.assertEqual(error.code, 'status') + self.assertEqual(error.status, 201) + self.assertEqual(error.trace_id, '4bf92f3577b34da6a3ce929d0e0e4736') + elif fixture.get('route') in ('context', 'batch', 'promotedContext', 'status', 'promotedStatus'): + self.assertEqual(error.kind, 'invalid-request') + self.assertFalse(error.outcome_unknown) + elif fixture['status'] != 200: + self.assertEqual(error.kind, 'protocol') + self.assertEqual(error.code, 'problem') + else: + self.assertEqual(error.kind, 'protocol') + self.assertEqual(error.code, 'body') + self.assertEqual(error.status, 200) + self.assertEqual(error.trace_id, '4bf92f3577b34da6a3ce929d0e0e4736') + self.assertTrue(error.outcome_unknown) + finally: + server.shutdown() + thread.join() diff --git a/crates/registry-breg-client-py/tests/python/test_proposal_results.py b/crates/registry-breg-client-py/tests/python/test_proposal_results.py index e949d4b00c..9a3ce1cf17 100644 --- a/crates/registry-breg-client-py/tests/python/test_proposal_results.py +++ b/crates/registry-breg-client-py/tests/python/test_proposal_results.py @@ -120,7 +120,12 @@ def respond(self): self.end_headers() self.wfile.write(owner.download_bytes) return - payload = json.dumps(owner.metadata if self.path.startswith('/tenant/v1/registry') else owner.value).encode() + served = owner.value + if self.command == 'GET' and self.path.split('?')[0] == f'/tenant/v1/proposals/{ID}': + turn = {'draft': 'party', 'submitted': 'official', 'applied': 'nobody', 'rejected': 'nobody', 'cancelled': 'nobody'}.get(served.get('state')) + if turn and 'turn' not in served: + served = dict(served, turn=turn) + payload = json.dumps(owner.metadata if self.path.startswith('/tenant/v1/registry') else served).encode() self.send_response(owner.reply_status) for key, value in [('content-type', owner.content_type), ('cache-control', 'no-store'), ('vary', 'authorization, accept'), ('traceparent', '00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01'), ('content-length', str(len(payload)))]: @@ -175,7 +180,7 @@ def test_application_identity_is_canonical_and_preserves_exact_receipt_recovery( self.value['application']['applicationId'] = application_id with self.subTest(application_id=application_id), self.assertRaises(BaseRegistryClientError) as raised: self.client.get_proposal(self.binding, ID) - self.assertEqual(raised.exception.kind, 'invalid-request') + self.assertEqual(raised.exception.kind, 'protocol') with self.assertRaises(BaseRegistryClientError) as raised: self.client.execute_proposal(attempt) self.assertEqual(raised.exception.kind, 'protocol') @@ -207,7 +212,7 @@ def test_attachment_availability_requires_complete_unavailable_details(self): self.value['attachments']['support']['links']['upload']['availability'] = availability with self.subTest(missing=missing), self.assertRaises(BaseRegistryClientError) as raised: self.client.get_proposal(self.binding, ID) - self.assertEqual(raised.exception.kind, 'invalid-request') + self.assertEqual(raised.exception.kind, 'protocol') self.value['revision'] = availability['observedRevision'] = 9 with self.assertRaises(BaseRegistryClientError) as raised: self.client.execute_proposal(attempt) @@ -232,7 +237,7 @@ def test_application_result_record_identifiers_retain_canonical_spelling(self): count = len(self.requests) with self.subTest(record_id=record_id), self.assertRaises(BaseRegistryClientError) as raised: self.client.get_proposal(self.binding, ID) - self.assertEqual(raised.exception.kind, 'invalid-request') + self.assertEqual(raised.exception.kind, 'protocol') self.assertEqual(len(self.requests), count + 1) def test_application_status_preserves_current_progress_and_retained_evidence_absence(self): @@ -276,9 +281,7 @@ def test_package_change_exposes_only_the_rebase_recovery_vocabulary(self): def test_malformed_and_widened_receipts_are_refused(self): for path, value in [(('submissionVersion',), 1), (('effectDigest',), 'sha256:UPPERCASE'), - (('resultLinks', 0, 'revision'), 0), (('resultLinks', 0, 'recordId'), 'not-a-uuid'), - (('actorReference',), 'private-canary'), (('reason',), 'private-canary'), - (('resultLinks', 0, 'href'), 'https://elsewhere.invalid/private')]: + (('resultLinks', 0, 'revision'), 0), (('resultLinks', 0, 'recordId'), 'not-a-uuid')]: self.value = document() target = self.value['application'] for member in path[:-1]: @@ -287,6 +290,13 @@ def test_malformed_and_widened_receipts_are_refused(self): with self.subTest(path=path), self.assertRaises(BaseRegistryClientError): self.client.get_proposal(self.binding, ID) + def test_unknown_application_members_are_projected_out(self): + self.value = document() + self.value['application'].update(actorReference='private-canary', reason='private-canary') + self.value['application']['resultLinks'][0]['href'] = 'https://elsewhere.invalid/private' + response = self.client.get_proposal(self.binding, ID).document + self.assertEqual(response['application'], document()['application']) + def test_exact_input_and_prepared_edit_recovery(self): self.value = document() self.value.update(state='draft', input={'wide': 9007199254740993, 'decimal': '12.3400', 'nullable': None}) @@ -410,7 +420,7 @@ def test_documents_require_version_and_state_appropriate_frozen_evidence(self): del self.value['effectDigest'] with self.subTest(state=state), self.assertRaises(BaseRegistryClientError) as raised: self.client.get_proposal(self.binding, ID) - self.assertEqual(raised.exception.kind, 'invalid-request') + self.assertEqual(raised.exception.kind, 'protocol') self.value = document() self.value['state'] = 'submitted' del self.value['application'] @@ -705,7 +715,7 @@ def test_retained_attachment_download_uses_value_size_but_upload_uses_current_po self.value['attachments']['support']['value']['uploadedAt'] = uploaded_at with self.subTest(uploaded_at=uploaded_at), self.assertRaises(BaseRegistryClientError) as raised: self.client.get_proposal(self.binding, ID) - self.assertEqual(raised.exception.kind, 'invalid-request') + self.assertEqual(raised.exception.kind, 'protocol') self.assertNotIn('private-canary', str(raised.exception)) self.value = disclosed retained = self.client.get_proposal(self.binding, ID) diff --git a/crates/registry-breg-client-py/tests/python/test_proposals.py b/crates/registry-breg-client-py/tests/python/test_proposals.py index 6ddce52a2e..221e12f714 100644 --- a/crates/registry-breg-client-py/tests/python/test_proposals.py +++ b/crates/registry-breg-client-py/tests/python/test_proposals.py @@ -20,7 +20,7 @@ } PROPOSAL = { 'id': ID, 'actionId': 'correct', 'actionRevision': REVISION, - 'submissionVersion': 1, 'revision': 2, 'state': 'draft', + 'submissionVersion': 1, 'revision': 2, 'state': 'draft', 'turn': 'party', 'input': {'addressLine': 'Disclosed address'}, 'links': {'self': {'method': 'GET', 'path': '/v1/proposals/' + ID, 'accessProfile': 'reader', 'operation': 'get'}}, @@ -388,7 +388,7 @@ def log_message(self, *args): 'invalid supplied Proposal inputs fail before credential acquisition or I/O', ) for state in ['submitted', 'applied', 'cancelled']: - value = dict(PROPOSAL, state=state, submissionVersion=1) + value = dict(PROPOSAL, state=state, submissionVersion=1, turn='official' if state == 'submitted' else 'nobody') if state == 'submitted': value['effectDigest'] = REVISION self.assertEqual(client.get_proposal(get, ID).document['state'], state) @@ -496,7 +496,7 @@ def answer(self): dict(proposal, revision=3, state='submitted', effectDigest=REVISION) if '/submit?' in self.path else proposal)) payload = json.dumps(value).encode() - self.send_response(200) + self.send_response(201 if self.path.startswith('/v1/actions/') else 200) for key, val in [('content-type', 'application/json'), ('cache-control', 'no-store'), ('traceparent', '00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01'), ('vary', 'authorization, accept'), ('content-length', str(len(payload)))]: @@ -572,7 +572,7 @@ def respond(self): value['revision'] += 1 value['attachments'][slot].pop('value', None) payload = json.dumps(value).encode() - self.send_response(200) + self.send_response(201 if self.path.startswith('/v1/actions/') else 200) for key, val in [('content-type', 'application/json'), ('cache-control', 'no-store'), ('vary', 'authorization, accept'), ('content-length', str(len(payload))), ('traceparent', '00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01')]: diff --git a/crates/registry-breg-client/README.md b/crates/registry-breg-client/README.md index d87a8803ab..ec0cbe7354 100644 --- a/crates/registry-breg-client/README.md +++ b/crates/registry-breg-client/README.md @@ -325,18 +325,21 @@ Unknown object members are ignored after duplicate rejection; recognized extensions on known codes retain their existing validation. -A valid unrecognized Problem code returns `UnrecognizedProblem` with only its -HTTP status and trace identifier. Node.js and Python expose kind `problem` with -no code or typed extensions, including for an unknown `404`. Known -`resource.not-found` still exposes `not-found`. Unknown `4xx` outcomes are known -refusals; unknown `5xx` outcomes may have committed and use the existing bounded -same-key retry rules. Malformed envelopes and mismatched status, trace, or BReg -type/code URI still fail as protocol errors. Malformed known codes cannot fall -back to unknown-code handling. +An unfamiliar Problem with a valid code and type returns `UnrecognizedProblem`. +Rust exposes the identifiers through `problem_code_str()` and `problem_type()`. +Node.js exposes `code` and `problemType`, and Python exposes `code` and +`problem_type`. The client retains the actual HTTP status and correlated trace +and omits the unfamiliar identifiers from default error formatting. It uses +kind `problem` for unfamiliar codes, including on an HTTP 404. Registered +`resource.not-found` uses kind `not-found`. An unfamiliar 4xx indicates refusal. +An unfamiliar 5xx can leave the outcome unknown and follows the bounded same-key +retry rules. Malformed envelopes and mismatched status, trace, or BReg type and +code pairs fail as protocol errors. The historical `request.plan_refused` +response keeps its status and trace fallback. Errors retain fixed local reasons, public status or problem codes, validated trace identifiers, bounded problem locations, and bounded retry guidance. They -do not retain credentials, selectors, response bodies, header values, URLs, or +do not retain credentials, selectors, response bodies, header values, request URLs, or transport error chains. ### Explicit recovery across process restarts diff --git a/crates/registry-breg-client/src/actions.rs b/crates/registry-breg-client/src/actions.rs index 4b3d91b690..e3b1304f96 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()); } @@ -686,8 +687,8 @@ impl BaseRegistryClient { Some(raw.metadata.trace_id().clone()), ) }; - let proposal = - crate::BRegProposal::from_slice(raw.value.as_bytes()).map_err(|_| invalid_receipt())?; + let proposal = crate::BRegProposal::from_response(raw.value.as_bytes()) + .map_err(|_| invalid_receipt())?; if proposal.action_id() != action.action_identifier() || proposal.action_revision() != action.definition_revision() || proposal.state() != crate::BRegProposalState::Draft @@ -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..151c5d37a6 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(|_| { @@ -450,11 +463,9 @@ fn decode_receipt( let value = crate::strict_json::from_slice(bytes).map_err(|_| BRegBatchError::InvalidResponse)?; let object = value.as_object().ok_or(BRegBatchError::InvalidResponse)?; - if object.len() != 2 || !object.contains_key("snapshot") || !object.contains_key("results") { - return Err(BRegBatchError::InvalidResponse); - } - let snapshot = object["snapshot"] - .as_str() + let snapshot = object + .get("snapshot") + .and_then(Value::as_str) .filter(|value| { value .strip_prefix("breg1_") @@ -468,8 +479,9 @@ fn decode_receipt( }) .ok_or(BRegBatchError::InvalidResponse)? .to_owned(); - let results = object["results"] - .as_array() + let results = object + .get("results") + .and_then(Value::as_array) .filter(|items| items.len() == request.item_operations.len()) .ok_or(BRegBatchError::InvalidResponse)? .iter() @@ -485,20 +497,7 @@ fn decode_result( readable: &BTreeSet, ) -> Result { let object = value.as_object().ok_or(BRegBatchError::InvalidResponse)?; - if object.len() != 5 - || ![ - "operation", - "recordId", - "revisionIdentifier", - "etag", - "domainData", - ] - .iter() - .all(|key| object.contains_key(*key)) - { - return Err(BRegBatchError::InvalidResponse); - } - let operation = match object["operation"].as_str() { + let operation = match object.get("operation").and_then(Value::as_str) { Some("create") => BRegBatchOperation::Create, Some("patch") => BRegBatchOperation::Patch, _ => return Err(BRegBatchError::InvalidResponse), @@ -506,28 +505,32 @@ fn decode_result( if operation != expected { return Err(BRegBatchError::InvalidResponse); } - let record_id = object["recordId"] - .as_str() + let record_id = object + .get("recordId") + .and_then(Value::as_str) .and_then(|value| { Uuid::parse_str(value) .ok() .filter(|id| id.to_string() == value) }) .ok_or(BRegBatchError::InvalidResponse)?; - let revision_identifier = object["revisionIdentifier"] - .as_str() + let revision_identifier = object + .get("revisionIdentifier") + .and_then(Value::as_str) .filter(|value| { value.parse::().is_ok_and(|revision| { revision > 0 && revision <= i64::MAX as u64 && revision.to_string() == *value }) }) .ok_or(BRegBatchError::InvalidResponse)?; - let etag = object["etag"] - .as_str() + let etag = object + .get("etag") + .and_then(Value::as_str) .and_then(|value| BRegEtag::parse(value).ok()) .ok_or(BRegBatchError::InvalidResponse)?; - let domain_data = object["domainData"] - .as_object() + let domain_data = object + .get("domainData") + .and_then(Value::as_object) .filter(|data| data.keys().all(|field| readable.contains(field))) .cloned() .ok_or(BRegBatchError::InvalidResponse)?; diff --git a/crates/registry-breg-client/src/client.rs b/crates/registry-breg-client/src/client.rs index d2479c5d4d..898c0acd23 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,50 @@ const MAXIMUM_ENGINE_VERSION_BYTES: usize = 64; const X_CONTENT_TYPE_OPTIONS: reqwest::header::HeaderName = reqwest::header::HeaderName::from_static("x-content-type-options"); +#[derive(Clone, Copy, PartialEq, Eq)] +pub(crate) enum ProblemContext { + Default, + ProposalThreadList, +} + +/// 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 +1376,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 +1405,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) @@ -1412,7 +1478,9 @@ impl BaseRegistryClient { self.send_keyed( builder.header("idempotency-key", key.as_str()), move |response| async move { - let wire = self.proposal_wire(response).await?; + let wire = self + .proposal_wire(response, StatusCode::OK, ProblemContext::Default) + .await?; Ok(BRegComplete { value: BRegRawDocument::new(wire.media_type, wire.body), metadata: wire.metadata, @@ -1437,16 +1505,59 @@ impl BaseRegistryClient { if let Some(key) = key { self.send_keyed( builder.header("idempotency-key", key.as_str()), - |response| self.decode_proposal_response(response), + |response| self.decode_proposal_response(response, StatusCode::OK), ) .await } else { let builder = self.authorize(builder, Credential::Optional).await?; - self.decode_proposal_response(self.transport.send(builder).await?) + self.decode_proposal_response(self.transport.send(builder).await?, StatusCode::OK) .await } } + pub(crate) async fn proposal_mark_read_exchange( + &self, + link: &BRegProposalLink, + body: Vec, + ) -> Result>, BaseRegistryClientError> { + let builder = self.proposal_request(link, Some(body))?; + let builder = self.authorize(builder, Credential::Optional).await?; + let response = self.transport.send(builder).await?; + let status = response.status(); + if status != StatusCode::NO_CONTENT { + let complete = self + .decode_proposal_response(response, StatusCode::OK) + .await?; + return Ok(BRegComplete { + value: Some(complete.value), + metadata: complete.metadata, + }); + } + + let headers = response.headers(); + let trace_id = breg_trace_id(status, headers)?; + validate_no_store(status, headers, &trace_id)?; + if headers.contains_key(CONTENT_TYPE) { + return Err(BaseRegistryClientError::protocol( + status.as_u16(), + BRegProtocolFailure::MediaType, + Some(trace_id), + )); + } + // HTTP stacks may discard an illegal 204 payload. Check its framing + // before asking the transport to verify the bounded empty body. + if headers.contains_key(reqwest::header::CONTENT_LENGTH) + || headers.contains_key(reqwest::header::TRANSFER_ENCODING) + || !self.transport.read(response, 1).await?.is_empty() + { + return Err(body_failure(status.as_u16(), trace_id)); + } + Ok(BRegComplete { + value: None, + metadata: BRegResponseMetadata::new(trace_id, None), + }) + } + pub(crate) async fn proposal_review_progress_exchange( &self, link: &BRegProposalLink, @@ -1492,7 +1603,7 @@ impl BaseRegistryClient { Credential::Optional, ) .await?; - self.decode_proposal_response(self.transport.send(builder).await?) + self.decode_proposal_response(self.transport.send(builder).await?, StatusCode::OK) .await } @@ -1528,10 +1639,11 @@ impl BaseRegistryClient { async fn decode_proposal_response( &self, response: Response, + expected_status: StatusCode, ) -> Result, BaseRegistryClientError> { - let wire = self.proposal_wire(response).await?; - crate::strict_json::from_slice(&wire.body) - .map_err(|_| body_failure(wire.status, wire.metadata.trace_id().clone()))?; + let wire = self + .proposal_wire(response, expected_status, ProblemContext::Default) + .await?; Ok(BRegComplete { value: BRegRawDocument::new(wire.media_type, wire.body), metadata: wire.metadata, @@ -1542,6 +1654,7 @@ impl BaseRegistryClient { &self, path: &str, pairs: &[(String, String)], + problem_context: ProblemContext, ) -> Result, BaseRegistryClientError> { let segments = fixed_operation_segments(path)?; let url = self.url_with_query(&segments, pairs)?; @@ -1555,7 +1668,11 @@ impl BaseRegistryClient { ) .await?; let wire = self - .proposal_wire(self.transport.send(builder).await?) + .proposal_wire( + self.transport.send(builder).await?, + StatusCode::OK, + problem_context, + ) .await?; Ok(BRegComplete { value: BRegRawDocument::new(wire.media_type, wire.body), @@ -1582,7 +1699,9 @@ impl BaseRegistryClient { .header("idempotency-key", key.as_str()) .body(body); self.send_keyed(builder, move |response| async move { - let wire = self.proposal_wire(response).await?; + let wire = self + .proposal_wire(response, StatusCode::CREATED, ProblemContext::Default) + .await?; Ok(BRegComplete { value: BRegRawDocument::new(wire.media_type, wire.body), metadata: wire.metadata, @@ -1591,12 +1710,17 @@ impl BaseRegistryClient { .await } - async fn proposal_wire(&self, response: Response) -> Result { + async fn proposal_wire( + &self, + response: Response, + expected_status: StatusCode, + problem_context: ProblemContext, + ) -> Result { let status = response.status(); if !status.is_success() { - return Err(breg_problem(response, &self.transport).await); + return Err(breg_problem_in_context(response, &self.transport, problem_context).await); } - if !matches!(status, StatusCode::OK | StatusCode::CREATED) { + if status != expected_status { return Err(BaseRegistryClientError::protocol( status.as_u16(), BRegProtocolFailure::Status, @@ -1643,15 +1767,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 +1987,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 +1998,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?; @@ -2241,14 +2370,12 @@ struct BRegWire { fn decode_breg_json( wire: BRegWire, ) -> Result, BaseRegistryClientError> { - let status = wire.status; - let value = serde_json::from_slice(&wire.body).map_err(|_| { - BaseRegistryClientError::protocol( - status, - BRegProtocolFailure::Body, - Some(wire.metadata.trace_id().clone()), - ) - })?; + let invalid = || body_failure(wire.status, wire.metadata.trace_id().clone()); + let json = crate::strict_json::from_slice(&wire.body).map_err(|_| invalid())?; + if !json.is_object() { + return Err(invalid()); + } + let value = serde_json::from_value(json).map_err(|_| invalid())?; Ok(BRegComplete { value, metadata: wire.metadata, @@ -2834,6 +2961,14 @@ fn breg_response_location( } async fn breg_problem(response: Response, transport: &Transport) -> BaseRegistryClientError { + breg_problem_in_context(response, transport, ProblemContext::Default).await +} + +async fn breg_problem_in_context( + response: Response, + transport: &Transport, + context: ProblemContext, +) -> BaseRegistryClientError { let status = response.status(); let headers = response.headers().clone(); let trace_id = match breg_trace_id(status, &headers) { @@ -2882,9 +3017,12 @@ async fn breg_problem(response: Response, transport: &Transport) -> BaseRegistry { return problem_failure(status, trace_id); } + let retain_identifiers = document.code != LEGACY_PLAN_REFUSAL_CODE; return BaseRegistryClientError::UnrecognizedProblem { status: status.as_u16(), trace_id, + code: retain_identifiers.then_some(document.code), + problem_type: retain_identifiers.then_some(document.type_uri), }; }; if (extensions.declared_field || extensions.constraint.is_some()) @@ -2892,7 +3030,15 @@ async fn breg_problem(response: Response, transport: &Transport) -> BaseRegistry || extensions .field_path .as_ref() - .is_some_and(|(path, _)| !path.permits(code)) + .is_some_and(|(category, path)| { + let thread_list_location = context == ProblemContext::ProposalThreadList + && matches!( + (code, path.as_str()), + (BRegProblemCode::RequestInvalid, "limit" | "cursor") + | (BRegProblemCode::QueryCursorInvalid, "cursor") + ); + !(category.permits(code) || thread_list_location) + }) || extensions.refusal_code.is_some() != matches!( code, @@ -2939,8 +3085,18 @@ fn valid_problem_text(value: &str, maximum_chars: usize) -> bool { value.chars().count() <= maximum_chars && !value.chars().any(char::is_control) } +const LEGACY_PLAN_REFUSAL_CODE: &str = "request.plan_refused"; + fn valid_unrecognized_problem(document: &ProblemDocument) -> bool { - !document.code.is_empty() + // The historical plan refusal already has generic fallback semantics. + (document.code == LEGACY_PLAN_REFUSAL_CODE + || (document.code.len() <= 128 + && document.code.contains('.') + && document.code.split('.').all(|segment| { + let mut bytes = segment.bytes(); + bytes.next().is_some_and(|byte| byte.is_ascii_lowercase()) + && bytes.all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'-') + }))) // Retired registered codes do not get the unknown problem fallback. && !matches!( document.code.as_str(), @@ -2967,9 +3123,6 @@ fn valid_unrecognized_problem(document: &ProblemDocument) -> bool { | "statistical_dataset.version_withdrawn" | "unsupported.media_type" ) - && valid_problem_text(&document.code, 128) - && valid_problem_text(&document.title, 128) - && valid_problem_text(&document.detail, 256) && valid_problem_text(&document.type_uri, 256) && document.type_uri == format!( @@ -3239,13 +3392,11 @@ fn breg_problem_path(path: &str) -> Option { } /// The fixed query parameters a `query.invalid` refusal may name. -const BREG_QUERY_PARAMETERS: [&str; 26] = [ +const BREG_QUERY_PARAMETERS: [&str; 22] = [ "$select", "$filter", "$orderby", - "$top", "$count", - "$skiptoken", "bbox", "accessProfile", "asOf", @@ -3262,9 +3413,7 @@ const BREG_QUERY_PARAMETERS: [&str; 26] = [ "pendingManualApplication", "target", "cursor", - "top", "inputDigest", - "after", "query", ]; @@ -3409,3 +3558,31 @@ mod ask_field_paths { )); } } + +#[cfg(test)] +mod query_field_paths { + use super::{breg_problem_path, BRegProblemCode, BRegProblemPath}; + + #[test] + fn query_problems_admit_only_current_paging_locations() { + for path in [ + "limit", + "cursor", + "query", + "status", + "inputDigest", + "$select", + ] { + let category = breg_problem_path(path).unwrap_or_else(|| panic!("{path}")); + assert!( + matches!(category, BRegProblemPath::QueryParameter), + "{path}" + ); + assert!(category.permits(BRegProblemCode::QueryInvalid), "{path}"); + assert!(!category.permits(BRegProblemCode::RequestInvalid), "{path}"); + } + for path in ["$top", "$skiptoken", "top", "after", "unknownCanary"] { + assert!(breg_problem_path(path).is_none(), "{path}"); + } + } +} diff --git a/crates/registry-breg-client/src/error.rs b/crates/registry-breg-client/src/error.rs index 9dd819531e..51cfb0b7ee 100644 --- a/crates/registry-breg-client/src/error.rs +++ b/crates/registry-breg-client/src/error.rs @@ -423,11 +423,19 @@ impl BRegProblemCode { "The record attachment slot already holds a file and is write-once." } Self::AttachmentTooLarge => "The file is larger than the attachment slot accepts.", - Self::AttachmentLimitReached => "The supporting document slot has reached its file limit.", + Self::AttachmentLimitReached => { + "The supporting document slot has reached its file limit." + } Self::AttachmentRequired => "The required attachment slot is empty.", - Self::AttachmentVerificationPending => "The attachment is awaiting verification. Refresh the Proposal before submitting.", - Self::AttachmentVerificationRejected => "The attachment was rejected by verification. Replace or remove the file before submitting.", - Self::AuthenticationRefused => "The bearer token or delivery signature was not accepted.", + Self::AttachmentVerificationPending => { + "The attachment is awaiting verification. Refresh the Proposal before submitting." + } + Self::AttachmentVerificationRejected => { + "The attachment was rejected by verification. Replace or remove the file before submitting." + } + Self::AuthenticationRefused => { + "The bearer token or delivery signature was not accepted." + } Self::ExternalViewIncomplete => { "The external view's indexed coverage is incomplete for this request." } @@ -448,12 +456,20 @@ impl BRegProblemCode { "A production registry refuses task assertions issued in development." } Self::PreconditionFailed => "The mutation precondition failed.", - Self::ProposalReviewResultMismatch => "The current review result does not match the retained approval.", - Self::ProposalFormLimitReached => "The submission has reached the entry limit for this form.", + Self::ProposalReviewResultMismatch => { + "The current review result does not match the retained approval." + } + Self::ProposalFormLimitReached => { + "The submission has reached the entry limit for this form." + } Self::ProposalFormUndeclared => "The Action does not declare this additional form.", Self::ProposalMessageLimitReached => "This Proposal's message thread is full.", - Self::ProposalSubjectChanged => "The person this Proposal is about changed since it was first submitted. Cancel it and file a new Proposal.", - Self::ProposalSubjectNotCaller => "This Proposal names someone other than you as the person it is about, and your access profile files only for yourself.", + Self::ProposalSubjectChanged => { + "The person this Proposal is about changed since it was first submitted. Cancel it and file a new Proposal." + } + Self::ProposalSubjectNotCaller => { + "This Proposal names someone other than you as the person it is about, and your access profile files only for yourself." + } Self::PreconditionRequired => "The mutation precondition is required.", Self::ProfileNotAuthorized => "No access profile admits this caller for this request.", Self::ProposalRejected => { @@ -572,7 +588,7 @@ impl std::fmt::Display for BRegProtocolFailure { /// detail codes through `refusal_code` or `reason_code`, and paths through /// `field_path`, and declared row-local constraints through `constraint`; /// none are rendered. -#[derive(Clone, Debug, Error, PartialEq, Eq)] +#[derive(Clone, Error, PartialEq, Eq)] #[non_exhaustive] pub enum BaseRegistryClientError { #[error( @@ -597,12 +613,20 @@ pub enum BaseRegistryClientError { constraint: Option>, refusal_code: Option, }, - /// A valid Problem whose code is newer than this client. Only HTTP status - /// and the validated trace identifier carry semantics; service text and - /// extensions are discarded. - #[error("Base Registry Engine refused or failed the request: status {status}, unrecognized problem code")] - UnrecognizedProblem { status: u16, trace_id: TraceId }, - #[error("the Base Registry Engine response did not satisfy its wire contract: status {status}, {failure}; verify the server URL and use a matching BReg runtime and client before continuing")] + /// A valid Problem whose code is newer than this client. Its identifiers + /// are diagnostics. Recovery uses the actual HTTP status. + #[error( + "Base Registry Engine refused or failed the request: status {status}, unrecognized problem code" + )] + UnrecognizedProblem { + status: u16, + trace_id: TraceId, + code: Option, + problem_type: Option, + }, + #[error( + "the Base Registry Engine response did not satisfy its wire contract: status {status}, {failure}; verify the server URL and use a matching BReg runtime and client before continuing" + )] Protocol { status: u16, failure: BRegProtocolFailure, @@ -615,6 +639,24 @@ pub enum BaseRegistryClientError { }, } +impl std::fmt::Debug for BaseRegistryClientError { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + let mut debug = formatter.debug_struct("BaseRegistryClientError"); + debug + .field("kind", &self.kind()) + .field("status", &self.status()) + .field("message", &format_args!("{self}")); + if let Self::Problem { + refusal_code: Some(code), + .. + } = self + { + debug.field("refusal_code", code); + } + debug.finish_non_exhaustive() + } +} + impl BaseRegistryClientError { pub(crate) const fn configuration(reason: &'static str) -> Self { Self::Configuration { reason } @@ -714,6 +756,26 @@ impl BaseRegistryClientError { } } + /// The registered or validated unrecognized Problem code. + #[must_use] + pub fn problem_code_str(&self) -> Option<&str> { + match self { + Self::Problem { code, .. } => Some(code.code()), + Self::UnrecognizedProblem { code, .. } => code.as_deref(), + _ => None, + } + } + + /// The validated type URI retained for an unfamiliar Problem. + /// Use [`Self::problem_code`] for a registered BReg problem code. + #[must_use] + pub fn problem_type(&self) -> Option<&str> { + match self { + Self::UnrecognizedProblem { problem_type, .. } => problem_type.as_deref(), + _ => None, + } + } + /// The declared reason an immediate action or statistical release was refused. #[must_use] pub fn refusal_code(&self) -> Option<&BRegRefusalCode> { @@ -978,6 +1040,10 @@ mod tests { let error = BaseRegistryClientError::UnrecognizedProblem { status, trace_id: TraceId::parse("0123456789abcdef0123456789abcdef").unwrap(), + code: Some("future.refused".into()), + problem_type: Some( + "https://id.registrystack.org/problems/registry-breg/future/refused".into(), + ), }; assert_eq!(error.kind(), "problem"); assert_eq!(error.status(), Some(status)); 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..d9bd2f74e1 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 @@ -254,14 +255,9 @@ impl BRegIngestionAttempt { let attempt = value .as_object() .ok_or(BRegIngestionError::InvalidResponse)?; - if attempt.len() != 2 - || !attempt.contains_key("outcome") - || !attempt.contains_key("chunkIndex") - { - return Err(BRegIngestionError::InvalidResponse); - } - let outcome = attempt["outcome"] - .as_str() + let outcome = attempt + .get("outcome") + .and_then(Value::as_str) .and_then(BRegIngestionAttemptOutcome::parse) .ok_or(BRegIngestionError::InvalidResponse)?; let chunk_index = match attempt.get("chunkIndex") { @@ -445,9 +441,7 @@ impl BRegIngestionRun { ]; let refuse = BRegIngestionError::InvalidResponse; let object = value.as_object().ok_or(refuse)?; - if object.len() != MEMBERS.len() - || MEMBERS.iter().any(|member| !object.contains_key(*member)) - { + if MEMBERS.iter().any(|member| !object.contains_key(*member)) { return Err(refuse); } let run_id = text_member(object, "runId")?; @@ -596,7 +590,7 @@ impl BRegIngestionRunPage { Some(canonical_run_cursor(cursor).ok_or(refuse)?) } }; - if has_more != next_cursor.is_some() || !object.is_empty() { + if has_more != next_cursor.is_some() { return Err(refuse); } Ok(Self { @@ -652,9 +646,7 @@ impl BRegIngestionChunkReceipt { const MEMBERS: [&str; 5] = ["chunkIndex", "digest", "replayed", "erased", "batch"]; let refuse = BRegIngestionError::InvalidResponse; let object = value.as_object().ok_or(refuse)?; - if object.len() != MEMBERS.len() - || MEMBERS.iter().any(|member| !object.contains_key(*member)) - { + if MEMBERS.iter().any(|member| !object.contains_key(*member)) { return Err(refuse); } let chunk_index = count_member(object, "chunkIndex")?; @@ -704,12 +696,9 @@ impl BRegIngestionReceiptBatch { fn from_value(value: &Value) -> Result { let refuse = BRegIngestionError::InvalidResponse; let object = value.as_object().ok_or(refuse)?; - if object.len() != 2 || !object.contains_key("snapshot") || !object.contains_key("results") - { - return Err(refuse); - } - let snapshot = object["snapshot"] - .as_str() + let snapshot = object + .get("snapshot") + .and_then(Value::as_str) .filter(|value| { value.len() <= MAXIMUM_SNAPSHOT_REFERENCE_BYTES && value @@ -723,7 +712,11 @@ impl BRegIngestionReceiptBatch { }) .ok_or(refuse)? .to_owned(); - let results = object["results"].as_array().ok_or(refuse)?.clone(); + let results = object + .get("results") + .and_then(Value::as_array) + .ok_or(refuse)? + .clone(); Ok(Self { snapshot, results }) } } @@ -750,9 +743,6 @@ impl BRegIngestionChunkSubmission { fn from_members(object: &mut Map) -> Result { let run = BRegIngestionRun::from_value(take_member(object, "run")?)?; let receipt = BRegIngestionChunkReceipt::from_value(take_member(object, "receipt")?)?; - if !object.is_empty() { - return Err(BRegIngestionError::InvalidResponse); - } Ok(Self { run, receipt }) } } @@ -1400,8 +1390,20 @@ fn serialize_uuid(value: &Uuid, serializer: S) -> Result( raw: BRegComplete, expected_status: u16, - members: &[&str], decode: impl FnOnce(&mut Map) -> Result, +) -> Result, BaseRegistryClientError> { + decode_response(raw, expected_status, |value| { + let Value::Object(mut object) = value else { + return Err(BRegIngestionError::InvalidResponse); + }; + decode(&mut object) + }) +} + +fn decode_response( + raw: BRegComplete, + expected_status: u16, + decode: impl FnOnce(Value) -> Result, ) -> Result, BaseRegistryClientError> { let refuse = || { BaseRegistryClientError::protocol( @@ -1411,11 +1413,7 @@ fn decode_envelope( ) }; let value = crate::strict_json::from_slice(raw.value.as_bytes()).map_err(|_| refuse())?; - let mut object = value.as_object().cloned().ok_or_else(refuse)?; - if object.len() != members.len() || members.iter().any(|member| !object.contains_key(*member)) { - return Err(refuse()); - } - let value = decode(&mut object).map_err(|_| refuse())?; + let value = decode(value).map_err(|_| refuse())?; Ok(BRegComplete { value, metadata: raw.metadata, @@ -1498,6 +1496,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,19 +1517,15 @@ impl BaseRegistryClient { request.body().to_vec(), Some(crate::client::APPLICATION_JSON), reqwest::StatusCode::CREATED, + access_reason, ) .await?; - decode_envelope( - raw, - reqwest::StatusCode::CREATED.as_u16(), - &["run"], - |object| { - bound_created_run( - BRegIngestionRun::from_value(take_member(object, "run")?)?, - request, - ) - }, - ) + decode_envelope(raw, reqwest::StatusCode::CREATED.as_u16(), |object| { + bound_created_run( + BRegIngestionRun::from_value(take_member(object, "run")?)?, + request, + ) + }) } /// Read one bounded page of ingestion runs for one record route. @@ -1528,18 +1533,29 @@ 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( raw, reqwest::StatusCode::OK.as_u16(), - &["runs", "hasMore", "nextCursor"], BRegIngestionRunPage::from_members, ) } @@ -1552,6 +1568,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,9 +1594,10 @@ impl BaseRegistryClient { &run_identifier, ], &pairs, + access_reason, ) .await?; - decode_envelope(raw, reqwest::StatusCode::OK.as_u16(), &["run"], |object| { + decode_envelope(raw, reqwest::StatusCode::OK.as_u16(), |object| { bound_run( BRegIngestionRun::from_value(take_member(object, "run")?)?, run_id, @@ -1586,6 +1615,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,20 +1652,16 @@ impl BaseRegistryClient { chunk.body().to_vec(), Some(crate::client::APPLICATION_JSON), reqwest::StatusCode::OK, + access_reason, ) .await?; - decode_envelope( - raw, - reqwest::StatusCode::OK.as_u16(), - &["run", "receipt"], - |object| { - bound_submission( - BRegIngestionChunkSubmission::from_members(object)?, - run_id, - chunk, - ) - }, - ) + decode_envelope(raw, reqwest::StatusCode::OK.as_u16(), |object| { + bound_submission( + BRegIngestionChunkSubmission::from_members(object)?, + run_id, + chunk, + ) + }) } /// Cancel an open ingestion run. Committed chunks stay committed. @@ -1630,6 +1674,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,9 +1704,10 @@ impl BaseRegistryClient { Vec::new(), None, reqwest::StatusCode::OK, + access_reason, ) .await?; - decode_envelope(raw, reqwest::StatusCode::OK.as_u16(), &["run"], |object| { + decode_envelope(raw, reqwest::StatusCode::OK.as_u16(), |object| { bound_run( BRegIngestionRun::from_value(take_member(object, "run")?)?, run_id, @@ -1667,6 +1724,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,19 +1761,12 @@ impl BaseRegistryClient { "receipt", ], &pairs, + access_reason, ) .await?; - decode_envelope( - raw, - reqwest::StatusCode::OK.as_u16(), - &["receipt"], - |object| { - bound_receipt( - BRegIngestionChunkReceipt::from_value(take_member(object, "receipt")?)?, - chunk_index, - ) - }, - ) + decode_response(raw, reqwest::StatusCode::OK.as_u16(), |value| { + bound_receipt(BRegIngestionChunkReceipt::from_value(value)?, chunk_index) + }) } } @@ -1833,7 +1902,7 @@ mod tests { } #[test] - fn unknown_run_values_and_members_are_refused() { + fn invalid_run_values_and_missing_members_are_refused() { for mutate in [ |wire: &mut Value| wire["status"] = json!("archived"), |wire: &mut Value| wire["status"] = json!(7), @@ -1841,10 +1910,8 @@ mod tests { |wire: &mut Value| wire["blockedReason"] = json!("import_authority_closed"), |wire: &mut Value| wire["operation"] = json!("delete"), |wire: &mut Value| wire["lastAttempt"]["outcome"] = json!("crashed"), - |wire: &mut Value| { - wire["lastAttempt"] = json!({"outcome": "committed", "chunkIndex": 0, "extra": 1}) - }, - |wire: &mut Value| wire["extra"] = json!("member"), + |wire: &mut Value| wire["lastAttempt"] = json!({"outcome": "committed"}), + |wire: &mut Value| drop(wire.as_object_mut().unwrap().remove("blockedReason")), |wire: &mut Value| wire["inputDigest"] = json!("AAAA"), |wire: &mut Value| wire["runId"] = json!("not-a-uuid"), |wire: &mut Value| wire["recordType"] = json!("Facility"), @@ -1896,10 +1963,10 @@ mod tests { for mutate in [ |wire: &mut Value| wire["replayed"] = json!("yes"), |wire: &mut Value| wire["digest"] = json!(PREFIX_DIGEST.to_owned() + "0"), - |wire: &mut Value| wire["extra"] = json!(1), + |wire: &mut Value| drop(wire.as_object_mut().unwrap().remove("erased")), |wire: &mut Value| wire["batch"]["snapshot"] = json!("snapshot-1"), |wire: &mut Value| wire["batch"]["results"] = json!("none"), - |wire: &mut Value| wire["batch"]["extra"] = json!(1), + |wire: &mut Value| drop(wire["batch"].as_object_mut().unwrap().remove("snapshot")), ] { let mut wire = receipt_wire(); mutate(&mut wire); @@ -1961,7 +2028,7 @@ mod tests { } #[test] - fn submission_and_page_envelopes_decode_their_exact_members() { + fn submission_and_page_envelopes_require_known_members() { let run = run_wire(); let receipt = receipt_wire(); let submission = BRegIngestionChunkSubmission::from_members( @@ -1973,11 +2040,6 @@ mod tests { assert_eq!(submission.run().run_id().to_string(), RUN_ID); assert_eq!(submission.receipt().chunk_index(), 0); for mutate in [ - |wire: &mut Value| { - wire.as_object_mut() - .expect("object") - .insert("extra".to_owned(), json!(1)); - }, |wire: &mut Value| drop(wire.as_object_mut().expect("object").remove("receipt")), |wire: &mut Value| drop(wire.as_object_mut().expect("object").remove("run")), ] { @@ -2016,24 +2078,18 @@ mod tests { #[test] fn envelope_decode_maps_strict_failures_to_protocol_body_failures() { - let error = decode_envelope( - raw_document(&json!({"run": run_wire(), "extra": 1})), - 201, - &["run"], - |object| BRegIngestionRun::from_value(take_member(object, "run")?), - ) - .expect_err("an envelope with an extra member is a protocol failure"); + let error = decode_envelope(raw_document(&json!({"extra": 1})), 201, |object| { + BRegIngestionRun::from_value(take_member(object, "run")?) + }) + .expect_err("an envelope missing its run is a protocol failure"); let BaseRegistryClientError::Protocol { status, .. } = error else { panic!("a body mismatch is a protocol failure"); }; assert_eq!(status, 201); - let complete = decode_envelope( - raw_document(&json!({"run": run_wire()})), - 201, - &["run"], - |object| BRegIngestionRun::from_value(take_member(object, "run")?), - ) + let complete = decode_envelope(raw_document(&json!({"run": run_wire()})), 201, |object| { + BRegIngestionRun::from_value(take_member(object, "run")?) + }) .expect("the run envelope decodes"); assert_eq!(complete.value.run_id().to_string(), RUN_ID); } 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/metadata.rs b/crates/registry-breg-client/src/metadata.rs index c9004cc3d4..285af64663 100644 --- a/crates/registry-breg-client/src/metadata.rs +++ b/crates/registry-breg-client/src/metadata.rs @@ -1775,7 +1775,18 @@ impl BRegMetadata { && request.if_match_required == Some(true) && request.mutation_semantics.as_deref() == Some("direct") && request.patch_path_prefix.as_deref() == Some("/data/") - && request.patch_operations == ["add", "replace", "remove", "test"] + && matches!( + request + .patch_operations + .iter() + .map(String::as_str) + .collect::>() + .as_slice(), + ["add", "replace"] + | ["add", "replace", "remove"] + | ["add", "replace", "test"] + | ["add", "replace", "remove", "test"] + ) && request.remove_semantics.as_deref() == Some("set_null") && request.maximum_items.is_none() && request.maximum_body_bytes.is_none() @@ -3325,6 +3336,9 @@ fn validate_temporal(value: Value) -> Result<(), BRegMetadataError> { "as-of" => { bounded_text(required(&mut temporal, "parameter")?)?; boolean(required(&mut temporal, "required")?)?; + if let Some(first_page) = temporal.remove("requiredOnFirstPage") { + boolean(first_page)?; + } validate_schema_object(required(&mut temporal, "schema")?)?; } "snapshot" => { diff --git a/crates/registry-breg-client/src/metadata_tests.rs b/crates/registry-breg-client/src/metadata_tests.rs index cd5e093e02..b6dd967961 100644 --- a/crates/registry-breg-client/src/metadata_tests.rs +++ b/crates/registry-breg-client/src/metadata_tests.rs @@ -75,7 +75,7 @@ fn fixture() -> Value { "body": "json_patch", "contentType": "application/json-patch+json", "patchPathPrefix": "/data/", - "patchOperations": ["add", "replace", "remove", "test"], + "patchOperations": ["add", "replace", "test"], "removeSemantics": "set_null", "ifMatchRequired": true, "idempotencyKeyRequired": true, @@ -776,7 +776,7 @@ fn list_query_and_presentation_descriptors_are_retained_without_authority() { "sortableFields": [{"id": "legal-name", "apiName": "legalName", "directions": ["asc", "desc"]}], "allowCount": true, "defaultPageSize": 25, "maximumPageSize": 100, "maximumFilterClauses": 5, "maximumInValues": 10, - "pagination": {"parameter": "$skiptoken", "responsePath": "pageInfo.nextCursor", "exclusive": true}, + "pagination": {"parameter": "cursor", "responsePath": "pageInfo.nextCursor", "exclusive": true}, "temporal": {"mode": "current"} }); let metadata = parse(&value); @@ -789,6 +789,9 @@ fn list_query_and_presentation_descriptors_are_retained_without_authority() { assert_eq!(query.filterable_fields[0].api_name, "legalName"); assert_eq!(query.filterable_fields[0].operators, ["equals", "in"]); assert_eq!(query.maximum_page_size, 100); + assert_eq!(query.pagination.parameter, "cursor"); + assert_eq!(query.pagination.response_path, "pageInfo.nextCursor"); + assert!(query.pagination.exclusive); assert!(metadata .select_direct_write("records.company.get", "company-writer") .is_err()); @@ -843,7 +846,7 @@ fn unsupported_selector_is_omitted_and_unsupported_temporal_mode_stays_visible() "filterableFields": [], "sortableFields": [], "allowCount": false, "defaultPageSize": 25, "maximumPageSize": 100, "maximumFilterClauses": 5, "maximumInValues": 10, - "pagination": {"parameter": "$skiptoken", "responsePath": "pageInfo.nextCursor", "exclusive": true}, + "pagination": {"parameter": "cursor", "responsePath": "pageInfo.nextCursor", "exclusive": true}, "temporal": {"mode": "future-temporal-mode", "futureParameter": "at"} }); @@ -873,6 +876,29 @@ fn unsupported_selector_is_omitted_and_unsupported_temporal_mode_stays_visible() BRegMetadataErrorKind::Shape ); + let mut conditional = value.clone(); + conditional["operations"][2]["query"]["temporal"] = json!({ + "mode": "as-of", "parameter": "asOf", + "required": false, "requiredOnFirstPage": true, + "schema": {"type": "string", "format": "date-time"} + }); + let temporal = parse(&conditional) + .operation("records.company.get") + .unwrap() + .query() + .unwrap() + .temporal + .clone() + .unwrap(); + assert_eq!(temporal, conditional["operations"][2]["query"]["temporal"]); + conditional["operations"][2]["query"]["temporal"]["requiredOnFirstPage"] = json!("true"); + assert_eq!( + BRegMetadata::from_slice(&serde_json::to_vec(&conditional).unwrap()) + .unwrap_err() + .kind(), + BRegMetadataErrorKind::Shape + ); + let mut malformed_temporal = value; malformed_temporal["operations"][2]["query"]["temporal"] = json!({"mode": "as-of"}); assert_eq!( @@ -892,7 +918,7 @@ fn unsupported_spatial_vocabulary_omits_only_the_spatial_capability() { "filterableFields": [], "sortableFields": [], "allowCount": false, "defaultPageSize": 25, "maximumPageSize": 100, "maximumFilterClauses": 5, "maximumInValues": 10, - "pagination": {"parameter": "$skiptoken", "responsePath": "pageInfo.nextCursor", "exclusive": true}, + "pagination": {"parameter": "cursor", "responsePath": "pageInfo.nextCursor", "exclusive": true}, "temporal": null, "spatialQueries": {"bbox": {"geometryProperty": "legalName", "maximumLongitudeSpanDegrees": 0.5, "maximumLatitudeSpanDegrees": 0.25, @@ -1210,7 +1236,7 @@ fn complete_descriptive_metadata_is_retained_and_spatial_is_optional() { "filterableFields": [], "sortableFields": [], "allowCount": false, "defaultPageSize": 25, "maximumPageSize": 100, "maximumFilterClauses": 8, "maximumInValues": 16, - "pagination": {"parameter": "$skiptoken", "responsePath": "pageInfo.nextCursor", "exclusive": true}, + "pagination": {"parameter": "cursor", "responsePath": "pageInfo.nextCursor", "exclusive": true}, "temporal": null, "spatialQueries": {"bbox": {"geometryProperty": "legalName", "maximumLongitudeSpanDegrees": 0.5, "maximumLatitudeSpanDegrees": 0.25, @@ -1266,7 +1292,7 @@ fn required_filters_are_validated_and_exposed_on_the_query() { "filterableFields": [], "sortableFields": [], "allowCount": false, "defaultPageSize": 25, "maximumPageSize": 100, "maximumFilterClauses": 8, "maximumInValues": 16, - "pagination": {"parameter": "$skiptoken", "responsePath": "pageInfo.nextCursor", "exclusive": true}, + "pagination": {"parameter": "cursor", "responsePath": "pageInfo.nextCursor", "exclusive": true}, "temporal": null }); value["operations"][2]["query"]["requiredFilters"] = diff --git a/crates/registry-breg-client/src/proposal.rs b/crates/registry-breg-client/src/proposal.rs index 11509edef2..8be3b2f7c8 100644 --- a/crates/registry-breg-client/src/proposal.rs +++ b/crates/registry-breg-client/src/proposal.rs @@ -1,7 +1,7 @@ // SPDX-License-Identifier: Apache-2.0 //! Distinct Proposal resources and exact, caller-controlled transition attempts. -use crate::*; +use crate::{client::ProblemContext, *}; use serde::{Deserialize, Serialize}; use serde_json::Value; use std::collections::BTreeMap; @@ -22,6 +22,7 @@ pub use asks::{ BRegProposalAnswerRequest, BRegProposalAsk, BRegProposalAskAnswer, BRegProposalAskState, BRegProposalAskWant, }; +mod response; mod review_asks; mod review_document; pub use additions::{BRegProposalAddition, BRegProposalAdditionSlot}; @@ -689,6 +690,24 @@ impl BRegProposal { proposal.validate()?; Ok(proposal) } + pub(crate) fn from_response(bytes: &[u8]) -> Result { + if bytes.len() > DEFAULT_MAXIMUM_RESPONSE_BYTES as usize { + return Err(refusal()); + } + let proposal: Self = response::decode(bytes, response::proposal).map_err(|_| refusal())?; + proposal.validate()?; + Ok(proposal) + } + fn from_current_response(bytes: &[u8]) -> Result { + let proposal = Self::from_response(bytes)?; + proposal.require_current_turn()?; + Ok(proposal) + } + + fn require_current_turn(&self) -> Result<(), BaseRegistryClientError> { + self.turn.map(|_| ()).ok_or_else(refusal) + } + fn validate(&self) -> Result<(), BaseRegistryClientError> { if !canonical_proposal_id(&self.id) || self.submission_version == 0 @@ -748,10 +767,12 @@ impl BRegProposal { }; let valid_turn = self.turn.is_none_or(|turn| match status { Status::Draft | Status::AwaitingParty => turn == BRegProposalTurn::Party, - Status::InReview => turn == BRegProposalTurn::Official, - Status::Approved | Status::Processing => { - matches!(turn, BRegProposalTurn::Official | BRegProposalTurn::Nobody) + // An unread office message can give the party the turn + // without changing the underlying command status. + Status::InReview => { + matches!(turn, BRegProposalTurn::Party | BRegProposalTurn::Official) } + Status::Approved | Status::Processing => true, Status::Applied | Status::Rejected | Status::Cancelled => { turn == BRegProposalTurn::Nobody } @@ -1012,6 +1033,11 @@ impl BRegProposal { source: String, profile: &str, ) -> Result { + self.check_link_profiles(profile)?; + Ok(self.bind(source)) + } + + fn check_link_profiles(&self, profile: &str) -> Result<(), BaseRegistryClientError> { if self .links .values() @@ -1036,7 +1062,7 @@ impl BRegProposal { { return Err(refusal()); } - Ok(self.bind(source)) + Ok(()) } } impl fmt::Debug for BRegProposal { @@ -1377,8 +1403,13 @@ impl BaseRegistryClient { let response = self.proposal_exchange(&link, Some(body), None).await?; let value = crate::strict_json::from_slice(response.value.as_bytes()).map_err(|_| refusal())?; + let expected = serde_json::to_value(request).map_err(|_| refusal())?; + if value.get("request") != Some(&expected) { + return Err(refusal()); + } let document: BRegProposalTaskContextDocument = - serde_json::from_value(value).map_err(|_| refusal())?; + response::decode_value(value, response::task_context) + .map_err(|_| invalid_response(&response.metadata))?; let fields = document.proposal.context.fields.as_ref().map(|fields| { fields .keys() @@ -1455,17 +1486,23 @@ impl BaseRegistryClient { } else { self.proposal_exchange(&link, None, None).await? }; - let value = - crate::strict_json::from_slice(response.value.as_bytes()).map_err(|_| refusal())?; - let document: BRegProposalReviewDocument = - serde_json::from_value(value).map_err(|_| refusal())?; let is_context = binding.operation == "get-review-context"; + let document: BRegProposalReviewDocument = response::decode( + response.value.as_bytes(), + if is_context { + response::review_context + } else { + response::review_status + }, + ) + .map_err(|_| refusal())?; if document.id != id || (!include_answers && (!document.context.asks.is_empty() || document.context.messages.is_some())) || document.action_id != binding.action || !valid_review_document(&document, is_context, false) || !review_asks::profiles(&document, &binding.profile) + || !messages::links_match_profile(&document, &binding.profile) { return Err(refusal()); } @@ -1515,11 +1552,11 @@ impl BaseRegistryClient { ("accessProfile".to_owned(), binding.profile.clone()), ("ids".to_owned(), ids.join(",")), ], + ProblemContext::Default, ) .await?; - let value: serde_json::Value = - crate::strict_json::from_slice(response.value.as_bytes()).map_err(|_| refusal())?; - let batch: Batch = serde_json::from_value(value).map_err(|_| refusal())?; + let batch: Batch = response::decode(response.value.as_bytes(), response::review_batch) + .map_err(|_| refusal())?; if batch.items.len() != ids.len() { return Err(refusal()); } @@ -1566,12 +1603,16 @@ impl BaseRegistryClient { availability: None, }; let response = self.proposal_exchange(&link, None, None).await?; - let proposal = BRegProposal::from_slice(response.value.as_bytes())?; + let invalid = || invalid_response(&response.metadata); + let proposal = BRegProposal::from_current_response(response.value.as_bytes()) + .map_err(|_| invalid())?; if proposal.id != id { - return Err(refusal()); + return Err(invalid()); } Ok(BRegComplete { - value: proposal.bind_profile(self.source_binding(), &binding.profile)?, + value: proposal + .bind_profile(self.source_binding(), &binding.profile) + .map_err(|_| invalid())?, metadata: response.metadata, }) } @@ -1622,10 +1663,15 @@ impl BaseRegistryClient { } else { self.proposal_exchange(link, None, None).await? }; - let value = - crate::strict_json::from_slice(response.value.as_bytes()).map_err(|_| refusal())?; - let document: BRegProposalReviewDocument = - serde_json::from_value(value).map_err(|_| refusal())?; + let document: BRegProposalReviewDocument = response::decode( + response.value.as_bytes(), + if operation == "reviewContext" { + response::review_context + } else { + response::review_status + }, + ) + .map_err(|_| refusal())?; if document.id != proposal.id || document.action_id != proposal.action_id || document.action_revision != proposal.action_revision @@ -1637,6 +1683,7 @@ impl BaseRegistryClient { .is_some_and(|digest| digest != document.effect_digest) || !valid_review_document(&document, operation == "reviewContext", include_progress) || !review_asks::profiles(&document, &link.access_profile) + || !messages::links_match_profile(&document, &link.access_profile) { return Err(refusal()); } @@ -1752,8 +1799,8 @@ impl BaseRegistryClient { Some(response.metadata.trace_id().clone()), ) }; - let current = - BRegProposal::from_slice(response.value.as_bytes()).map_err(|_| invalid_receipt())?; + let current = BRegProposal::from_response(response.value.as_bytes()) + .map_err(|_| invalid_receipt())?; if current.discloses_application_actor() || current.id != prior.id || current.action_id != prior.action_id @@ -1854,11 +1901,11 @@ impl BaseRegistryClient { pairs.push(("limit".to_owned(), limit.to_string())); } let response = self - .proposal_list_exchange(&collection.path, &pairs) + .proposal_list_exchange(&collection.path, &pairs, ProblemContext::Default) .await?; - let value = - crate::strict_json::from_slice(response.value.as_bytes()).map_err(|_| refusal())?; - let mut page: BRegProposalPage = serde_json::from_value(value).map_err(|_| refusal())?; + let invalid = || invalid_response(&response.metadata); + let mut page: BRegProposalPage = + response::decode(response.value.as_bytes(), response::page).map_err(|_| invalid())?; if page.items.len() > query.limit.unwrap_or(50) as usize || page.next_cursor.as_ref().is_some_and(|cursor| { !valid_cursor(cursor) || query.cursor.as_ref() == Some(cursor) @@ -1867,7 +1914,8 @@ impl BaseRegistryClient { return Err(refusal()); } for item in &mut page.items { - item.validate()?; + item.validate().map_err(|_| invalid())?; + item.require_current_turn().map_err(|_| invalid())?; if item.discloses_application_actor() || query .action @@ -1883,20 +1931,8 @@ impl BaseRegistryClient { { return Err(refusal()); } - if item - .links - .values() - .chain( - item.attachments - .values() - .flat_map(|slot| slot.links.values()), - ) - .chain(item.addition_links()) - .chain(item.asks.iter().flat_map(|ask| ask.links.values())) - .any(|link| link.access_profile != collection.profile) - { - return Err(refusal()); - } + item.check_link_profiles(&collection.profile) + .map_err(|_| invalid())?; item.source = Some(self.source_binding()); } Ok(BRegComplete { @@ -1990,8 +2026,8 @@ impl BaseRegistryClient { Some(response.metadata.trace_id().clone()), ) }; - let proposal = - BRegProposal::from_slice(response.value.as_bytes()).map_err(|_| invalid_receipt())?; + let proposal = BRegProposal::from_response(response.value.as_bytes()) + .map_err(|_| invalid_receipt())?; if proposal.discloses_application_actor() || !transition_successor(&evidence, &proposal) { return Err(invalid_receipt()); } @@ -2012,7 +2048,8 @@ impl BaseRegistryClient { } let link = proposal.links.get("self").ok_or_else(refusal)?; let response = self.proposal_exchange(link, None, None).await?; - let current = BRegProposal::from_slice(response.value.as_bytes())?; + let current = BRegProposal::from_current_response(response.value.as_bytes()) + .map_err(|_| invalid_response(&response.metadata))?; if current.id != proposal.id || current.action_id != proposal.action_id || current.action_revision != proposal.action_revision @@ -2053,10 +2090,9 @@ impl BaseRegistryClient { availability: None, }; let response = self.proposal_exchange(&link, None, None).await?; - let value = - crate::strict_json::from_slice(response.value.as_bytes()).map_err(|_| refusal())?; let submission: BRegProposalSubmission = - serde_json::from_value(value).map_err(|_| refusal())?; + response::decode(response.value.as_bytes(), response::retained_submission) + .map_err(|_| refusal())?; if submission.id != proposal.id || submission.action_id != proposal.action_id || submission.submission_version != version @@ -2216,6 +2252,7 @@ fn valid_review_document( && document.subject.source.len() <= 512 && !document.context.reference.is_empty() && document.context.reference.len() <= 2048 + && document.context.additional_forms.len() <= 8 && document.context.contract.as_ref().is_none_or(|contract| { contract.id.starts_with("urn:registry:breg:review-context:") && contract.id.len() <= 2048 @@ -2418,19 +2455,11 @@ fn proposal_instant(value: &str) -> Option { fn canonical_proposal_id(value: &str) -> bool { Uuid::parse_str(value).is_ok_and(|id| !id.is_nil() && id.to_string() == value) } -/// An available link carries no reason, and an unavailable one carries a -/// recovery BReg pairs with its reason: a rejected review is revised while -/// the Proposal is still submitted and read from its receipt once it is -/// rejected, and a changed package is rebased. A closed Proposal names its -/// state on every unavailable link, and an open one never gives either closed -/// reason. -fn valid_availability( - availability: &BRegAvailability, - revision: u64, - state: BRegProposalState, -) -> bool { +/// An available link carries no reason or recovery. On unavailable links, +/// BReg pairs the reason with its recovery, such as rebase for a changed package. +/// Thread replies may carry availability without a Proposal lifecycle state. +fn valid_availability_pair(availability: &BRegAvailability, revision: u64) -> bool { use BRegAvailabilityReason as Reason; - use BRegProposalState as State; use BRegRecoveryHint as Recovery; availability.observed_revision == revision && match ( @@ -2471,6 +2500,21 @@ fn valid_availability( ), (false, _, _) => false, } +} + +/// A closed Proposal names its state on every unavailable lifecycle link. +/// An open Proposal never uses a closed-state reason. A rejected review is +/// revised while the Proposal is submitted and read from its receipt once +/// the Proposal is rejected. +fn valid_availability( + availability: &BRegAvailability, + revision: u64, + state: BRegProposalState, +) -> bool { + use BRegAvailabilityReason as Reason; + use BRegProposalState as State; + use BRegRecoveryHint as Recovery; + valid_availability_pair(availability, revision) && (availability.available || match (availability.reason, availability.recovery) { (Some(Reason::AlreadyApplied), _) => state == State::Applied, @@ -2667,6 +2711,14 @@ fn unavailable(availability: &BRegAvailability) -> BaseRegistryClientError { _ => return refusal(), }) } +fn invalid_response(metadata: &crate::BRegResponseMetadata) -> BaseRegistryClientError { + BaseRegistryClientError::protocol( + 200, + BRegProtocolFailure::Body, + Some(metadata.trace_id().clone()), + ) +} + fn refusal() -> BaseRegistryClientError { BaseRegistryClientError::invalid_request( "the Base Registry Engine Proposal contract or attempt is invalid", @@ -2778,6 +2830,58 @@ mod tests { assert_eq!(token.0.load(Ordering::SeqCst), 0); } + #[tokio::test] + async fn task_context_refuses_disclosed_forms_or_messages() { + let subject = json!({"source":"invitation-source","subjectType":"proposal", + "id":ID,"version":"1","digest":REVISION}); + let contract = json!({"id":"urn:registry:breg:review-context:invitation-source:book-visit:booking-context", + "revision":REVISION,"schemaDigest":REVISION}); + let policy = json!({"id":"booking-review","version":"1","digest":REVISION}); + let request: BRegProposalTaskContextRequest = serde_json::from_value(json!({ + "expected":{"actionId":"book-visit","subject":subject,"contract":contract}, + "requestId":"00000000-0000-4000-8000-000000000010", + "taskId":"00000000-0000-4000-8000-000000000011", + "taskRevision":3,"policy":policy,"purpose":"task-grant","fields":["applicationId"] + })) + .unwrap(); + let reply = json!({"request":request,"proposal":{"id":ID,"actionId":"book-visit", + "actionRevision":REVISION,"submissionVersion":1,"revision":3,"effectDigest":REVISION, + "subject":subject,"authority":"review","policy":policy,"reviewable":true, + "context":{"reference":"opaque","contract":contract,"fields":{"applicationId":ID}}}}); + let (client, responses, server) = proposal_response_client(reply.clone()).await; + let binding = BRegProposalTaskContextBinding::from_metadata( + &json!([{"actionId":"book-visit","accessProfile":"task-context", + "operations":["get-task-grant-context"],"readableContextFields":["applicationId"]}]), + &client.source_binding(), "task-context", "book-visit", + ).unwrap(); + client + .read_proposal_task_grant_context(&binding, &request) + .await + .unwrap(); + for (member, value) in [ + ("additionalForms", json!({"extra":"extra"})), + ("messages", json!({"count":1,"unread":0})), + ] { + let mut response = reply.clone(); + response["proposal"]["context"][member] = value; + *responses.lock().unwrap() = response; + let error = client + .read_proposal_task_grant_context(&binding, &request) + .await + .err() + .expect("task context must stay within the task projection"); + assert_eq!(error.status(), Some(200)); + assert!(matches!( + error, + BaseRegistryClientError::Protocol { + failure: BRegProtocolFailure::Body, + .. + } + )); + } + server.abort(); + } + async fn proposal_response_client( initial: Value, ) -> ( @@ -2789,19 +2893,29 @@ mod tests { use std::sync::{Arc, Mutex}; let response = Arc::new(Mutex::new(initial)); let app = Router::new() - .fallback(any(|State(value): State>>| async move { - ( - [ - ( - "traceparent", - "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01", - ), - ("cache-control", "no-store"), - ("vary", "authorization, accept"), - ], - Json(value.lock().unwrap().clone()), - ) - })) + .fallback(any( + |State(value): State>>, uri: axum::http::Uri| async move { + let status = if uri.path().starts_with("/v1/actions/") + && uri.path().ends_with("/proposals") + { + axum::http::StatusCode::CREATED + } else { + axum::http::StatusCode::OK + }; + ( + status, + [ + ( + "traceparent", + "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01", + ), + ("cache-control", "no-store"), + ("vary", "authorization, accept"), + ], + Json(value.lock().unwrap().clone()), + ) + }, + )) .with_state(response.clone()); let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); let address = listener.local_addr().unwrap(); @@ -2858,6 +2972,11 @@ mod tests { let mut current = document(); current["revision"] = json!(revision); current["state"] = json!(state); + current["turn"] = json!(match state { + "draft" => "party", + "applied" => "nobody", + _ => "official", + }); if state == "draft" { current.as_object_mut().unwrap().remove("effectDigest"); } else if state == "applied" { @@ -2895,6 +3014,11 @@ mod tests { current["revision"] = json!(5); current["submissionVersion"] = json!(version); current["state"] = json!(state); + current["turn"] = json!(match state { + "draft" => "party", + "applied" => "nobody", + _ => "official", + }); if state == "draft" { current.as_object_mut().unwrap().remove("effectDigest"); } @@ -3389,7 +3513,9 @@ mod tests { ); } for cursor in [ID.to_owned(), "x".repeat(512)] { - *response.lock().unwrap() = json!({"items":[document()],"nextCursor":cursor}); + let mut item = document(); + item["turn"] = json!("official"); + *response.lock().unwrap() = json!({"items":[item],"nextCursor":cursor}); let page = client .list_proposals(&collection, &BRegProposalQuery::default()) .await @@ -3744,6 +3870,13 @@ mod tests { absent.as_object_mut().unwrap().remove("handoff"); assert_eq!(read(absent).await.unwrap(), None); + let mut extended = valid.clone(); + extended["handoff"]["extra"] = json!(true); + assert_eq!( + read(extended).await.unwrap(), + read(valid.clone()).await.unwrap() + ); + let mut cases = Vec::new(); for handoff in [ json!({"state":"accepted"}), @@ -3751,7 +3884,6 @@ mod tests { json!({"state":"pending","reason":"remote-refused"}), json!({"state":"failed","reason":"synthetic-internal-code"}), json!({"state":"settled"}), - json!({"state":"pending","extra":true}), json!({}), json!("pending"), ] { @@ -4524,6 +4656,7 @@ mod tests { #[tokio::test] async fn proposal_get_accepts_both_sides_of_the_thread_and_enforces_message_bounds() { let mut value = document(); + value["turn"] = json!("official"); value["messages"] = json!({ "count": 1001, "unread": 1000, "lastSentAt": "2026-12-01T10:00:00Z", "items": [{"id": ID, "from": "official", "mine": false, @@ -4553,7 +4686,10 @@ mod tests { assert!( matches!( client.get_proposal(&binding, ID).await, - Err(BaseRegistryClientError::InvalidRequest { .. }) + Err(BaseRegistryClientError::Protocol { + failure: BRegProtocolFailure::Body, + .. + }) ), "count={count}, unread={unread}" ); @@ -4669,6 +4805,11 @@ mod tests { for returned in states { let mut item = document(); item["state"] = serde_json::to_value(returned).unwrap(); + item["turn"] = json!(match returned { + BRegProposalState::Draft => "party", + BRegProposalState::Submitted => "official", + _ => "nobody", + }); if returned == BRegProposalState::Draft { item.as_object_mut().unwrap().remove("effectDigest"); } else if returned == BRegProposalState::Applied { @@ -4766,6 +4907,7 @@ mod tests { let ask_id = "00000000-0000-4000-8000-000000000099"; let make_item = |profile: &str| { let mut item = document(); + item["turn"] = json!("party"); item["asks"] = json!([{ "id": ask_id, "text": "Provide proof", diff --git a/crates/registry-breg-client/src/proposal/additions.rs b/crates/registry-breg-client/src/proposal/additions.rs index 3b306cd383..972474672d 100644 --- a/crates/registry-breg-client/src/proposal/additions.rs +++ b/crates/registry-breg-client/src/proposal/additions.rs @@ -48,8 +48,8 @@ impl BaseRegistryClient { Some(response.metadata.trace_id().clone()), ) }; - let current = - BRegProposal::from_slice(response.value.as_bytes()).map_err(|_| invalid_receipt())?; + let current = BRegProposal::from_response(response.value.as_bytes()) + .map_err(|_| invalid_receipt())?; use sha2::{Digest, Sha256}; let hash = Sha256::digest(bytes) .iter() diff --git a/crates/registry-breg-client/src/proposal/asks.rs b/crates/registry-breg-client/src/proposal/asks.rs index 27b089f10d..04c95d3904 100644 --- a/crates/registry-breg-client/src/proposal/asks.rs +++ b/crates/registry-breg-client/src/proposal/asks.rs @@ -205,7 +205,8 @@ impl BaseRegistryClient { Some(response.metadata.trace_id().clone()), ) }; - let current = BRegProposal::from_slice(response.value.as_bytes()).map_err(|_| invalid())?; + let current = + BRegProposal::from_response(response.value.as_bytes()).map_err(|_| invalid())?; let matches_answer = current.asks.is_empty() || current .asks diff --git a/crates/registry-breg-client/src/proposal/forms.rs b/crates/registry-breg-client/src/proposal/forms.rs index bd588ac3cd..4db321dbf2 100644 --- a/crates/registry-breg-client/src/proposal/forms.rs +++ b/crates/registry-breg-client/src/proposal/forms.rs @@ -116,7 +116,8 @@ impl BaseRegistryClient { Some(response.metadata.trace_id().clone()), ) }; - let current = BRegProposal::from_slice(response.value.as_bytes()).map_err(|_| invalid())?; + let current = + BRegProposal::from_response(response.value.as_bytes()).map_err(|_| invalid())?; let entry_id = current.form_entry_id().ok_or_else(invalid)?; let slot = current.additional_forms.get(form_id).ok_or_else(invalid)?; if current.discloses_application_actor() diff --git a/crates/registry-breg-client/src/proposal/messages.rs b/crates/registry-breg-client/src/proposal/messages.rs index 3272574f51..f1b78ea651 100644 --- a/crates/registry-breg-client/src/proposal/messages.rs +++ b/crates/registry-breg-client/src/proposal/messages.rs @@ -50,7 +50,6 @@ pub struct BRegProposalMessagePage { #[serde(default, skip_serializing_if = "Option::is_none")] pub next_cursor: Option, /// The thread's links, with the write's current condition. - #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] pub links: BTreeMap, } @@ -69,6 +68,8 @@ pub enum BRegProposalMessageOutcome { /// review context is readable, between rounds or after the Action /// changed. Thread(Box), + /// Mark Read completed without a caller-visible response document. + NoContent, } impl BRegProposal { @@ -131,27 +132,41 @@ pub(super) fn valid_thread(thread: &BRegProposalMessages, id: &str, revision: u6 .items .as_ref() .is_none_or(|items| items.len() <= usize::from(thread.count) && valid_items(items, 20)) - && thread.links.iter().all(|(name, link)| { - let (method, tail, keyed) = match name.as_str() { - "message" => ("POST", "", true), - "markRead" => ("POST", "/read", false), - "list" => ("GET", "", false), - _ => return false, - }; - identifier(&link.access_profile) - && link.method == method - && link.operation == "message" - && link.path == format!("/v1/proposals/{id}/messages{tail}") - && (if keyed { - valid_condition(link.if_match.as_deref()) - } else { - link.if_match.is_none() - }) - && link - .availability - .as_ref() - .is_some_and(|value| value.observed_revision == revision) + && thread + .links + .iter() + .all(|(name, link)| valid_thread_link(name, link, id, revision)) +} + +pub(super) fn links_match_profile(document: &BRegProposalReviewDocument, profile: &str) -> bool { + document.context.messages.as_ref().is_none_or(|thread| { + thread + .links + .values() + .all(|link| link.access_profile == profile) + }) +} + +fn valid_thread_link(name: &str, link: &BRegProposalLink, id: &str, revision: u64) -> bool { + let (method, tail, keyed) = match name { + "message" => ("POST", "", true), + "markRead" => ("POST", "/read", false), + "list" => ("GET", "", false), + _ => return false, + }; + identifier(&link.access_profile) + && link.method == method + && link.operation == "message" + && link.path == format!("/v1/proposals/{id}/messages{tail}") + && (if keyed { + valid_condition(link.if_match.as_deref()) + } else { + link.if_match.is_none() }) + && link + .availability + .as_ref() + .is_some_and(|value| valid_availability_pair(value, revision)) } impl<'a> BRegProposalMessageTarget<'a> { @@ -220,10 +235,12 @@ impl BaseRegistryClient { pub async fn list_proposal_messages( &self, target: BRegProposalMessageTarget<'_>, - after: Option<&str>, + cursor: Option<&str>, limit: u8, ) -> Result, BaseRegistryClientError> { - if !(1..=50).contains(&limit) || after.is_some_and(|value| cursor(value).is_none()) { + if !(1..=50).contains(&limit) + || cursor.is_some_and(|value| cursor_position(value).is_none()) + { return Err(refusal()); } let source = self.source_binding(); @@ -232,10 +249,12 @@ impl BaseRegistryClient { ("accessProfile".into(), link.access_profile.clone()), ("limit".into(), limit.to_string()), ]; - if let Some(after) = after { - query.push(("after".into(), after.into())); + if let Some(cursor) = cursor { + query.push(("cursor".into(), cursor.into())); } - let result = self.proposal_list_exchange(&link.path, &query).await?; + let result = self + .proposal_list_exchange(&link.path, &query, ProblemContext::ProposalThreadList) + .await?; let invalid = || { BaseRegistryClientError::protocol( 200, @@ -244,7 +263,9 @@ impl BaseRegistryClient { ) }; let page: BRegProposalMessagePage = - decode(result.value.as_bytes()).map_err(|_| invalid())?; + response::decode(result.value.as_bytes(), response::message_page) + .map_err(|_| invalid())?; + let (id, _, _) = target.identity(); let observed = page .links .values() @@ -252,14 +273,18 @@ impl BaseRegistryClient { .map(|availability| availability.observed_revision) .collect::>(); if !valid_items(&page.items, usize::from(limit)) - || page.links.values().any(|item| { - item.access_profile != link.access_profile || item.availability.is_none() + || page.links.iter().any(|(name, item)| { + item.access_profile != link.access_profile + || !item.availability.as_ref().is_some_and(|availability| { + availability.observed_revision != 0 + && valid_thread_link(name, item, id, availability.observed_revision) + }) }) || observed.len() > 1 || page.next_cursor.as_deref().is_some_and(|next| { - cursor(next).is_none() + cursor_position(next).is_none() || page.items.len() != usize::from(limit) - || after.is_some_and(|prior| cursor(next) >= cursor(prior)) + || cursor.is_some_and(|prior| cursor_position(next) >= cursor_position(prior)) }) { return Err(invalid()); @@ -283,13 +308,22 @@ impl BaseRegistryClient { return Err(unavailable(availability)); } let (id, action, prior) = target.identity(); - let response = self - .proposal_exchange( - link, - Some(serde_json::to_vec(&body).map_err(|_| refusal())?), - key, - ) - .await?; + let request = serde_json::to_vec(&body).map_err(|_| refusal())?; + let response = if operation == "markRead" { + let result = self.proposal_mark_read_exchange(link, request).await?; + let Some(value) = result.value else { + return Ok(BRegComplete { + value: BRegProposalMessageOutcome::NoContent, + metadata: result.metadata, + }); + }; + BRegComplete { + value, + metadata: result.metadata, + } + } else { + self.proposal_exchange(link, Some(request), key).await? + }; let invalid = || { BaseRegistryClientError::protocol( 200, @@ -314,17 +348,24 @@ impl BaseRegistryClient { .is_some_and(|entry| entry.mine && entry.text.as_deref() == Some(text)) }) }; - let value = match target { - BRegProposalMessageTarget::Proposal(prior) => { - let current = - BRegProposal::from_slice(response.value.as_bytes()).map_err(|_| invalid())?; + let document = + crate::strict_json::from_slice(response.value.as_bytes()).map_err(|_| invalid())?; + let proposal_reply = + |action_revision: &str, submission_version, effect_digest: Option<&str>| { + let bytes = response.value.as_bytes(); + let current = if key.is_some() { + BRegProposal::from_response(bytes) + } else { + BRegProposal::from_current_response(bytes) + } + .map_err(|_| invalid())?; if current.id != id || current.action_id != action || !valid_revision(current.revision) || key.is_some() - && (current.action_revision != prior.action_revision - || current.submission_version != prior.submission_version - || current.effect_digest != prior.effect_digest) + && (current.action_revision != action_revision + || current.submission_version != submission_version + || current.effect_digest.as_deref() != effect_digest) || current .messages .as_ref() @@ -333,44 +374,55 @@ impl BaseRegistryClient { { return Err(invalid()); } - BRegProposalMessageOutcome::Proposal(Box::new( - current - .bind_profile(source, &link.access_profile) - .map_err(|_| invalid())?, - )) - } - // A reviewer whose profile also holds Get is answered with the - // Proposal document; one without Get is answered with the thread - // alone while no review context is readable. - BRegProposalMessageTarget::Review { .. } - if serde_json::from_slice::(response.value.as_bytes()) - .ok() - .is_some_and(|value| value.get("context").is_none()) => - { - let value: Value = - serde_json::from_slice(response.value.as_bytes()).map_err(|_| invalid())?; - if value.get("actionId").is_some() { - let current = BRegProposal::from_slice(response.value.as_bytes()) - .map_err(|_| invalid())?; + current + .bind_profile(source.clone(), &link.access_profile) + .map(Box::new) + .map(BRegProposalMessageOutcome::Proposal) + .map_err(|_| invalid()) + }; + let value = match target { + BRegProposalMessageTarget::Proposal(prior) => proposal_reply( + &prior.action_revision, + prior.submission_version, + prior.effect_digest.as_deref(), + )?, + BRegProposalMessageTarget::Review { + document: prior, .. + } => { + let proposal = proposal_reply( + &prior.action_revision, + prior.submission_version, + Some(&prior.effect_digest), + ) + .ok(); + let review = (|| { + let current: BRegProposalReviewDocument = + response::decode_value(document.clone(), response::review_context).ok()?; if current.id != id || current.action_id != action || !valid_revision(current.revision) - || current - .messages - .as_ref() - .is_none_or(|thread| !matches_outcome(thread)) - || current.discloses_application_actor() + || key.is_some() + && (current.action_revision != prior.action_revision + || current.submission_version != prior.submission_version + || current.effect_digest != prior.effect_digest + || current.subject != prior.subject) + || current.context.messages.as_ref().is_none_or(|thread| { + !matches_outcome(thread) + || thread + .links + .values() + .any(|item| item.access_profile != link.access_profile) + }) + || !valid_review_document(¤t, true, false) + || !current.context.asks.is_empty() { - return Err(invalid()); + return None; } - BRegProposalMessageOutcome::Proposal(Box::new( - current - .bind_profile(source, &link.access_profile) - .map_err(|_| invalid())?, - )) - } else { + Some(BRegProposalMessageOutcome::Review(Box::new(current))) + })(); + let thread = (|| { let thread: BRegProposalMessages = - decode(response.value.as_bytes()).map_err(|_| invalid())?; + response::decode_value(document, response::thread).ok()?; let observed = thread .links .values() @@ -386,37 +438,19 @@ impl BaseRegistryClient { .values() .any(|item| item.access_profile != link.access_profile) { - return Err(invalid()); + return None; } - BRegProposalMessageOutcome::Thread(Box::new(thread)) + Some(BRegProposalMessageOutcome::Thread(Box::new(thread))) + })(); + // Additive fields can look like members of another reply. + // Only a fully validated and correlated view can disambiguate. + match (proposal, review, thread) { + (Some(value), None, None) + | (None, Some(value), None) + | (None, None, Some(value)) => value, + _ => return Err(invalid()), } } - BRegProposalMessageTarget::Review { - document: prior, .. - } => { - let current: BRegProposalReviewDocument = - decode(response.value.as_bytes()).map_err(|_| invalid())?; - if current.id != id - || current.action_id != action - || !valid_revision(current.revision) - || key.is_some() - && (current.action_revision != prior.action_revision - || current.submission_version != prior.submission_version - || current.effect_digest != prior.effect_digest) - || current.context.messages.as_ref().is_none_or(|thread| { - !matches_outcome(thread) - || thread - .links - .values() - .any(|item| item.access_profile != link.access_profile) - }) - || !valid_review_document(¤t, true, false) - || !current.context.asks.is_empty() - { - return Err(invalid()); - } - BRegProposalMessageOutcome::Review(Box::new(current)) - } }; Ok(BRegComplete { value, @@ -425,14 +459,9 @@ impl BaseRegistryClient { } } -fn cursor(value: &str) -> Option { +fn cursor_position(value: &str) -> Option { value .parse::() .ok() .filter(|position| *position > 0 && position.to_string() == value) } - -fn decode(bytes: &[u8]) -> Result { - let value = crate::strict_json::from_slice(bytes).map_err(|_| ())?; - serde_json::from_value(value).map_err(|_| ()) -} diff --git a/crates/registry-breg-client/src/proposal/response.rs b/crates/registry-breg-client/src/proposal/response.rs new file mode 100644 index 0000000000..3bfadc6a65 --- /dev/null +++ b/crates/registry-breg-client/src/proposal/response.rs @@ -0,0 +1,332 @@ +// SPDX-License-Identifier: Apache-2.0 +//! Project bounded, duplicate-checked HTTP responses into the closed Proposal +//! models also used for caller-held inputs. +use serde::de::DeserializeOwned; +use serde_json::{Map, Value}; + +type Projection = fn(&mut Value) -> Result<(), ()>; + +pub(super) fn decode(bytes: &[u8], project: Projection) -> Result { + let value = crate::strict_json::from_slice(bytes).map_err(|_| ())?; + decode_value(value, project) +} + +pub(super) fn decode_value( + mut value: Value, + project: Projection, +) -> Result { + project(&mut value)?; + serde_json::from_value(value).map_err(|_| ()) +} + +fn members<'a>(value: &'a mut Value, fields: &[&str]) -> Result<&'a mut Map, ()> { + let object = value.as_object_mut().ok_or(())?; + object.retain(|name, _| fields.contains(&name.as_str())); + Ok(object) +} + +fn array(project: Projection) -> impl FnOnce(&mut Value) -> Result<(), ()> { + move |value| { + value + .as_array_mut() + .ok_or(())? + .iter_mut() + .try_for_each(project) + } +} + +fn map(project: Projection) -> impl FnOnce(&mut Value) -> Result<(), ()> { + move |value| { + value + .as_object_mut() + .ok_or(())? + .values_mut() + .try_for_each(project) + } +} + +fn links(relations: &'static [&'static str]) -> impl FnOnce(&mut Value) -> Result<(), ()> { + move |value| members(value, relations)?.values_mut().try_for_each(link) +} + +fn string(value: &mut Value) -> Result<(), ()> { + value.is_string().then_some(()).ok_or(()) +} + +fn optional( + project: impl FnOnce(&mut Value) -> Result<(), ()>, +) -> impl FnOnce(&mut Value) -> Result<(), ()> { + move |value| { + if value.is_null() { + Ok(()) + } else { + project(value) + } + } +} + +// Each projection declares the members its target uses, then visits the known +// nested shapes. Required fields and scalar types are still checked by Serde. +macro_rules! projection { + ($vis:vis $name:ident { $($field:literal),* $(,)? }) => { + $vis fn $name(value: &mut Value) -> Result<(), ()> { + members(value, &[$($field),*]).map(|_| ()) + } + }; + ($vis:vis $name:ident { $($field:literal $(=> $project:expr)?),* $(,)? }) => { + $vis fn $name(value: &mut Value) -> Result<(), ()> { + let object = members(value, &[$($field),*])?; + $(projection!(@field object, $field $(, $project)?);)* + Ok(()) + } + }; + (@field $object:ident, $field:literal) => {}; + (@field $object:ident, $field:literal, $project:expr) => { + if let Some(value) = $object.get_mut($field) { + ($project)(value)?; + } + }; +} + +projection!(pub(super) proposal { + "id", "actionId", "actionRevision", "input", "submissionVersion", "revision", + "state" => string, "title", "blockedReason", "createdAt", "effectDigest", + "links" => links(&["self", "reviewContext", "reviewStatus", "submit", "edit", "revise", + "rebase", "retry", "cancel", "apply"]), + "attachments" => map(attachment), + "additions" => map(addition_slot), + "additionalForms" => map(form), + "formEntryId", + "messages" => optional(thread), + "asks" => array(ask), + "application" => optional(application), + "applicationStatus" => optional(application_status), + "turn" => string, + "partyRole" => string, + "status" => string, + "decision" => optional(decision), + "handoffRefusal" => optional(handoff_refusal), +}); +projection!(pub(super) page { + "items" => array(list_item), "nextCursor" => string, +}); + +fn list_item(value: &mut Value) -> Result<(), ()> { + if let Some(thread) = value.get("messages") { + thread_summary(thread)?; + } + proposal(value) +} + +fn thread_summary(value: &Value) -> Result<(), ()> { + let object = value.as_object().ok_or(())?; + if object.contains_key("items") || object.contains_key("links") { + return Err(()); + } + Ok(()) +} +projection!(link { + "method", "path", "accessProfile", "operation", "ifMatch", + "availability" => optional(availability), +}); +projection!(availability { + "available", "observedRevision", "reason" => optional(string), "recovery" => optional(string), +}); +projection!(attachment { + "id", "required", "maximumBytes", "contentTypes", "classification", + "links" => links(&["download", "upload", "remove"]), + "value" => optional(attachment_value), +}); +projection!(attachment_value { + "submissionVersion", "sha256", "contentType", "byteSize", "uploadedAt", "verificationStatus", +}); +projection!(addition_slot { + "id", "maximumBytes", "maximumCount", "contentTypes", "classification", + "items" => array(addition), "links" => links(&["add"]), +}); +projection!(addition { + "id", "submissionVersion", "sha256", "byteSize", "contentType", "addedAt", "verificationStatus", + "links" => links(&["download"]), +}); +projection!(form { + "id", "maximumCount", "items" => optional(array(applicant_form_entry)), "links" => links(&["add"]), +}); +fn applicant_form_entry(value: &mut Value) -> Result<(), ()> { + form_entry_shape(value)?; + form_entry(value) +} + +projection!(form_entry { + "id", "submissionVersion", "addedAt", "input", "contractChanged", +}); +projection!(pub(super) thread { + "count", "unread", "lastSentAt", "readerSide" => string, "items" => optional(array(message)), + "links" => links(&["message", "markRead", "list"]), +}); +projection!(pub(super) message_page { + "items" => array(message), "nextCursor" => string, "links" => links(&["message", "markRead", "list"]), +}); +projection!(message { + "id", "from" => string, "partyRole" => string, "mine", "sentAt", "text", +}); +projection!(ask { + "id", "text", "wants" => array(want), "askedAt", "dueAt", "state" => string, + "answer" => optional(answer), "links" => links(&["answer"]), +}); +projection!(answer { "text", "additions", "formEntries", "answeredAt" }); + +fn want(value: &mut Value) -> Result<(), ()> { + let kind = value.get("kind").and_then(Value::as_str); + if value.get("formId").is_some() || (kind != Some("form") && value.get("form").is_some()) { + return Err(()); + } + let fields = match kind { + Some("answer" | "document") => &["kind"][..], + Some("form") => &["kind", "form"][..], + _ => return Err(()), + }; + members(value, fields)?; + Ok(()) +} + +projection!(application { + "applicationId", "submissionVersion", "effectDigest", "appliedBy", "appliedAt", + "resultLinks" => array(result_reference), +}); +projection!(result_reference { "recordType", "recordId", "revision" }); +projection!(application_status { + "state" => string, "mode" => string, "reason" => optional(string), + "recovery" => optional(string), "automaticRetry" => optional(automatic_retry), +}); +projection!(automatic_retry { "scheduled", "attempts", "maximumAttempts" }); +projection!(decision { "status" => string, "decidedAt", "publicReason" }); +projection!(handoff_refusal { "code" => string }); + +projection!(pub(super) review { + "id", "actionId", "actionRevision", "submissionVersion", "revision", "effectDigest", + "subject" => subject, "context" => context, "reviewable", "requestId", + "progressCode" => optional(string), "authority", "policy" => optional(policy), + "result" => optional(review_result), "handoff" => optional(handoff), +}); +pub(super) fn review_status(value: &mut Value) -> Result<(), ()> { + if value + .get("context") + .and_then(|context| context.get("additionalForms")) + .is_some() + { + return Err(()); + } + review(value) +} + +pub(super) fn review_context(value: &mut Value) -> Result<(), ()> { + if ["requestId", "result", "handoff", "progressCode"] + .iter() + .any(|key| value.get(key).is_some()) + { + return Err(()); + } + review(value) +} + +projection!(subject { "source", "subjectType", "id", "version", "digest" }); +fn context(value: &mut Value) -> Result<(), ()> { + // The retired local ID cannot stand alongside the producer's contract ID. + if value.get("id").is_some() { + return Err(()); + } + context_members(value) +} + +projection!(context_members { + "reference", "contract" => optional(exact_context_contract), "fields", + "asks" => array(review_ask), "additionalForms", "messages" => optional(thread), +}); + +fn exact_context_contract(value: &mut Value) -> Result<(), ()> { + // Keep the attested contract intact for the closed typed decoder. + value.is_object().then_some(()).ok_or(()) +} +projection!(policy { "id", "version", "digest" }); +projection!(handoff { "state" => string, "reason" => optional(string) }); +projection!(review_result { "state", "resultId", "completedAt", "availableUntil" }); +projection!(review_ask { + "id", "text", "wants" => array(want), "askedAt", "dueAt", "state" => string, + "answer" => optional(review_answer), +}); +projection!(review_answer { + "text", "documents" => array(review_answer_document), + "formEntries" => array(cited_form_entry), "answeredAt", +}); +projection!(review_form_entry { "id", "addedAt", "input", "contractChanged" }); + +fn cited_form_entry(value: &mut Value) -> Result<(), ()> { + form_entry_shape(value)?; + review_form_entry(value) +} + +fn form_entry_shape(value: &Value) -> Result<(), ()> { + let object = value.as_object().ok_or(())?; + let id = object.get("id").and_then(Value::as_str).ok_or(())?; + let added_at = object.get("addedAt").and_then(Value::as_str).ok_or(())?; + let valid_entry = match (object.get("input"), object.get("contractChanged")) { + (Some(Value::Object(input)), None) => (1..=16).contains(&input.len()), + (None, Some(Value::Bool(true))) => true, + _ => false, + }; + (super::canonical_proposal_id(id) && super::proposal_instant(added_at).is_some() && valid_entry) + .then_some(()) + .ok_or(()) +} +projection!(review_answer_document { + "id", "sha256", "contentType", "byteSize", "verificationStatus", + "download" => optional(review_answer_download), +}); +projection!(review_answer_download { "method", "operation", "accessProfile", "path" }); + +projection!(pub(super) task_context { "request", "proposal" => task_review_context }); + +fn task_review_context(value: &mut Value) -> Result<(), ()> { + let context = value.get("context").and_then(Value::as_object).ok_or(())?; + if ["asks", "messages", "additionalForms"] + .iter() + .any(|key| context.contains_key(*key)) + { + return Err(()); + } + review_context(value) +} + +fn batch_review_context(value: &mut Value) -> Result<(), ()> { + let context = value.get("context").and_then(Value::as_object).ok_or(())?; + if context.contains_key("asks") { + return Err(()); + } + if let Some(thread) = context.get("messages") { + thread_summary(thread)?; + } + review_context(value) +} +// The task request is an exact echo. Its closed model is shared with the +// outgoing request and its fields never pass through an additive projection. + +projection!(pub(super) review_batch { "items" => array(review_batch_item) }); +projection!(review_batch_item { "status" => string, "id", "context" => batch_review_context }); + +pub(super) fn retained_submission(value: &mut Value) -> Result<(), ()> { + if value.get("review").is_none() || value.get("application").is_none() { + return Err(()); + } + submission(value) +} + +projection!(submission { + "id", "actionId", "submissionVersion", "current", "effectDigest", + "review" => optional(review_result), "application" => optional(submission_application), + "decision" => optional(decision), "handoffRefusal" => optional(handoff_refusal), +}); +projection!(submission_application { + "state" => string, "mode" => optional(string), "reason" => optional(string), + "recovery" => optional(string), "automaticRetry" => optional(automatic_retry), + "applicationId", "appliedBy", "appliedAt", +}); 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/attachment_http_boundary.rs b/crates/registry-breg-client/tests/attachment_http_boundary.rs index f8e2fa52f2..43c88ba7dd 100644 --- a/crates/registry-breg-client/tests/attachment_http_boundary.rs +++ b/crates/registry-breg-client/tests/attachment_http_boundary.rs @@ -367,7 +367,7 @@ async fn selected_with_document( MockResponse::json(StatusCode::OK, metadata) .with_header("cache-control", "no-store") .with_header("vary", "authorization, accept"), - MockResponse::json(StatusCode::OK, document) + MockResponse::json(StatusCode::CREATED, document) .with_header("cache-control", "no-store") .with_header("vary", "authorization, accept"), ]; diff --git a/crates/registry-breg-client/tests/fixtures/ordinary-ingestion-receipt.json b/crates/registry-breg-client/tests/fixtures/ordinary-ingestion-receipt.json new file mode 100644 index 0000000000..56775763f9 --- /dev/null +++ b/crates/registry-breg-client/tests/fixtures/ordinary-ingestion-receipt.json @@ -0,0 +1,19 @@ +{ + "chunkIndex": 0, + "digest": "afd0c674539faef83a50823a16f6d14567ba387026fc7decfd70959d0f8d4655", + "replayed": true, + "erased": false, + "batch": { + "snapshot": "breg1_00000000-0000-4000-8000-000000000002", + "results": [{ + "operation": "create", + "recordId": "00000000-0000-4000-8000-000000000001", + "revisionIdentifier": "1", + "etag": "\"breg-record-v1-abcdef012345\"", + "domainData": {"label": "Example Ltd"}, + "futureItem": true + }], + "futureBatch": {"marker": 1} + }, + "futureReceipt": null +} diff --git a/crates/registry-breg-client/tests/fixtures/proposal-response-tolerance.json b/crates/registry-breg-client/tests/fixtures/proposal-response-tolerance.json new file mode 100644 index 0000000000..fef52128b6 --- /dev/null +++ b/crates/registry-breg-client/tests/fixtures/proposal-response-tolerance.json @@ -0,0 +1,1065 @@ +{ + "id": "00000000-0000-4000-8000-000000000001", + "metadata": { + "id": "proposal-lookup", + "version": "1", + "revision": "sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "metadataVersion": "2", + "recordTypes": [], + "operations": [], + "actions": [], + "proposals": { + "method": "GET", + "path": "/v1/proposals", + "accessProfiles": [ + "reader" + ], + "actions": [ + { + "actionId": "correct", + "accessProfile": "reader", + "party": "subject", + "operations": [ + "get", + "get-review-context", + "message", + "list", + "get-review-status" + ], + "readableInputs": [], + "writableInputs": [], + "readableContextFields": [] + } + ], + "get": { + "method": "GET", + "path": "/v1/proposals/{proposal_id}", + "accessProfiles": [ + "reader" + ] + } + } + }, + "cases": [ + { + "name": "additive", + "status": 200, + "body": "{\"id\":\"00000000-0000-4000-8000-000000000001\",\"actionId\":\"correct\",\"actionRevision\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"submissionVersion\":1,\"revision\":2,\"state\":\"draft\",\"links\":{\"self\":{\"method\":\"GET\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001\",\"accessProfile\":\"reader\",\"operation\":\"get\",\"futureMember\":{\"flag\":true}},\"future-relation\":{\"path\":\"https://canary.invalid\"}},\"futureMember\":{\"flag\":true},\"additionalForms\":{\"extra\":{\"id\":\"extra\",\"maximumCount\":2,\"items\":[{\"id\":\"00000000-0000-4000-8000-000000000002\",\"submissionVersion\":1,\"addedAt\":\"2026-11-27T00:00:00Z\",\"input\":{\"futureMember\":\"Declared input\"},\"futureMember\":true}],\"futureMember\":true}},\"messages\":{\"count\":1,\"unread\":1,\"lastSentAt\":\"2026-11-27T00:00:00Z\",\"items\":[{\"id\":\"00000000-0000-4000-8000-000000000002\",\"from\":\"official\",\"mine\":false,\"sentAt\":\"2026-11-27T00:00:00Z\",\"text\":\"Synthetic message\",\"futureMember\":true}],\"futureMember\":true},\"turn\":\"party\"}" + }, + { + "name": "duplicate", + "status": 200, + "body": "{\"id\":\"00000000-0000-4000-8000-000000000001\",\"actionId\":\"correct\",\"actionRevision\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"submissionVersion\":1,\"revision\":2,\"state\":\"draft\",\"turn\":\"party\",\"links\":{\"self\":{\"method\":\"GET\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001\",\"accessProfile\":\"reader\",\"operation\":\"get\",\"futureMember\":{\"flag\":true,\"flag\":false}},\"future-relation\":{\"path\":\"https://canary.invalid\"}},\"futureMember\":{\"flag\":true,\"flag\":false},\"additionalForms\":{\"extra\":{\"id\":\"extra\",\"maximumCount\":2,\"items\":[{\"id\":\"00000000-0000-4000-8000-000000000002\",\"submissionVersion\":1,\"addedAt\":\"2026-11-27T00:00:00Z\",\"input\":{\"futureMember\":\"Declared input\"},\"futureMember\":true}],\"futureMember\":true}},\"messages\":{\"count\":1,\"unread\":1,\"lastSentAt\":\"2026-11-27T00:00:00Z\",\"items\":[{\"id\":\"00000000-0000-4000-8000-000000000002\",\"from\":\"official\",\"mine\":false,\"sentAt\":\"2026-11-27T00:00:00Z\",\"text\":\"Synthetic message\",\"futureMember\":true}],\"futureMember\":true}}" + }, + { + "name": "badRequired", + "status": 200, + "body": "{\"id\":\"00000000-0000-4000-8000-000000000001\",\"actionId\":\"correct\",\"actionRevision\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"submissionVersion\":1,\"revision\":\"2\",\"state\":\"draft\",\"links\":{\"self\":{\"method\":\"GET\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001\",\"accessProfile\":\"reader\",\"operation\":\"get\",\"futureMember\":{\"flag\":true}},\"future-relation\":{\"path\":\"https://canary.invalid\"}},\"futureMember\":{\"flag\":true},\"additionalForms\":{\"extra\":{\"id\":\"extra\",\"maximumCount\":2,\"items\":[{\"id\":\"00000000-0000-4000-8000-000000000002\",\"submissionVersion\":1,\"addedAt\":\"2026-11-27T00:00:00Z\",\"input\":{\"futureMember\":\"Declared input\"},\"futureMember\":true}],\"futureMember\":true}},\"messages\":{\"count\":1,\"unread\":1,\"lastSentAt\":\"2026-11-27T00:00:00Z\",\"items\":[{\"id\":\"00000000-0000-4000-8000-000000000002\",\"from\":\"official\",\"mine\":false,\"sentAt\":\"2026-11-27T00:00:00Z\",\"text\":\"Synthetic message\",\"futureMember\":true}],\"futureMember\":true},\"turn\":\"party\"}" + }, + { + "name": "objectState", + "status": 200, + "body": "{\"id\":\"00000000-0000-4000-8000-000000000001\",\"actionId\":\"correct\",\"actionRevision\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"submissionVersion\":1,\"revision\":2,\"state\":{\"draft\":null},\"links\":{\"self\":{\"method\":\"GET\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001\",\"accessProfile\":\"reader\",\"operation\":\"get\"}},\"turn\":\"party\"}" + }, + { + "name": "objectStatus", + "status": 200, + "body": "{\"id\":\"00000000-0000-4000-8000-000000000001\",\"actionId\":\"correct\",\"actionRevision\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"submissionVersion\":1,\"revision\":2,\"state\":\"draft\",\"links\":{\"self\":{\"method\":\"GET\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001\",\"accessProfile\":\"reader\",\"operation\":\"get\"}},\"status\":{\"draft\":null},\"turn\":\"party\"}" + }, + { + "name": "objectTurn", + "status": 200, + "body": "{\"id\":\"00000000-0000-4000-8000-000000000001\",\"actionId\":\"correct\",\"actionRevision\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"submissionVersion\":1,\"revision\":2,\"state\":\"draft\",\"links\":{\"self\":{\"method\":\"GET\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001\",\"accessProfile\":\"reader\",\"operation\":\"get\"}},\"turn\":{\"party\":null}}" + }, + { + "name": "positionalLink", + "status": 200, + "body": "{\"id\":\"00000000-0000-4000-8000-000000000001\",\"actionId\":\"correct\",\"actionRevision\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"submissionVersion\":1,\"revision\":2,\"state\":\"draft\",\"links\":{\"self\":[\"GET\",\"/v1/proposals/00000000-0000-4000-8000-000000000001\",\"reader\",null,\"get\",null]},\"turn\":\"party\"}" + }, + { + "name": "objectMessageSide", + "status": 200, + "body": "{\"id\":\"00000000-0000-4000-8000-000000000001\",\"actionId\":\"correct\",\"actionRevision\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"submissionVersion\":1,\"revision\":2,\"state\":\"draft\",\"links\":{\"self\":{\"method\":\"GET\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001\",\"accessProfile\":\"reader\",\"operation\":\"get\"}},\"messages\":{\"count\":1,\"unread\":1,\"lastSentAt\":\"2026-11-27T00:00:00Z\",\"items\":[{\"id\":\"00000000-0000-4000-8000-000000000002\",\"from\":{\"official\":null},\"mine\":false,\"sentAt\":\"2026-11-27T00:00:00Z\",\"text\":\"Synthetic message\"}]},\"turn\":\"party\"}" + }, + { + "name": "unknown", + "status": 422, + "body": "{\"type\":\"https://id.registrystack.org/problems/registry-breg/future/refused\",\"title\":\"Synthetic refusal\",\"status\":422,\"detail\":\"Synthetic detail\",\"code\":\"future.refused\",\"traceId\":\"4bf92f3577b34da6a3ce929d0e0e4736\",\"futureMember\":{\"flag\":true}}" + }, + { + "name": "unknownServerError", + "status": 503, + "body": "{\"type\":\"https://id.registrystack.org/problems/registry-breg/future/refused\",\"title\":\"Reworded refusal\",\"status\":503,\"detail\":\"Reworded detail\",\"code\":\"future.refused\",\"traceId\":\"4bf92f3577b34da6a3ce929d0e0e4736\",\"futureMember\":{\"flag\":true}}" + }, + { + "name": "badCode", + "status": 422, + "body": "{\"type\":\"https://id.registrystack.org/problems/registry-breg/future//refused\",\"title\":\"Synthetic refusal\",\"status\":422,\"detail\":\"Synthetic detail\",\"code\":\"future..refused\",\"traceId\":\"4bf92f3577b34da6a3ce929d0e0e4736\",\"futureMember\":{\"flag\":true}}" + }, + { + "name": "duplicateProblem", + "status": 422, + "body": "{\"type\":\"https://id.registrystack.org/problems/registry-breg/future/refused\",\"title\":\"Synthetic refusal\",\"status\":422,\"detail\":\"Synthetic detail\",\"code\":\"future.refused\",\"traceId\":\"4bf92f3577b34da6a3ce929d0e0e4736\",\"futureMember\":{\"flag\":true,\"flag\":false}}" + }, + { + "name": "legacyPlanRefusal", + "status": 400, + "body": "{\"type\":\"https://id.registrystack.org/problems/registry-breg/request/plan_refused\",\"title\":\"Synthetic refusal\",\"status\":400,\"detail\":\"Synthetic detail\",\"code\":\"request.plan_refused\",\"traceId\":\"4bf92f3577b34da6a3ce929d0e0e4736\",\"futureMember\":{\"flag\":true}}" + }, + { + "name": "rewordedKnown", + "status": 404, + "body": "{\"type\":\"https://id.registrystack.org/problems/registry-breg/resource/not-found\",\"title\":\"Synthetic refusal\",\"status\":404,\"detail\":\"Synthetic detail\",\"code\":\"resource.not-found\",\"traceId\":\"4bf92f3577b34da6a3ce929d0e0e4736\",\"futureMember\":{\"flag\":true}}" + }, + { + "name": "contradictoryKnown", + "status": 422, + "body": "{\"type\":\"https://id.registrystack.org/problems/registry-breg/resource/not-found\",\"title\":\"Synthetic refusal\",\"status\":422,\"detail\":\"Synthetic detail\",\"code\":\"resource.not-found\",\"traceId\":\"4bf92f3577b34da6a3ce929d0e0e4736\",\"futureMember\":{\"flag\":true}}" + }, + { + "name": "mismatchedType", + "status": 422, + "body": "{\"type\":\"https://id.registrystack.org/problems/registry-breg/future/other\",\"title\":\"Synthetic refusal\",\"status\":422,\"detail\":\"Synthetic detail\",\"code\":\"future.refused\",\"traceId\":\"4bf92f3577b34da6a3ce929d0e0e4736\",\"futureMember\":{\"flag\":true}}" + }, + { + "name": "overlongCode", + "status": 422, + "body": "{\"type\":\"https://id.registrystack.org/problems/registry-breg/future/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"title\":\"Synthetic refusal\",\"status\":422,\"detail\":\"Synthetic detail\",\"code\":\"future.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"traceId\":\"4bf92f3577b34da6a3ce929d0e0e4736\",\"futureMember\":{\"flag\":true}}" + }, + { + "name": "missingTurn", + "status": 200, + "body": "{\"id\":\"00000000-0000-4000-8000-000000000001\",\"actionId\":\"correct\",\"actionRevision\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"submissionVersion\":1,\"revision\":2,\"state\":\"submitted\",\"links\":{\"self\":{\"method\":\"GET\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001\",\"accessProfile\":\"reader\",\"operation\":\"get\"}},\"additionalForms\":{\"extra\":{\"id\":\"extra\",\"maximumCount\":2,\"items\":[{\"id\":\"00000000-0000-4000-8000-000000000002\",\"submissionVersion\":1,\"addedAt\":\"2026-11-27T00:00:00Z\",\"input\":{\"futureMember\":\"Declared input\"}}]}},\"messages\":{\"count\":1,\"unread\":1,\"lastSentAt\":\"2026-11-27T00:00:00Z\",\"items\":[{\"id\":\"00000000-0000-4000-8000-000000000002\",\"from\":\"official\",\"mine\":false,\"sentAt\":\"2026-11-27T00:00:00Z\",\"text\":\"Synthetic message\"}],\"links\":{\"list\":{\"method\":\"GET\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":2}},\"message\":{\"method\":\"POST\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":2},\"ifMatch\":\"\\\"condition\\\"\"}}},\"effectDigest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"}", + "route": "get", + "accept": false + }, + { + "name": "nullTurn", + "status": 200, + "body": "{\"id\":\"00000000-0000-4000-8000-000000000001\",\"actionId\":\"correct\",\"actionRevision\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"submissionVersion\":1,\"revision\":2,\"state\":\"submitted\",\"links\":{\"self\":{\"method\":\"GET\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001\",\"accessProfile\":\"reader\",\"operation\":\"get\"}},\"additionalForms\":{\"extra\":{\"id\":\"extra\",\"maximumCount\":2,\"items\":[{\"id\":\"00000000-0000-4000-8000-000000000002\",\"submissionVersion\":1,\"addedAt\":\"2026-11-27T00:00:00Z\",\"input\":{\"futureMember\":\"Declared input\"}}]}},\"messages\":{\"count\":1,\"unread\":1,\"lastSentAt\":\"2026-11-27T00:00:00Z\",\"items\":[{\"id\":\"00000000-0000-4000-8000-000000000002\",\"from\":\"official\",\"mine\":false,\"sentAt\":\"2026-11-27T00:00:00Z\",\"text\":\"Synthetic message\"}],\"links\":{\"list\":{\"method\":\"GET\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":2}},\"message\":{\"method\":\"POST\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":2},\"ifMatch\":\"\\\"condition\\\"\"}}},\"turn\":null,\"effectDigest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"}", + "route": "get", + "accept": false + }, + { + "name": "emptyPageLinks", + "status": 200, + "body": "{\"items\":[],\"links\":{}}", + "route": "page", + "accept": true + }, + { + "name": "additivePage", + "status": 200, + "body": "{\"items\":[{\"id\":\"00000000-0000-4000-8000-000000000002\",\"from\":\"official\",\"mine\":false,\"sentAt\":\"2026-11-27T00:00:00Z\",\"text\":\"Synthetic message\",\"futureMember\":true}],\"links\":{\"list\":{\"method\":\"GET\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":2}},\"future\":[]},\"futureMember\":true}", + "route": "page", + "accept": true + }, + { + "name": "missingPageLinks", + "status": 200, + "body": "{\"items\":[]}", + "route": "page", + "accept": false + }, + { + "name": "invalidPageMethod", + "status": 200, + "body": "{\"items\":[],\"links\":{\"list\":{\"method\":\"POST\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":2}}}}", + "route": "page", + "accept": false + }, + { + "name": "invalidPagePath", + "status": 200, + "body": "{\"items\":[],\"links\":{\"list\":{\"method\":\"GET\",\"path\":\"/v1/proposals/other/messages\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":2}}}}", + "route": "page", + "accept": false + }, + { + "name": "unkeyedPageCondition", + "status": 200, + "body": "{\"items\":[],\"links\":{\"list\":{\"method\":\"GET\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":2},\"ifMatch\":\"\\\"condition\\\"\"}}}", + "route": "page", + "accept": false + }, + { + "name": "missingPageCondition", + "status": 200, + "body": "{\"items\":[],\"links\":{\"message\":{\"method\":\"POST\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":2}}}}", + "route": "page", + "accept": false + }, + { + "name": "nullContextrequestId", + "status": 200, + "body": "{\"id\":\"00000000-0000-4000-8000-000000000001\",\"actionId\":\"correct\",\"actionRevision\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"submissionVersion\":1,\"revision\":2,\"effectDigest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"reviewable\":true,\"subject\":{\"source\":\"proposal-lookup\",\"subjectType\":\"proposal\",\"id\":\"00000000-0000-4000-8000-000000000001\",\"version\":\"1\",\"digest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"},\"context\":{\"reference\":\"opaque\",\"contract\":{\"id\":\"urn:registry:breg:review-context:proposal-lookup:correct:review\",\"revision\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"schemaDigest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"},\"fields\":{},\"messages\":{\"count\":1,\"unread\":1,\"lastSentAt\":\"2026-11-27T00:00:00Z\",\"items\":[{\"id\":\"00000000-0000-4000-8000-000000000002\",\"from\":\"official\",\"mine\":false,\"sentAt\":\"2026-11-27T00:00:00Z\",\"text\":\"Synthetic message\"}],\"links\":{\"list\":{\"method\":\"GET\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":2}},\"message\":{\"method\":\"POST\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":2},\"ifMatch\":\"\\\"condition\\\"\"}}}},\"requestId\":null}", + "route": "context", + "accept": false + }, + { + "name": "nullContextresult", + "status": 200, + "body": "{\"id\":\"00000000-0000-4000-8000-000000000001\",\"actionId\":\"correct\",\"actionRevision\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"submissionVersion\":1,\"revision\":2,\"effectDigest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"reviewable\":true,\"subject\":{\"source\":\"proposal-lookup\",\"subjectType\":\"proposal\",\"id\":\"00000000-0000-4000-8000-000000000001\",\"version\":\"1\",\"digest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"},\"context\":{\"reference\":\"opaque\",\"contract\":{\"id\":\"urn:registry:breg:review-context:proposal-lookup:correct:review\",\"revision\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"schemaDigest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"},\"fields\":{},\"messages\":{\"count\":1,\"unread\":1,\"lastSentAt\":\"2026-11-27T00:00:00Z\",\"items\":[{\"id\":\"00000000-0000-4000-8000-000000000002\",\"from\":\"official\",\"mine\":false,\"sentAt\":\"2026-11-27T00:00:00Z\",\"text\":\"Synthetic message\"}],\"links\":{\"list\":{\"method\":\"GET\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":2}},\"message\":{\"method\":\"POST\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":2},\"ifMatch\":\"\\\"condition\\\"\"}}}},\"result\":null}", + "route": "context", + "accept": false + }, + { + "name": "nullContexthandoff", + "status": 200, + "body": "{\"id\":\"00000000-0000-4000-8000-000000000001\",\"actionId\":\"correct\",\"actionRevision\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"submissionVersion\":1,\"revision\":2,\"effectDigest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"reviewable\":true,\"subject\":{\"source\":\"proposal-lookup\",\"subjectType\":\"proposal\",\"id\":\"00000000-0000-4000-8000-000000000001\",\"version\":\"1\",\"digest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"},\"context\":{\"reference\":\"opaque\",\"contract\":{\"id\":\"urn:registry:breg:review-context:proposal-lookup:correct:review\",\"revision\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"schemaDigest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"},\"fields\":{},\"messages\":{\"count\":1,\"unread\":1,\"lastSentAt\":\"2026-11-27T00:00:00Z\",\"items\":[{\"id\":\"00000000-0000-4000-8000-000000000002\",\"from\":\"official\",\"mine\":false,\"sentAt\":\"2026-11-27T00:00:00Z\",\"text\":\"Synthetic message\"}],\"links\":{\"list\":{\"method\":\"GET\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":2}},\"message\":{\"method\":\"POST\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":2},\"ifMatch\":\"\\\"condition\\\"\"}}}},\"handoff\":null}", + "route": "context", + "accept": false + }, + { + "name": "nullContextprogressCode", + "status": 200, + "body": "{\"id\":\"00000000-0000-4000-8000-000000000001\",\"actionId\":\"correct\",\"actionRevision\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"submissionVersion\":1,\"revision\":2,\"effectDigest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"reviewable\":true,\"subject\":{\"source\":\"proposal-lookup\",\"subjectType\":\"proposal\",\"id\":\"00000000-0000-4000-8000-000000000001\",\"version\":\"1\",\"digest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"},\"context\":{\"reference\":\"opaque\",\"contract\":{\"id\":\"urn:registry:breg:review-context:proposal-lookup:correct:review\",\"revision\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"schemaDigest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"},\"fields\":{},\"messages\":{\"count\":1,\"unread\":1,\"lastSentAt\":\"2026-11-27T00:00:00Z\",\"items\":[{\"id\":\"00000000-0000-4000-8000-000000000002\",\"from\":\"official\",\"mine\":false,\"sentAt\":\"2026-11-27T00:00:00Z\",\"text\":\"Synthetic message\"}],\"links\":{\"list\":{\"method\":\"GET\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":2}},\"message\":{\"method\":\"POST\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":2},\"ifMatch\":\"\\\"condition\\\"\"}}}},\"progressCode\":null}", + "route": "context", + "accept": false + }, + { + "name": "validCitedForm", + "status": 200, + "body": "{\"id\":\"00000000-0000-4000-8000-000000000001\",\"actionId\":\"correct\",\"actionRevision\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"submissionVersion\":1,\"revision\":2,\"effectDigest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"reviewable\":true,\"subject\":{\"source\":\"proposal-lookup\",\"subjectType\":\"proposal\",\"id\":\"00000000-0000-4000-8000-000000000001\",\"version\":\"1\",\"digest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"},\"context\":{\"reference\":\"opaque\",\"contract\":{\"id\":\"urn:registry:breg:review-context:proposal-lookup:correct:review\",\"revision\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"schemaDigest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"},\"fields\":{},\"messages\":{\"count\":1,\"unread\":1,\"lastSentAt\":\"2026-11-27T00:00:00Z\",\"items\":[{\"id\":\"00000000-0000-4000-8000-000000000002\",\"from\":\"official\",\"mine\":false,\"sentAt\":\"2026-11-27T00:00:00Z\",\"text\":\"Synthetic message\"}],\"links\":{\"list\":{\"method\":\"GET\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":2}},\"message\":{\"method\":\"POST\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":2},\"ifMatch\":\"\\\"condition\\\"\"}}},\"asks\":[{\"id\":\"00000000-0000-4000-8000-000000000005\",\"text\":\"Please provide a file.\",\"wants\":[{\"kind\":\"form\",\"form\":\"extra\"}],\"askedAt\":\"2026-11-26T00:00:00Z\",\"state\":\"answered\",\"answer\":{\"documents\":[],\"formEntries\":[{\"id\":\"00000000-0000-4000-8000-000000000002\",\"addedAt\":\"2026-11-27T00:00:00Z\",\"input\":{\"futureMember\":\"Declared input\"},\"futureMember\":true}],\"answeredAt\":\"2026-11-27T00:00:00Z\"}}]},\"authority\":\"casework\",\"policy\":{\"id\":\"policy\",\"version\":\"one\",\"digest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"}}", + "route": "context", + "accept": true + }, + { + "name": "citedChangedContract", + "status": 200, + "body": "{\"id\":\"00000000-0000-4000-8000-000000000001\",\"actionId\":\"correct\",\"actionRevision\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"submissionVersion\":1,\"revision\":2,\"effectDigest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"reviewable\":true,\"subject\":{\"source\":\"proposal-lookup\",\"subjectType\":\"proposal\",\"id\":\"00000000-0000-4000-8000-000000000001\",\"version\":\"1\",\"digest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"},\"context\":{\"reference\":\"opaque\",\"contract\":{\"id\":\"urn:registry:breg:review-context:proposal-lookup:correct:review\",\"revision\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"schemaDigest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"},\"fields\":{},\"messages\":{\"count\":1,\"unread\":1,\"lastSentAt\":\"2026-11-27T00:00:00Z\",\"items\":[{\"id\":\"00000000-0000-4000-8000-000000000002\",\"from\":\"official\",\"mine\":false,\"sentAt\":\"2026-11-27T00:00:00Z\",\"text\":\"Synthetic message\"}],\"links\":{\"list\":{\"method\":\"GET\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":2}},\"message\":{\"method\":\"POST\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":2},\"ifMatch\":\"\\\"condition\\\"\"}}},\"asks\":[{\"id\":\"00000000-0000-4000-8000-000000000005\",\"text\":\"Please provide a file.\",\"wants\":[{\"kind\":\"form\",\"form\":\"extra\"}],\"askedAt\":\"2026-11-26T00:00:00Z\",\"state\":\"answered\",\"answer\":{\"documents\":[],\"formEntries\":[{\"id\":\"00000000-0000-4000-8000-000000000002\",\"addedAt\":\"2026-11-27T00:00:00Z\",\"contractChanged\":true}],\"answeredAt\":\"2026-11-27T00:00:00Z\"}}]},\"authority\":\"casework\",\"policy\":{\"id\":\"policy\",\"version\":\"one\",\"digest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"}}", + "route": "context", + "accept": true + }, + { + "name": "emptyCitedForm", + "status": 200, + "body": "{\"id\":\"00000000-0000-4000-8000-000000000001\",\"actionId\":\"correct\",\"actionRevision\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"submissionVersion\":1,\"revision\":2,\"effectDigest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"reviewable\":true,\"subject\":{\"source\":\"proposal-lookup\",\"subjectType\":\"proposal\",\"id\":\"00000000-0000-4000-8000-000000000001\",\"version\":\"1\",\"digest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"},\"context\":{\"reference\":\"opaque\",\"contract\":{\"id\":\"urn:registry:breg:review-context:proposal-lookup:correct:review\",\"revision\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"schemaDigest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"},\"fields\":{},\"messages\":{\"count\":1,\"unread\":1,\"lastSentAt\":\"2026-11-27T00:00:00Z\",\"items\":[{\"id\":\"00000000-0000-4000-8000-000000000002\",\"from\":\"official\",\"mine\":false,\"sentAt\":\"2026-11-27T00:00:00Z\",\"text\":\"Synthetic message\"}],\"links\":{\"list\":{\"method\":\"GET\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":2}},\"message\":{\"method\":\"POST\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":2},\"ifMatch\":\"\\\"condition\\\"\"}}},\"asks\":[{\"id\":\"00000000-0000-4000-8000-000000000005\",\"text\":\"Please provide a file.\",\"wants\":[{\"kind\":\"form\",\"form\":\"extra\"}],\"askedAt\":\"2026-11-26T00:00:00Z\",\"state\":\"answered\",\"answer\":{\"documents\":[],\"formEntries\":[{}],\"answeredAt\":\"2026-11-27T00:00:00Z\"}}]},\"authority\":\"casework\",\"policy\":{\"id\":\"policy\",\"version\":\"one\",\"digest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"}}", + "route": "context", + "accept": false + }, + { + "name": "invalidCitedInput", + "status": 200, + "body": "{\"id\":\"00000000-0000-4000-8000-000000000001\",\"actionId\":\"correct\",\"actionRevision\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"submissionVersion\":1,\"revision\":2,\"effectDigest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"reviewable\":true,\"subject\":{\"source\":\"proposal-lookup\",\"subjectType\":\"proposal\",\"id\":\"00000000-0000-4000-8000-000000000001\",\"version\":\"1\",\"digest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"},\"context\":{\"reference\":\"opaque\",\"contract\":{\"id\":\"urn:registry:breg:review-context:proposal-lookup:correct:review\",\"revision\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"schemaDigest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"},\"fields\":{},\"messages\":{\"count\":1,\"unread\":1,\"lastSentAt\":\"2026-11-27T00:00:00Z\",\"items\":[{\"id\":\"00000000-0000-4000-8000-000000000002\",\"from\":\"official\",\"mine\":false,\"sentAt\":\"2026-11-27T00:00:00Z\",\"text\":\"Synthetic message\"}],\"links\":{\"list\":{\"method\":\"GET\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":2}},\"message\":{\"method\":\"POST\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":2},\"ifMatch\":\"\\\"condition\\\"\"}}},\"asks\":[{\"id\":\"00000000-0000-4000-8000-000000000005\",\"text\":\"Please provide a file.\",\"wants\":[{\"kind\":\"form\",\"form\":\"extra\"}],\"askedAt\":\"2026-11-26T00:00:00Z\",\"state\":\"answered\",\"answer\":{\"documents\":[],\"formEntries\":[{\"id\":\"00000000-0000-4000-8000-000000000002\",\"addedAt\":\"2026-11-27T00:00:00Z\",\"input\":[]}],\"answeredAt\":\"2026-11-27T00:00:00Z\"}}]},\"authority\":\"casework\",\"policy\":{\"id\":\"policy\",\"version\":\"one\",\"digest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"}}", + "route": "context", + "accept": false + }, + { + "name": "emptyCitedInput", + "status": 200, + "body": "{\"id\":\"00000000-0000-4000-8000-000000000001\",\"actionId\":\"correct\",\"actionRevision\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"submissionVersion\":1,\"revision\":2,\"effectDigest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"reviewable\":true,\"subject\":{\"source\":\"proposal-lookup\",\"subjectType\":\"proposal\",\"id\":\"00000000-0000-4000-8000-000000000001\",\"version\":\"1\",\"digest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"},\"context\":{\"reference\":\"opaque\",\"contract\":{\"id\":\"urn:registry:breg:review-context:proposal-lookup:correct:review\",\"revision\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"schemaDigest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"},\"fields\":{},\"messages\":{\"count\":1,\"unread\":1,\"lastSentAt\":\"2026-11-27T00:00:00Z\",\"items\":[{\"id\":\"00000000-0000-4000-8000-000000000002\",\"from\":\"official\",\"mine\":false,\"sentAt\":\"2026-11-27T00:00:00Z\",\"text\":\"Synthetic message\"}],\"links\":{\"list\":{\"method\":\"GET\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":2}},\"message\":{\"method\":\"POST\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":2},\"ifMatch\":\"\\\"condition\\\"\"}}},\"asks\":[{\"id\":\"00000000-0000-4000-8000-000000000005\",\"text\":\"Please provide a file.\",\"wants\":[{\"kind\":\"form\",\"form\":\"extra\"}],\"askedAt\":\"2026-11-26T00:00:00Z\",\"state\":\"answered\",\"answer\":{\"documents\":[],\"formEntries\":[{\"id\":\"00000000-0000-4000-8000-000000000002\",\"addedAt\":\"2026-11-27T00:00:00Z\",\"input\":{}}],\"answeredAt\":\"2026-11-27T00:00:00Z\"}}]},\"authority\":\"casework\",\"policy\":{\"id\":\"policy\",\"version\":\"one\",\"digest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"}}", + "route": "context", + "accept": false + }, + { + "name": "invalidCitedTime", + "status": 200, + "body": "{\"id\":\"00000000-0000-4000-8000-000000000001\",\"actionId\":\"correct\",\"actionRevision\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"submissionVersion\":1,\"revision\":2,\"effectDigest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"reviewable\":true,\"subject\":{\"source\":\"proposal-lookup\",\"subjectType\":\"proposal\",\"id\":\"00000000-0000-4000-8000-000000000001\",\"version\":\"1\",\"digest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"},\"context\":{\"reference\":\"opaque\",\"contract\":{\"id\":\"urn:registry:breg:review-context:proposal-lookup:correct:review\",\"revision\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"schemaDigest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"},\"fields\":{},\"messages\":{\"count\":1,\"unread\":1,\"lastSentAt\":\"2026-11-27T00:00:00Z\",\"items\":[{\"id\":\"00000000-0000-4000-8000-000000000002\",\"from\":\"official\",\"mine\":false,\"sentAt\":\"2026-11-27T00:00:00Z\",\"text\":\"Synthetic message\"}],\"links\":{\"list\":{\"method\":\"GET\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":2}},\"message\":{\"method\":\"POST\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":2},\"ifMatch\":\"\\\"condition\\\"\"}}},\"asks\":[{\"id\":\"00000000-0000-4000-8000-000000000005\",\"text\":\"Please provide a file.\",\"wants\":[{\"kind\":\"form\",\"form\":\"extra\"}],\"askedAt\":\"2026-11-26T00:00:00Z\",\"state\":\"answered\",\"answer\":{\"documents\":[],\"formEntries\":[{\"id\":\"00000000-0000-4000-8000-000000000002\",\"addedAt\":\"tomorrow\",\"input\":{\"futureMember\":\"Declared input\"}}],\"answeredAt\":\"2026-11-27T00:00:00Z\"}}]},\"authority\":\"casework\",\"policy\":{\"id\":\"policy\",\"version\":\"one\",\"digest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"}}", + "route": "context", + "accept": false + }, + { + "name": "nullCitedId", + "status": 200, + "body": "{\"id\":\"00000000-0000-4000-8000-000000000001\",\"actionId\":\"correct\",\"actionRevision\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"submissionVersion\":1,\"revision\":2,\"effectDigest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"reviewable\":true,\"subject\":{\"source\":\"proposal-lookup\",\"subjectType\":\"proposal\",\"id\":\"00000000-0000-4000-8000-000000000001\",\"version\":\"1\",\"digest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"},\"context\":{\"reference\":\"opaque\",\"contract\":{\"id\":\"urn:registry:breg:review-context:proposal-lookup:correct:review\",\"revision\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"schemaDigest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"},\"fields\":{},\"messages\":{\"count\":1,\"unread\":1,\"lastSentAt\":\"2026-11-27T00:00:00Z\",\"items\":[{\"id\":\"00000000-0000-4000-8000-000000000002\",\"from\":\"official\",\"mine\":false,\"sentAt\":\"2026-11-27T00:00:00Z\",\"text\":\"Synthetic message\"}],\"links\":{\"list\":{\"method\":\"GET\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":2}},\"message\":{\"method\":\"POST\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":2},\"ifMatch\":\"\\\"condition\\\"\"}}},\"asks\":[{\"id\":\"00000000-0000-4000-8000-000000000005\",\"text\":\"Please provide a file.\",\"wants\":[{\"kind\":\"form\",\"form\":\"extra\"}],\"askedAt\":\"2026-11-26T00:00:00Z\",\"state\":\"answered\",\"answer\":{\"documents\":[],\"formEntries\":[{\"id\":null,\"addedAt\":\"2026-11-27T00:00:00Z\",\"input\":{\"futureMember\":\"Declared input\"}}],\"answeredAt\":\"2026-11-27T00:00:00Z\"}}]},\"authority\":\"casework\",\"policy\":{\"id\":\"policy\",\"version\":\"one\",\"digest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"}}", + "route": "context", + "accept": false + }, + { + "name": "bothCitedBranches", + "status": 200, + "body": "{\"id\":\"00000000-0000-4000-8000-000000000001\",\"actionId\":\"correct\",\"actionRevision\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"submissionVersion\":1,\"revision\":2,\"effectDigest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"reviewable\":true,\"subject\":{\"source\":\"proposal-lookup\",\"subjectType\":\"proposal\",\"id\":\"00000000-0000-4000-8000-000000000001\",\"version\":\"1\",\"digest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"},\"context\":{\"reference\":\"opaque\",\"contract\":{\"id\":\"urn:registry:breg:review-context:proposal-lookup:correct:review\",\"revision\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"schemaDigest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"},\"fields\":{},\"messages\":{\"count\":1,\"unread\":1,\"lastSentAt\":\"2026-11-27T00:00:00Z\",\"items\":[{\"id\":\"00000000-0000-4000-8000-000000000002\",\"from\":\"official\",\"mine\":false,\"sentAt\":\"2026-11-27T00:00:00Z\",\"text\":\"Synthetic message\"}],\"links\":{\"list\":{\"method\":\"GET\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":2}},\"message\":{\"method\":\"POST\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":2},\"ifMatch\":\"\\\"condition\\\"\"}}},\"asks\":[{\"id\":\"00000000-0000-4000-8000-000000000005\",\"text\":\"Please provide a file.\",\"wants\":[{\"kind\":\"form\",\"form\":\"extra\"}],\"askedAt\":\"2026-11-26T00:00:00Z\",\"state\":\"answered\",\"answer\":{\"documents\":[],\"formEntries\":[{\"id\":\"00000000-0000-4000-8000-000000000002\",\"addedAt\":\"2026-11-27T00:00:00Z\",\"input\":{\"futureMember\":\"Declared input\"},\"contractChanged\":true}],\"answeredAt\":\"2026-11-27T00:00:00Z\"}}]},\"authority\":\"casework\",\"policy\":{\"id\":\"policy\",\"version\":\"one\",\"digest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"}}", + "route": "context", + "accept": false + }, + { + "name": "falseCitedMarker", + "status": 200, + "body": "{\"id\":\"00000000-0000-4000-8000-000000000001\",\"actionId\":\"correct\",\"actionRevision\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"submissionVersion\":1,\"revision\":2,\"effectDigest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"reviewable\":true,\"subject\":{\"source\":\"proposal-lookup\",\"subjectType\":\"proposal\",\"id\":\"00000000-0000-4000-8000-000000000001\",\"version\":\"1\",\"digest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"},\"context\":{\"reference\":\"opaque\",\"contract\":{\"id\":\"urn:registry:breg:review-context:proposal-lookup:correct:review\",\"revision\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"schemaDigest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"},\"fields\":{},\"messages\":{\"count\":1,\"unread\":1,\"lastSentAt\":\"2026-11-27T00:00:00Z\",\"items\":[{\"id\":\"00000000-0000-4000-8000-000000000002\",\"from\":\"official\",\"mine\":false,\"sentAt\":\"2026-11-27T00:00:00Z\",\"text\":\"Synthetic message\"}],\"links\":{\"list\":{\"method\":\"GET\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":2}},\"message\":{\"method\":\"POST\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":2},\"ifMatch\":\"\\\"condition\\\"\"}}},\"asks\":[{\"id\":\"00000000-0000-4000-8000-000000000005\",\"text\":\"Please provide a file.\",\"wants\":[{\"kind\":\"form\",\"form\":\"extra\"}],\"askedAt\":\"2026-11-26T00:00:00Z\",\"state\":\"answered\",\"answer\":{\"documents\":[],\"formEntries\":[{\"id\":\"00000000-0000-4000-8000-000000000002\",\"addedAt\":\"2026-11-27T00:00:00Z\",\"contractChanged\":false}],\"answeredAt\":\"2026-11-27T00:00:00Z\"}}]},\"authority\":\"casework\",\"policy\":{\"id\":\"policy\",\"version\":\"one\",\"digest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"}}", + "route": "context", + "accept": false + }, + { + "name": "correctMessageReceipt", + "status": 200, + "body": "{\"id\":\"00000000-0000-4000-8000-000000000001\",\"actionId\":\"correct\",\"actionRevision\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"submissionVersion\":1,\"revision\":3,\"state\":\"submitted\",\"links\":{\"self\":{\"method\":\"GET\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001\",\"accessProfile\":\"reader\",\"operation\":\"get\"}},\"additionalForms\":{\"extra\":{\"id\":\"extra\",\"maximumCount\":2,\"items\":[{\"id\":\"00000000-0000-4000-8000-000000000002\",\"submissionVersion\":1,\"addedAt\":\"2026-11-27T00:00:00Z\",\"input\":{\"futureMember\":\"Declared input\"}}]}},\"messages\":{\"count\":1,\"unread\":1,\"lastSentAt\":\"2026-11-27T00:00:00Z\",\"items\":[{\"id\":\"00000000-0000-4000-8000-000000000002\",\"mine\":true,\"sentAt\":\"2026-11-27T00:00:00Z\",\"text\":\"Synthetic reply\",\"from\":\"official\"}],\"links\":{\"list\":{\"method\":\"GET\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":3}},\"message\":{\"method\":\"POST\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":3},\"ifMatch\":\"\\\"condition\\\"\"}}},\"turn\":\"official\",\"effectDigest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"}", + "route": "send", + "accept": true + }, + { + "name": "wrongMessageActionRevision", + "status": 200, + "body": "{\"id\":\"00000000-0000-4000-8000-000000000001\",\"actionId\":\"correct\",\"actionRevision\":\"sha256:bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\",\"submissionVersion\":1,\"revision\":3,\"state\":\"submitted\",\"links\":{\"self\":{\"method\":\"GET\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001\",\"accessProfile\":\"reader\",\"operation\":\"get\"}},\"additionalForms\":{\"extra\":{\"id\":\"extra\",\"maximumCount\":2,\"items\":[{\"id\":\"00000000-0000-4000-8000-000000000002\",\"submissionVersion\":1,\"addedAt\":\"2026-11-27T00:00:00Z\",\"input\":{\"futureMember\":\"Declared input\"}}]}},\"messages\":{\"count\":1,\"unread\":1,\"lastSentAt\":\"2026-11-27T00:00:00Z\",\"items\":[{\"id\":\"00000000-0000-4000-8000-000000000002\",\"mine\":true,\"sentAt\":\"2026-11-27T00:00:00Z\",\"text\":\"Synthetic reply\",\"from\":\"official\"}],\"links\":{\"list\":{\"method\":\"GET\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":3}},\"message\":{\"method\":\"POST\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":3},\"ifMatch\":\"\\\"condition\\\"\"}}},\"turn\":\"official\",\"effectDigest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"}", + "route": "send", + "accept": false + }, + { + "name": "wrongMessageEffectDigest", + "status": 200, + "body": "{\"id\":\"00000000-0000-4000-8000-000000000001\",\"actionId\":\"correct\",\"actionRevision\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"submissionVersion\":1,\"revision\":3,\"state\":\"submitted\",\"links\":{\"self\":{\"method\":\"GET\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001\",\"accessProfile\":\"reader\",\"operation\":\"get\"}},\"additionalForms\":{\"extra\":{\"id\":\"extra\",\"maximumCount\":2,\"items\":[{\"id\":\"00000000-0000-4000-8000-000000000002\",\"submissionVersion\":1,\"addedAt\":\"2026-11-27T00:00:00Z\",\"input\":{\"futureMember\":\"Declared input\"}}]}},\"messages\":{\"count\":1,\"unread\":1,\"lastSentAt\":\"2026-11-27T00:00:00Z\",\"items\":[{\"id\":\"00000000-0000-4000-8000-000000000002\",\"mine\":true,\"sentAt\":\"2026-11-27T00:00:00Z\",\"text\":\"Synthetic reply\",\"from\":\"official\"}],\"links\":{\"list\":{\"method\":\"GET\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":3}},\"message\":{\"method\":\"POST\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":3},\"ifMatch\":\"\\\"condition\\\"\"}}},\"turn\":\"official\",\"effectDigest\":\"sha256:bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\"}", + "route": "send", + "accept": false + }, + { + "name": "wrongMessageSubmission", + "status": 200, + "body": "{\"id\":\"00000000-0000-4000-8000-000000000001\",\"actionId\":\"correct\",\"actionRevision\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"submissionVersion\":2,\"revision\":3,\"state\":\"submitted\",\"links\":{\"self\":{\"method\":\"GET\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001\",\"accessProfile\":\"reader\",\"operation\":\"get\"}},\"additionalForms\":{\"extra\":{\"id\":\"extra\",\"maximumCount\":2,\"items\":[{\"id\":\"00000000-0000-4000-8000-000000000002\",\"submissionVersion\":2,\"addedAt\":\"2026-11-27T00:00:00Z\",\"input\":{\"futureMember\":\"Declared input\"}}]}},\"messages\":{\"count\":1,\"unread\":1,\"lastSentAt\":\"2026-11-27T00:00:00Z\",\"items\":[{\"id\":\"00000000-0000-4000-8000-000000000002\",\"mine\":true,\"sentAt\":\"2026-11-27T00:00:00Z\",\"text\":\"Synthetic reply\",\"from\":\"official\"}],\"links\":{\"list\":{\"method\":\"GET\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":3}},\"message\":{\"method\":\"POST\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":3},\"ifMatch\":\"\\\"condition\\\"\"}}},\"turn\":\"official\",\"effectDigest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"}", + "route": "send", + "accept": false + }, + { + "name": "listCurrentTurn", + "status": 200, + "body": "{\"items\":[{\"id\":\"00000000-0000-4000-8000-000000000001\",\"actionId\":\"correct\",\"actionRevision\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"submissionVersion\":1,\"revision\":2,\"state\":\"submitted\",\"links\":{\"self\":{\"method\":\"GET\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001\",\"accessProfile\":\"reader\",\"operation\":\"get\"}},\"additionalForms\":{\"extra\":{\"id\":\"extra\",\"maximumCount\":2,\"items\":[{\"id\":\"00000000-0000-4000-8000-000000000002\",\"submissionVersion\":1,\"addedAt\":\"2026-11-27T00:00:00Z\",\"input\":{\"futureMember\":\"Declared input\"}}]}},\"messages\":{\"count\":1,\"unread\":1,\"lastSentAt\":\"2026-11-27T00:00:00Z\"},\"turn\":\"official\",\"effectDigest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"futureMember\":true}],\"futureMember\":true}", + "route": "list", + "accept": true + }, + { + "name": "listMissingTurn", + "status": 200, + "body": "{\"items\":[{\"id\":\"00000000-0000-4000-8000-000000000001\",\"actionId\":\"correct\",\"actionRevision\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"submissionVersion\":1,\"revision\":2,\"state\":\"submitted\",\"links\":{\"self\":{\"method\":\"GET\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001\",\"accessProfile\":\"reader\",\"operation\":\"get\"}},\"additionalForms\":{\"extra\":{\"id\":\"extra\",\"maximumCount\":2,\"items\":[{\"id\":\"00000000-0000-4000-8000-000000000002\",\"submissionVersion\":1,\"addedAt\":\"2026-11-27T00:00:00Z\",\"input\":{\"futureMember\":\"Declared input\"}}]}},\"messages\":{\"count\":1,\"unread\":1,\"lastSentAt\":\"2026-11-27T00:00:00Z\"},\"effectDigest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"}],\"futureMember\":true}", + "route": "list", + "accept": false + }, + { + "name": "listNullTurn", + "status": 200, + "body": "{\"items\":[{\"id\":\"00000000-0000-4000-8000-000000000001\",\"actionId\":\"correct\",\"actionRevision\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"submissionVersion\":1,\"revision\":2,\"state\":\"submitted\",\"links\":{\"self\":{\"method\":\"GET\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001\",\"accessProfile\":\"reader\",\"operation\":\"get\"}},\"additionalForms\":{\"extra\":{\"id\":\"extra\",\"maximumCount\":2,\"items\":[{\"id\":\"00000000-0000-4000-8000-000000000002\",\"submissionVersion\":1,\"addedAt\":\"2026-11-27T00:00:00Z\",\"input\":{\"futureMember\":\"Declared input\"}}]}},\"messages\":{\"count\":1,\"unread\":1,\"lastSentAt\":\"2026-11-27T00:00:00Z\"},\"turn\":null,\"effectDigest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"}],\"futureMember\":true}", + "route": "list", + "accept": false + }, + { + "name": "promotedCurrentTurn", + "status": 200, + "body": "{\"id\":\"00000000-0000-4000-8000-000000000001\",\"actionId\":\"correct\",\"actionRevision\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"submissionVersion\":1,\"revision\":2,\"state\":\"submitted\",\"links\":{\"self\":{\"method\":\"GET\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001\",\"accessProfile\":\"reader\",\"operation\":\"get\"}},\"additionalForms\":{\"extra\":{\"id\":\"extra\",\"maximumCount\":2,\"items\":[{\"id\":\"00000000-0000-4000-8000-000000000002\",\"submissionVersion\":1,\"addedAt\":\"2026-11-27T00:00:00Z\",\"input\":{\"futureMember\":\"Declared input\"}}]}},\"messages\":{\"count\":1,\"unread\":1,\"lastSentAt\":\"2026-11-27T00:00:00Z\",\"items\":[{\"id\":\"00000000-0000-4000-8000-000000000002\",\"from\":\"official\",\"mine\":false,\"sentAt\":\"2026-11-27T00:00:00Z\",\"text\":\"Synthetic message\"}],\"links\":{\"list\":{\"method\":\"GET\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":2}},\"message\":{\"method\":\"POST\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":2},\"ifMatch\":\"\\\"condition\\\"\"}}},\"turn\":\"official\",\"effectDigest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"futureMember\":true}", + "route": "promoted", + "accept": true + }, + { + "name": "promotedMissingTurn", + "status": 200, + "body": "{\"id\":\"00000000-0000-4000-8000-000000000001\",\"actionId\":\"correct\",\"actionRevision\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"submissionVersion\":1,\"revision\":2,\"state\":\"submitted\",\"links\":{\"self\":{\"method\":\"GET\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001\",\"accessProfile\":\"reader\",\"operation\":\"get\"}},\"additionalForms\":{\"extra\":{\"id\":\"extra\",\"maximumCount\":2,\"items\":[{\"id\":\"00000000-0000-4000-8000-000000000002\",\"submissionVersion\":1,\"addedAt\":\"2026-11-27T00:00:00Z\",\"input\":{\"futureMember\":\"Declared input\"}}]}},\"messages\":{\"count\":1,\"unread\":1,\"lastSentAt\":\"2026-11-27T00:00:00Z\",\"items\":[{\"id\":\"00000000-0000-4000-8000-000000000002\",\"from\":\"official\",\"mine\":false,\"sentAt\":\"2026-11-27T00:00:00Z\",\"text\":\"Synthetic message\"}],\"links\":{\"list\":{\"method\":\"GET\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":2}},\"message\":{\"method\":\"POST\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":2},\"ifMatch\":\"\\\"condition\\\"\"}}},\"effectDigest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"}", + "route": "promoted", + "accept": false + }, + { + "name": "promotedNullTurn", + "status": 200, + "body": "{\"id\":\"00000000-0000-4000-8000-000000000001\",\"actionId\":\"correct\",\"actionRevision\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"submissionVersion\":1,\"revision\":2,\"state\":\"submitted\",\"links\":{\"self\":{\"method\":\"GET\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001\",\"accessProfile\":\"reader\",\"operation\":\"get\"}},\"additionalForms\":{\"extra\":{\"id\":\"extra\",\"maximumCount\":2,\"items\":[{\"id\":\"00000000-0000-4000-8000-000000000002\",\"submissionVersion\":1,\"addedAt\":\"2026-11-27T00:00:00Z\",\"input\":{\"futureMember\":\"Declared input\"}}]}},\"messages\":{\"count\":1,\"unread\":1,\"lastSentAt\":\"2026-11-27T00:00:00Z\",\"items\":[{\"id\":\"00000000-0000-4000-8000-000000000002\",\"from\":\"official\",\"mine\":false,\"sentAt\":\"2026-11-27T00:00:00Z\",\"text\":\"Synthetic message\"}],\"links\":{\"list\":{\"method\":\"GET\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":2}},\"message\":{\"method\":\"POST\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":2},\"ifMatch\":\"\\\"condition\\\"\"}}},\"turn\":null,\"effectDigest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"}", + "route": "promoted", + "accept": false + }, + { + "name": "futureSuffixRefused", + "status": 422, + "body": "{\"type\":\"https://id.registrystack.org/problems/registry-breg/future1/refused-2\",\"title\":\"Synthetic refusal\",\"status\":422,\"detail\":\"Synthetic detail\",\"code\":\"future1.refused-2\",\"traceId\":\"4bf92f3577b34da6a3ce929d0e0e4736\",\"futureMember\":{\"flag\":true}}", + "accept": true + }, + { + "name": "futureSuffixServerError", + "status": 503, + "body": "{\"type\":\"https://id.registrystack.org/problems/registry-breg/future2/refused--2-\",\"title\":\"Synthetic refusal\",\"status\":503,\"detail\":\"Synthetic detail\",\"code\":\"future2.refused--2-\",\"traceId\":\"4bf92f3577b34da6a3ce929d0e0e4736\",\"futureMember\":{\"flag\":true}}", + "accept": true + }, + { + "name": "futureFirstDigit", + "status": 422, + "body": "{\"type\":\"https://id.registrystack.org/problems/registry-breg/1future/refused\",\"title\":\"Synthetic refusal\",\"status\":422,\"detail\":\"Synthetic detail\",\"code\":\"1future.refused\",\"traceId\":\"4bf92f3577b34da6a3ce929d0e0e4736\",\"futureMember\":{\"flag\":true}}", + "accept": false + }, + { + "name": "futureSecondDigit", + "status": 422, + "body": "{\"type\":\"https://id.registrystack.org/problems/registry-breg/future/2refused\",\"title\":\"Synthetic refusal\",\"status\":422,\"detail\":\"Synthetic detail\",\"code\":\"future.2refused\",\"traceId\":\"4bf92f3577b34da6a3ce929d0e0e4736\",\"futureMember\":{\"flag\":true}}", + "accept": false + }, + { + "name": "futureLeadingHyphen", + "status": 422, + "body": "{\"type\":\"https://id.registrystack.org/problems/registry-breg/future/-refused\",\"title\":\"Synthetic refusal\",\"status\":422,\"detail\":\"Synthetic detail\",\"code\":\"future.-refused\",\"traceId\":\"4bf92f3577b34da6a3ce929d0e0e4736\",\"futureMember\":{\"flag\":true}}", + "accept": false + }, + { + "name": "unreadGetin-review", + "route": "get", + "status": 200, + "body": "{\"id\":\"00000000-0000-4000-8000-000000000001\",\"actionId\":\"correct\",\"actionRevision\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"submissionVersion\":1,\"revision\":2,\"state\":\"submitted\",\"links\":{\"self\":{\"method\":\"GET\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001\",\"accessProfile\":\"reader\",\"operation\":\"get\"}},\"additionalForms\":{\"extra\":{\"id\":\"extra\",\"maximumCount\":2,\"items\":[{\"id\":\"00000000-0000-4000-8000-000000000002\",\"submissionVersion\":1,\"addedAt\":\"2026-11-27T00:00:00Z\",\"input\":{\"futureMember\":\"Declared input\"}}]}},\"messages\":{\"count\":1,\"unread\":1,\"lastSentAt\":\"2026-11-27T00:00:00Z\",\"items\":[{\"id\":\"00000000-0000-4000-8000-000000000002\",\"from\":\"official\",\"mine\":false,\"sentAt\":\"2026-11-27T00:00:00Z\",\"text\":\"Synthetic message\"}],\"links\":{\"list\":{\"method\":\"GET\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":2}},\"message\":{\"method\":\"POST\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":2},\"ifMatch\":\"\\\"condition\\\"\"},\"markRead\":{\"method\":\"POST\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages/read\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":2}}}},\"turn\":\"party\",\"effectDigest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"status\":\"in-review\"}", + "accept": true + }, + { + "name": "unreadListin-review", + "route": "list", + "status": 200, + "body": "{\"items\":[{\"id\":\"00000000-0000-4000-8000-000000000001\",\"actionId\":\"correct\",\"actionRevision\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"submissionVersion\":1,\"revision\":2,\"state\":\"submitted\",\"links\":{\"self\":{\"method\":\"GET\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001\",\"accessProfile\":\"reader\",\"operation\":\"get\"}},\"additionalForms\":{\"extra\":{\"id\":\"extra\",\"maximumCount\":2,\"items\":[{\"id\":\"00000000-0000-4000-8000-000000000002\",\"submissionVersion\":1,\"addedAt\":\"2026-11-27T00:00:00Z\",\"input\":{\"futureMember\":\"Declared input\"}}]}},\"messages\":{\"count\":1,\"unread\":1,\"lastSentAt\":\"2026-11-27T00:00:00Z\"},\"turn\":\"party\",\"effectDigest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"status\":\"in-review\"}]}", + "accept": true + }, + { + "name": "unreadGetapproved", + "route": "get", + "status": 200, + "body": "{\"id\":\"00000000-0000-4000-8000-000000000001\",\"actionId\":\"correct\",\"actionRevision\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"submissionVersion\":1,\"revision\":2,\"state\":\"submitted\",\"links\":{\"self\":{\"method\":\"GET\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001\",\"accessProfile\":\"reader\",\"operation\":\"get\"}},\"additionalForms\":{\"extra\":{\"id\":\"extra\",\"maximumCount\":2,\"items\":[{\"id\":\"00000000-0000-4000-8000-000000000002\",\"submissionVersion\":1,\"addedAt\":\"2026-11-27T00:00:00Z\",\"input\":{\"futureMember\":\"Declared input\"}}]}},\"messages\":{\"count\":1,\"unread\":1,\"lastSentAt\":\"2026-11-27T00:00:00Z\",\"items\":[{\"id\":\"00000000-0000-4000-8000-000000000002\",\"from\":\"official\",\"mine\":false,\"sentAt\":\"2026-11-27T00:00:00Z\",\"text\":\"Synthetic message\"}],\"links\":{\"list\":{\"method\":\"GET\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":2}},\"message\":{\"method\":\"POST\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":2},\"ifMatch\":\"\\\"condition\\\"\"},\"markRead\":{\"method\":\"POST\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages/read\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":2}}}},\"turn\":\"party\",\"effectDigest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"status\":\"approved\"}", + "accept": true + }, + { + "name": "unreadListapproved", + "route": "list", + "status": 200, + "body": "{\"items\":[{\"id\":\"00000000-0000-4000-8000-000000000001\",\"actionId\":\"correct\",\"actionRevision\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"submissionVersion\":1,\"revision\":2,\"state\":\"submitted\",\"links\":{\"self\":{\"method\":\"GET\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001\",\"accessProfile\":\"reader\",\"operation\":\"get\"}},\"additionalForms\":{\"extra\":{\"id\":\"extra\",\"maximumCount\":2,\"items\":[{\"id\":\"00000000-0000-4000-8000-000000000002\",\"submissionVersion\":1,\"addedAt\":\"2026-11-27T00:00:00Z\",\"input\":{\"futureMember\":\"Declared input\"}}]}},\"messages\":{\"count\":1,\"unread\":1,\"lastSentAt\":\"2026-11-27T00:00:00Z\"},\"turn\":\"party\",\"effectDigest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"status\":\"approved\"}]}", + "accept": true + }, + { + "name": "unreadGetprocessing", + "route": "get", + "status": 200, + "body": "{\"id\":\"00000000-0000-4000-8000-000000000001\",\"actionId\":\"correct\",\"actionRevision\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"submissionVersion\":1,\"revision\":2,\"state\":\"submitted\",\"links\":{\"self\":{\"method\":\"GET\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001\",\"accessProfile\":\"reader\",\"operation\":\"get\"}},\"additionalForms\":{\"extra\":{\"id\":\"extra\",\"maximumCount\":2,\"items\":[{\"id\":\"00000000-0000-4000-8000-000000000002\",\"submissionVersion\":1,\"addedAt\":\"2026-11-27T00:00:00Z\",\"input\":{\"futureMember\":\"Declared input\"}}]}},\"messages\":{\"count\":1,\"unread\":1,\"lastSentAt\":\"2026-11-27T00:00:00Z\",\"items\":[{\"id\":\"00000000-0000-4000-8000-000000000002\",\"from\":\"official\",\"mine\":false,\"sentAt\":\"2026-11-27T00:00:00Z\",\"text\":\"Synthetic message\"}],\"links\":{\"list\":{\"method\":\"GET\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":2}},\"message\":{\"method\":\"POST\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":2},\"ifMatch\":\"\\\"condition\\\"\"},\"markRead\":{\"method\":\"POST\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages/read\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":2}}}},\"turn\":\"party\",\"effectDigest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"status\":\"processing\"}", + "accept": true + }, + { + "name": "unreadListprocessing", + "route": "list", + "status": 200, + "body": "{\"items\":[{\"id\":\"00000000-0000-4000-8000-000000000001\",\"actionId\":\"correct\",\"actionRevision\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"submissionVersion\":1,\"revision\":2,\"state\":\"submitted\",\"links\":{\"self\":{\"method\":\"GET\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001\",\"accessProfile\":\"reader\",\"operation\":\"get\"}},\"additionalForms\":{\"extra\":{\"id\":\"extra\",\"maximumCount\":2,\"items\":[{\"id\":\"00000000-0000-4000-8000-000000000002\",\"submissionVersion\":1,\"addedAt\":\"2026-11-27T00:00:00Z\",\"input\":{\"futureMember\":\"Declared input\"}}]}},\"messages\":{\"count\":1,\"unread\":1,\"lastSentAt\":\"2026-11-27T00:00:00Z\"},\"turn\":\"party\",\"effectDigest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"status\":\"processing\"}]}", + "accept": true + }, + { + "name": "listThreadOverdisclosure", + "route": "list", + "status": 200, + "body": "{\"items\":[{\"id\":\"00000000-0000-4000-8000-000000000001\",\"actionId\":\"correct\",\"actionRevision\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"submissionVersion\":1,\"revision\":2,\"state\":\"submitted\",\"links\":{\"self\":{\"method\":\"GET\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001\",\"accessProfile\":\"reader\",\"operation\":\"get\"}},\"additionalForms\":{\"extra\":{\"id\":\"extra\",\"maximumCount\":2,\"items\":[{\"id\":\"00000000-0000-4000-8000-000000000002\",\"submissionVersion\":1,\"addedAt\":\"2026-11-27T00:00:00Z\",\"input\":{\"futureMember\":\"Declared input\"}}]}},\"messages\":{\"count\":1,\"unread\":1,\"lastSentAt\":\"2026-11-27T00:00:00Z\",\"items\":[{\"id\":\"00000000-0000-4000-8000-000000000002\",\"from\":\"official\",\"mine\":false,\"sentAt\":\"2026-11-27T00:00:00Z\",\"text\":\"Synthetic message\"}],\"links\":{\"list\":{\"method\":\"GET\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":2}},\"message\":{\"method\":\"POST\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":2},\"ifMatch\":\"\\\"condition\\\"\"},\"markRead\":{\"method\":\"POST\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages/read\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":2}}}},\"turn\":\"official\",\"effectDigest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"}]}", + "accept": false + }, + { + "name": "listWrongFormProfile", + "route": "list", + "status": 200, + "body": "{\"items\":[{\"id\":\"00000000-0000-4000-8000-000000000001\",\"actionId\":\"correct\",\"actionRevision\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"submissionVersion\":1,\"revision\":2,\"state\":\"submitted\",\"links\":{\"self\":{\"method\":\"GET\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001\",\"accessProfile\":\"reader\",\"operation\":\"get\"}},\"additionalForms\":{\"extra\":{\"id\":\"extra\",\"maximumCount\":2,\"items\":[{\"id\":\"00000000-0000-4000-8000-000000000002\",\"submissionVersion\":1,\"addedAt\":\"2026-11-27T00:00:00Z\",\"input\":{\"futureMember\":\"Declared input\"}}],\"links\":{\"add\":{\"method\":\"POST\",\"operation\":\"add\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/additional-forms/extra\",\"accessProfile\":\"foreign\",\"ifMatch\":\"\\\"condition\\\"\",\"availability\":{\"available\":true,\"observedRevision\":2}}}}},\"messages\":{\"count\":1,\"unread\":1,\"lastSentAt\":\"2026-11-27T00:00:00Z\"},\"turn\":\"official\",\"effectDigest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"}]}", + "accept": false + }, + { + "name": "listNullCursor", + "route": "list", + "status": 200, + "body": "{\"items\":[{\"id\":\"00000000-0000-4000-8000-000000000001\",\"actionId\":\"correct\",\"actionRevision\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"submissionVersion\":1,\"revision\":2,\"state\":\"submitted\",\"links\":{\"self\":{\"method\":\"GET\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001\",\"accessProfile\":\"reader\",\"operation\":\"get\"}},\"additionalForms\":{\"extra\":{\"id\":\"extra\",\"maximumCount\":2,\"items\":[{\"id\":\"00000000-0000-4000-8000-000000000002\",\"submissionVersion\":1,\"addedAt\":\"2026-11-27T00:00:00Z\",\"input\":{\"futureMember\":\"Declared input\"}}]}},\"messages\":{\"count\":1,\"unread\":1,\"lastSentAt\":\"2026-11-27T00:00:00Z\"},\"turn\":\"official\",\"effectDigest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"}],\"nextCursor\":null}", + "accept": false + }, + { + "name": "listValidCursor", + "route": "list", + "status": 200, + "body": "{\"items\":[{\"id\":\"00000000-0000-4000-8000-000000000001\",\"actionId\":\"correct\",\"actionRevision\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"submissionVersion\":1,\"revision\":2,\"state\":\"submitted\",\"links\":{\"self\":{\"method\":\"GET\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001\",\"accessProfile\":\"reader\",\"operation\":\"get\"}},\"additionalForms\":{\"extra\":{\"id\":\"extra\",\"maximumCount\":2,\"items\":[{\"id\":\"00000000-0000-4000-8000-000000000002\",\"submissionVersion\":1,\"addedAt\":\"2026-11-27T00:00:00Z\",\"input\":{\"futureMember\":\"Declared input\"}}]}},\"messages\":{\"count\":1,\"unread\":1,\"lastSentAt\":\"2026-11-27T00:00:00Z\"},\"turn\":\"official\",\"effectDigest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"}],\"nextCursor\":\"opaque-next\"}", + "accept": true + }, + { + "name": "threadNullCursor", + "route": "page", + "status": 200, + "body": "{\"items\":[],\"links\":{},\"nextCursor\":null}", + "accept": false + }, + { + "name": "threadValidCursor", + "route": "page", + "status": 200, + "body": "{\"items\":[{\"id\":\"00000000-0000-4000-8000-000000000002\",\"from\":\"official\",\"mine\":false,\"sentAt\":\"2026-11-27T00:00:00Z\",\"text\":\"Synthetic message\"},{\"id\":\"00000000-0000-4000-8000-000000000022\",\"from\":\"official\",\"mine\":false,\"sentAt\":\"2026-11-27T00:00:00Z\",\"text\":\"Synthetic message\"}],\"links\":{},\"nextCursor\":\"8\"}", + "accept": true + }, + { + "name": "markCurrentTurn", + "route": "mark", + "status": 200, + "body": "{\"id\":\"00000000-0000-4000-8000-000000000001\",\"actionId\":\"correct\",\"actionRevision\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"submissionVersion\":1,\"revision\":2,\"state\":\"submitted\",\"links\":{\"self\":{\"method\":\"GET\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001\",\"accessProfile\":\"reader\",\"operation\":\"get\"}},\"additionalForms\":{\"extra\":{\"id\":\"extra\",\"maximumCount\":2,\"items\":[{\"id\":\"00000000-0000-4000-8000-000000000002\",\"submissionVersion\":1,\"addedAt\":\"2026-11-27T00:00:00Z\",\"input\":{\"futureMember\":\"Declared input\"}}]}},\"messages\":{\"count\":1,\"unread\":1,\"lastSentAt\":\"2026-11-27T00:00:00Z\",\"items\":[{\"id\":\"00000000-0000-4000-8000-000000000002\",\"from\":\"official\",\"mine\":false,\"sentAt\":\"2026-11-27T00:00:00Z\",\"text\":\"Synthetic message\"}],\"links\":{\"list\":{\"method\":\"GET\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":2}},\"message\":{\"method\":\"POST\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":2},\"ifMatch\":\"\\\"condition\\\"\"},\"markRead\":{\"method\":\"POST\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages/read\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":2}}}},\"turn\":\"official\",\"effectDigest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"}", + "accept": true + }, + { + "name": "markMissingTurn", + "route": "mark", + "status": 200, + "body": "{\"id\":\"00000000-0000-4000-8000-000000000001\",\"actionId\":\"correct\",\"actionRevision\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"submissionVersion\":1,\"revision\":2,\"state\":\"submitted\",\"links\":{\"self\":{\"method\":\"GET\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001\",\"accessProfile\":\"reader\",\"operation\":\"get\"}},\"additionalForms\":{\"extra\":{\"id\":\"extra\",\"maximumCount\":2,\"items\":[{\"id\":\"00000000-0000-4000-8000-000000000002\",\"submissionVersion\":1,\"addedAt\":\"2026-11-27T00:00:00Z\",\"input\":{\"futureMember\":\"Declared input\"}}]}},\"messages\":{\"count\":1,\"unread\":1,\"lastSentAt\":\"2026-11-27T00:00:00Z\",\"items\":[{\"id\":\"00000000-0000-4000-8000-000000000002\",\"from\":\"official\",\"mine\":false,\"sentAt\":\"2026-11-27T00:00:00Z\",\"text\":\"Synthetic message\"}],\"links\":{\"list\":{\"method\":\"GET\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":2}},\"message\":{\"method\":\"POST\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":2},\"ifMatch\":\"\\\"condition\\\"\"},\"markRead\":{\"method\":\"POST\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages/read\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":2}}}},\"effectDigest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"}", + "accept": false + }, + { + "name": "markNullTurn", + "route": "mark", + "status": 200, + "body": "{\"id\":\"00000000-0000-4000-8000-000000000001\",\"actionId\":\"correct\",\"actionRevision\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"submissionVersion\":1,\"revision\":2,\"state\":\"submitted\",\"links\":{\"self\":{\"method\":\"GET\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001\",\"accessProfile\":\"reader\",\"operation\":\"get\"}},\"additionalForms\":{\"extra\":{\"id\":\"extra\",\"maximumCount\":2,\"items\":[{\"id\":\"00000000-0000-4000-8000-000000000002\",\"submissionVersion\":1,\"addedAt\":\"2026-11-27T00:00:00Z\",\"input\":{\"futureMember\":\"Declared input\"}}]}},\"messages\":{\"count\":1,\"unread\":1,\"lastSentAt\":\"2026-11-27T00:00:00Z\",\"items\":[{\"id\":\"00000000-0000-4000-8000-000000000002\",\"from\":\"official\",\"mine\":false,\"sentAt\":\"2026-11-27T00:00:00Z\",\"text\":\"Synthetic message\"}],\"links\":{\"list\":{\"method\":\"GET\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":2}},\"message\":{\"method\":\"POST\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":2},\"ifMatch\":\"\\\"condition\\\"\"},\"markRead\":{\"method\":\"POST\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages/read\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":2}}}},\"turn\":null,\"effectDigest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"}", + "accept": false + }, + { + "name": "applicantWant0", + "route": "get", + "status": 200, + "body": "{\"id\":\"00000000-0000-4000-8000-000000000001\",\"actionId\":\"correct\",\"actionRevision\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"submissionVersion\":1,\"revision\":2,\"state\":\"submitted\",\"links\":{\"self\":{\"method\":\"GET\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001\",\"accessProfile\":\"reader\",\"operation\":\"get\"}},\"additionalForms\":{\"extra\":{\"id\":\"extra\",\"maximumCount\":2,\"items\":[{\"id\":\"00000000-0000-4000-8000-000000000002\",\"submissionVersion\":1,\"addedAt\":\"2026-11-27T00:00:00Z\",\"input\":{\"futureMember\":\"Declared input\"}}]}},\"messages\":{\"count\":1,\"unread\":1,\"lastSentAt\":\"2026-11-27T00:00:00Z\",\"items\":[{\"id\":\"00000000-0000-4000-8000-000000000002\",\"from\":\"official\",\"mine\":false,\"sentAt\":\"2026-11-27T00:00:00Z\",\"text\":\"Synthetic message\"}],\"links\":{\"list\":{\"method\":\"GET\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":2}},\"message\":{\"method\":\"POST\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":2},\"ifMatch\":\"\\\"condition\\\"\"},\"markRead\":{\"method\":\"POST\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages/read\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":2}}}},\"turn\":\"official\",\"effectDigest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"asks\":[{\"id\":\"00000000-0000-4000-8000-000000000003\",\"text\":\"Please add your details\",\"wants\":[{\"kind\":\"form\",\"form\":\"extra\",\"futureMember\":true}],\"askedAt\":\"2026-11-26T00:00:00Z\",\"state\":\"open\",\"links\":{}}]}", + "accept": true + }, + { + "name": "reviewWant0", + "route": "context", + "status": 200, + "body": "{\"id\":\"00000000-0000-4000-8000-000000000001\",\"actionId\":\"correct\",\"actionRevision\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"submissionVersion\":1,\"revision\":2,\"effectDigest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"reviewable\":true,\"subject\":{\"source\":\"proposal-lookup\",\"subjectType\":\"proposal\",\"id\":\"00000000-0000-4000-8000-000000000001\",\"version\":\"1\",\"digest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"},\"context\":{\"reference\":\"opaque\",\"contract\":{\"id\":\"urn:registry:breg:review-context:proposal-lookup:correct:review\",\"revision\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"schemaDigest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"},\"fields\":{},\"messages\":{\"count\":1,\"unread\":1,\"lastSentAt\":\"2026-11-27T00:00:00Z\",\"items\":[{\"id\":\"00000000-0000-4000-8000-000000000002\",\"from\":\"official\",\"mine\":false,\"sentAt\":\"2026-11-27T00:00:00Z\",\"text\":\"Synthetic message\"}],\"links\":{\"list\":{\"method\":\"GET\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":2}},\"message\":{\"method\":\"POST\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":2},\"ifMatch\":\"\\\"condition\\\"\"}}},\"asks\":[{\"id\":\"00000000-0000-4000-8000-000000000003\",\"text\":\"Please add your details\",\"wants\":[{\"kind\":\"form\",\"form\":\"extra\",\"futureMember\":true}],\"askedAt\":\"2026-11-26T00:00:00Z\",\"state\":\"open\"}]},\"authority\":\"casework\",\"policy\":{\"id\":\"policy\",\"version\":\"one\",\"digest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"}}", + "accept": true + }, + { + "name": "applicantWant1", + "route": "get", + "status": 200, + "body": "{\"id\":\"00000000-0000-4000-8000-000000000001\",\"actionId\":\"correct\",\"actionRevision\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"submissionVersion\":1,\"revision\":2,\"state\":\"submitted\",\"links\":{\"self\":{\"method\":\"GET\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001\",\"accessProfile\":\"reader\",\"operation\":\"get\"}},\"additionalForms\":{\"extra\":{\"id\":\"extra\",\"maximumCount\":2,\"items\":[{\"id\":\"00000000-0000-4000-8000-000000000002\",\"submissionVersion\":1,\"addedAt\":\"2026-11-27T00:00:00Z\",\"input\":{\"futureMember\":\"Declared input\"}}]}},\"messages\":{\"count\":1,\"unread\":1,\"lastSentAt\":\"2026-11-27T00:00:00Z\",\"items\":[{\"id\":\"00000000-0000-4000-8000-000000000002\",\"from\":\"official\",\"mine\":false,\"sentAt\":\"2026-11-27T00:00:00Z\",\"text\":\"Synthetic message\"}],\"links\":{\"list\":{\"method\":\"GET\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":2}},\"message\":{\"method\":\"POST\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":2},\"ifMatch\":\"\\\"condition\\\"\"},\"markRead\":{\"method\":\"POST\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages/read\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":2}}}},\"turn\":\"official\",\"effectDigest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"asks\":[{\"id\":\"00000000-0000-4000-8000-000000000003\",\"text\":\"Please add your details\",\"wants\":[{\"kind\":\"answer\",\"form\":\"extra\"}],\"askedAt\":\"2026-11-26T00:00:00Z\",\"state\":\"open\",\"links\":{}}]}", + "accept": false + }, + { + "name": "reviewWant1", + "route": "context", + "status": 200, + "body": "{\"id\":\"00000000-0000-4000-8000-000000000001\",\"actionId\":\"correct\",\"actionRevision\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"submissionVersion\":1,\"revision\":2,\"effectDigest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"reviewable\":true,\"subject\":{\"source\":\"proposal-lookup\",\"subjectType\":\"proposal\",\"id\":\"00000000-0000-4000-8000-000000000001\",\"version\":\"1\",\"digest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"},\"context\":{\"reference\":\"opaque\",\"contract\":{\"id\":\"urn:registry:breg:review-context:proposal-lookup:correct:review\",\"revision\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"schemaDigest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"},\"fields\":{},\"messages\":{\"count\":1,\"unread\":1,\"lastSentAt\":\"2026-11-27T00:00:00Z\",\"items\":[{\"id\":\"00000000-0000-4000-8000-000000000002\",\"from\":\"official\",\"mine\":false,\"sentAt\":\"2026-11-27T00:00:00Z\",\"text\":\"Synthetic message\"}],\"links\":{\"list\":{\"method\":\"GET\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":2}},\"message\":{\"method\":\"POST\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":2},\"ifMatch\":\"\\\"condition\\\"\"}}},\"asks\":[{\"id\":\"00000000-0000-4000-8000-000000000003\",\"text\":\"Please add your details\",\"wants\":[{\"kind\":\"answer\",\"form\":\"extra\"}],\"askedAt\":\"2026-11-26T00:00:00Z\",\"state\":\"open\"}]},\"authority\":\"casework\",\"policy\":{\"id\":\"policy\",\"version\":\"one\",\"digest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"}}", + "accept": false + }, + { + "name": "applicantWant2", + "route": "get", + "status": 200, + "body": "{\"id\":\"00000000-0000-4000-8000-000000000001\",\"actionId\":\"correct\",\"actionRevision\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"submissionVersion\":1,\"revision\":2,\"state\":\"submitted\",\"links\":{\"self\":{\"method\":\"GET\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001\",\"accessProfile\":\"reader\",\"operation\":\"get\"}},\"additionalForms\":{\"extra\":{\"id\":\"extra\",\"maximumCount\":2,\"items\":[{\"id\":\"00000000-0000-4000-8000-000000000002\",\"submissionVersion\":1,\"addedAt\":\"2026-11-27T00:00:00Z\",\"input\":{\"futureMember\":\"Declared input\"}}]}},\"messages\":{\"count\":1,\"unread\":1,\"lastSentAt\":\"2026-11-27T00:00:00Z\",\"items\":[{\"id\":\"00000000-0000-4000-8000-000000000002\",\"from\":\"official\",\"mine\":false,\"sentAt\":\"2026-11-27T00:00:00Z\",\"text\":\"Synthetic message\"}],\"links\":{\"list\":{\"method\":\"GET\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":2}},\"message\":{\"method\":\"POST\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":2},\"ifMatch\":\"\\\"condition\\\"\"},\"markRead\":{\"method\":\"POST\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages/read\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":2}}}},\"turn\":\"official\",\"effectDigest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"asks\":[{\"id\":\"00000000-0000-4000-8000-000000000003\",\"text\":\"Please add your details\",\"wants\":[{\"kind\":\"document\",\"form\":\"extra\"}],\"askedAt\":\"2026-11-26T00:00:00Z\",\"state\":\"open\",\"links\":{}}]}", + "accept": false + }, + { + "name": "reviewWant2", + "route": "context", + "status": 200, + "body": "{\"id\":\"00000000-0000-4000-8000-000000000001\",\"actionId\":\"correct\",\"actionRevision\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"submissionVersion\":1,\"revision\":2,\"effectDigest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"reviewable\":true,\"subject\":{\"source\":\"proposal-lookup\",\"subjectType\":\"proposal\",\"id\":\"00000000-0000-4000-8000-000000000001\",\"version\":\"1\",\"digest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"},\"context\":{\"reference\":\"opaque\",\"contract\":{\"id\":\"urn:registry:breg:review-context:proposal-lookup:correct:review\",\"revision\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"schemaDigest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"},\"fields\":{},\"messages\":{\"count\":1,\"unread\":1,\"lastSentAt\":\"2026-11-27T00:00:00Z\",\"items\":[{\"id\":\"00000000-0000-4000-8000-000000000002\",\"from\":\"official\",\"mine\":false,\"sentAt\":\"2026-11-27T00:00:00Z\",\"text\":\"Synthetic message\"}],\"links\":{\"list\":{\"method\":\"GET\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":2}},\"message\":{\"method\":\"POST\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":2},\"ifMatch\":\"\\\"condition\\\"\"}}},\"asks\":[{\"id\":\"00000000-0000-4000-8000-000000000003\",\"text\":\"Please add your details\",\"wants\":[{\"kind\":\"document\",\"form\":\"extra\"}],\"askedAt\":\"2026-11-26T00:00:00Z\",\"state\":\"open\"}]},\"authority\":\"casework\",\"policy\":{\"id\":\"policy\",\"version\":\"one\",\"digest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"}}", + "accept": false + }, + { + "name": "applicantWant3", + "route": "get", + "status": 200, + "body": "{\"id\":\"00000000-0000-4000-8000-000000000001\",\"actionId\":\"correct\",\"actionRevision\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"submissionVersion\":1,\"revision\":2,\"state\":\"submitted\",\"links\":{\"self\":{\"method\":\"GET\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001\",\"accessProfile\":\"reader\",\"operation\":\"get\"}},\"additionalForms\":{\"extra\":{\"id\":\"extra\",\"maximumCount\":2,\"items\":[{\"id\":\"00000000-0000-4000-8000-000000000002\",\"submissionVersion\":1,\"addedAt\":\"2026-11-27T00:00:00Z\",\"input\":{\"futureMember\":\"Declared input\"}}]}},\"messages\":{\"count\":1,\"unread\":1,\"lastSentAt\":\"2026-11-27T00:00:00Z\",\"items\":[{\"id\":\"00000000-0000-4000-8000-000000000002\",\"from\":\"official\",\"mine\":false,\"sentAt\":\"2026-11-27T00:00:00Z\",\"text\":\"Synthetic message\"}],\"links\":{\"list\":{\"method\":\"GET\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":2}},\"message\":{\"method\":\"POST\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":2},\"ifMatch\":\"\\\"condition\\\"\"},\"markRead\":{\"method\":\"POST\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages/read\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":2}}}},\"turn\":\"official\",\"effectDigest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"asks\":[{\"id\":\"00000000-0000-4000-8000-000000000003\",\"text\":\"Please add your details\",\"wants\":[{\"kind\":\"form\",\"form\":\"extra\",\"formId\":\"other\"}],\"askedAt\":\"2026-11-26T00:00:00Z\",\"state\":\"open\",\"links\":{}}]}", + "accept": false + }, + { + "name": "reviewWant3", + "route": "context", + "status": 200, + "body": "{\"id\":\"00000000-0000-4000-8000-000000000001\",\"actionId\":\"correct\",\"actionRevision\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"submissionVersion\":1,\"revision\":2,\"effectDigest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"reviewable\":true,\"subject\":{\"source\":\"proposal-lookup\",\"subjectType\":\"proposal\",\"id\":\"00000000-0000-4000-8000-000000000001\",\"version\":\"1\",\"digest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"},\"context\":{\"reference\":\"opaque\",\"contract\":{\"id\":\"urn:registry:breg:review-context:proposal-lookup:correct:review\",\"revision\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"schemaDigest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"},\"fields\":{},\"messages\":{\"count\":1,\"unread\":1,\"lastSentAt\":\"2026-11-27T00:00:00Z\",\"items\":[{\"id\":\"00000000-0000-4000-8000-000000000002\",\"from\":\"official\",\"mine\":false,\"sentAt\":\"2026-11-27T00:00:00Z\",\"text\":\"Synthetic message\"}],\"links\":{\"list\":{\"method\":\"GET\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":2}},\"message\":{\"method\":\"POST\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":2},\"ifMatch\":\"\\\"condition\\\"\"}}},\"asks\":[{\"id\":\"00000000-0000-4000-8000-000000000003\",\"text\":\"Please add your details\",\"wants\":[{\"kind\":\"form\",\"form\":\"extra\",\"formId\":\"other\"}],\"askedAt\":\"2026-11-26T00:00:00Z\",\"state\":\"open\"}]},\"authority\":\"casework\",\"policy\":{\"id\":\"policy\",\"version\":\"one\",\"digest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"}}", + "accept": false + }, + { + "name": "applicantWant4", + "route": "get", + "status": 200, + "body": "{\"id\":\"00000000-0000-4000-8000-000000000001\",\"actionId\":\"correct\",\"actionRevision\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"submissionVersion\":1,\"revision\":2,\"state\":\"submitted\",\"links\":{\"self\":{\"method\":\"GET\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001\",\"accessProfile\":\"reader\",\"operation\":\"get\"}},\"additionalForms\":{\"extra\":{\"id\":\"extra\",\"maximumCount\":2,\"items\":[{\"id\":\"00000000-0000-4000-8000-000000000002\",\"submissionVersion\":1,\"addedAt\":\"2026-11-27T00:00:00Z\",\"input\":{\"futureMember\":\"Declared input\"}}]}},\"messages\":{\"count\":1,\"unread\":1,\"lastSentAt\":\"2026-11-27T00:00:00Z\",\"items\":[{\"id\":\"00000000-0000-4000-8000-000000000002\",\"from\":\"official\",\"mine\":false,\"sentAt\":\"2026-11-27T00:00:00Z\",\"text\":\"Synthetic message\"}],\"links\":{\"list\":{\"method\":\"GET\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":2}},\"message\":{\"method\":\"POST\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":2},\"ifMatch\":\"\\\"condition\\\"\"},\"markRead\":{\"method\":\"POST\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages/read\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":2}}}},\"turn\":\"official\",\"effectDigest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"asks\":[{\"id\":\"00000000-0000-4000-8000-000000000003\",\"text\":\"Please add your details\",\"wants\":[{\"kind\":\"form\"}],\"askedAt\":\"2026-11-26T00:00:00Z\",\"state\":\"open\",\"links\":{}}]}", + "accept": false + }, + { + "name": "reviewWant4", + "route": "context", + "status": 200, + "body": "{\"id\":\"00000000-0000-4000-8000-000000000001\",\"actionId\":\"correct\",\"actionRevision\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"submissionVersion\":1,\"revision\":2,\"effectDigest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"reviewable\":true,\"subject\":{\"source\":\"proposal-lookup\",\"subjectType\":\"proposal\",\"id\":\"00000000-0000-4000-8000-000000000001\",\"version\":\"1\",\"digest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"},\"context\":{\"reference\":\"opaque\",\"contract\":{\"id\":\"urn:registry:breg:review-context:proposal-lookup:correct:review\",\"revision\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"schemaDigest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"},\"fields\":{},\"messages\":{\"count\":1,\"unread\":1,\"lastSentAt\":\"2026-11-27T00:00:00Z\",\"items\":[{\"id\":\"00000000-0000-4000-8000-000000000002\",\"from\":\"official\",\"mine\":false,\"sentAt\":\"2026-11-27T00:00:00Z\",\"text\":\"Synthetic message\"}],\"links\":{\"list\":{\"method\":\"GET\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":2}},\"message\":{\"method\":\"POST\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":2},\"ifMatch\":\"\\\"condition\\\"\"}}},\"asks\":[{\"id\":\"00000000-0000-4000-8000-000000000003\",\"text\":\"Please add your details\",\"wants\":[{\"kind\":\"form\"}],\"askedAt\":\"2026-11-26T00:00:00Z\",\"state\":\"open\"}]},\"authority\":\"casework\",\"policy\":{\"id\":\"policy\",\"version\":\"one\",\"digest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"}}", + "accept": false + }, + { + "name": "batchCountsAndForms", + "route": "batch", + "status": 200, + "body": "{\"items\":[{\"status\":\"visible\",\"id\":\"00000000-0000-4000-8000-000000000001\",\"context\":{\"id\":\"00000000-0000-4000-8000-000000000001\",\"actionId\":\"correct\",\"actionRevision\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"submissionVersion\":1,\"revision\":2,\"effectDigest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"reviewable\":true,\"subject\":{\"source\":\"proposal-lookup\",\"subjectType\":\"proposal\",\"id\":\"00000000-0000-4000-8000-000000000001\",\"version\":\"1\",\"digest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"},\"context\":{\"reference\":\"opaque\",\"contract\":{\"id\":\"urn:registry:breg:review-context:proposal-lookup:correct:review\",\"revision\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"schemaDigest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"},\"fields\":{},\"messages\":{\"count\":1,\"unread\":1,\"lastSentAt\":\"2026-11-27T00:00:00Z\"},\"additionalForms\":{\"extra\":\"extra\"}},\"authority\":\"casework\",\"policy\":{\"id\":\"policy\",\"version\":\"one\",\"digest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"}}}]}", + "accept": true + }, + { + "name": "batchAnswersOverdisclosure", + "route": "batch", + "status": 200, + "body": "{\"items\":[{\"status\":\"visible\",\"id\":\"00000000-0000-4000-8000-000000000001\",\"context\":{\"id\":\"00000000-0000-4000-8000-000000000001\",\"actionId\":\"correct\",\"actionRevision\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"submissionVersion\":1,\"revision\":2,\"effectDigest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"reviewable\":true,\"subject\":{\"source\":\"proposal-lookup\",\"subjectType\":\"proposal\",\"id\":\"00000000-0000-4000-8000-000000000001\",\"version\":\"1\",\"digest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"},\"context\":{\"reference\":\"opaque\",\"contract\":{\"id\":\"urn:registry:breg:review-context:proposal-lookup:correct:review\",\"revision\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"schemaDigest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"},\"fields\":{},\"messages\":{\"count\":1,\"unread\":1,\"lastSentAt\":\"2026-11-27T00:00:00Z\"},\"additionalForms\":{\"extra\":\"extra\"},\"asks\":[{\"id\":\"00000000-0000-4000-8000-000000000003\",\"text\":\"Please add your details\",\"wants\":[{\"kind\":\"answer\"}],\"askedAt\":\"2026-11-26T00:00:00Z\",\"state\":\"open\"}]},\"authority\":\"casework\",\"policy\":{\"id\":\"policy\",\"version\":\"one\",\"digest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"}}}]}", + "accept": false + }, + { + "name": "reviewMessageReceipt", + "route": "send", + "status": 200, + "body": "{\"id\":\"00000000-0000-4000-8000-000000000001\",\"actionId\":\"correct\",\"actionRevision\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"submissionVersion\":1,\"revision\":3,\"effectDigest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"reviewable\":true,\"subject\":{\"source\":\"proposal-lookup\",\"subjectType\":\"proposal\",\"id\":\"00000000-0000-4000-8000-000000000001\",\"version\":\"1\",\"digest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"},\"context\":{\"reference\":\"opaque\",\"contract\":{\"id\":\"urn:registry:breg:review-context:proposal-lookup:correct:review\",\"revision\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"schemaDigest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"},\"fields\":{},\"messages\":{\"count\":1,\"unread\":1,\"lastSentAt\":\"2026-11-27T00:00:00Z\",\"items\":[{\"id\":\"00000000-0000-4000-8000-000000000002\",\"mine\":true,\"sentAt\":\"2026-11-27T00:00:00Z\",\"text\":\"Synthetic reply\",\"from\":\"official\"}],\"links\":{\"list\":{\"method\":\"GET\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":3}},\"message\":{\"method\":\"POST\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":3},\"ifMatch\":\"\\\"condition\\\"\"}}}}}", + "accept": true + }, + { + "name": "reviewMessageWrongSubject", + "route": "send", + "status": 200, + "body": "{\"id\":\"00000000-0000-4000-8000-000000000001\",\"actionId\":\"correct\",\"actionRevision\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"submissionVersion\":1,\"revision\":3,\"effectDigest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"reviewable\":true,\"subject\":{\"source\":\"different-source\",\"subjectType\":\"proposal\",\"id\":\"00000000-0000-4000-8000-000000000001\",\"version\":\"1\",\"digest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"},\"context\":{\"reference\":\"opaque\",\"contract\":{\"id\":\"urn:registry:breg:review-context:proposal-lookup:correct:review\",\"revision\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"schemaDigest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"},\"fields\":{},\"messages\":{\"count\":1,\"unread\":1,\"lastSentAt\":\"2026-11-27T00:00:00Z\",\"items\":[{\"id\":\"00000000-0000-4000-8000-000000000002\",\"mine\":true,\"sentAt\":\"2026-11-27T00:00:00Z\",\"text\":\"Synthetic reply\",\"from\":\"official\"}],\"links\":{\"list\":{\"method\":\"GET\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":3}},\"message\":{\"method\":\"POST\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":3},\"ifMatch\":\"\\\"condition\\\"\"}}}}}", + "accept": false + }, + { + "name": "contextKeepsForms", + "status": 200, + "body": "{\"id\":\"00000000-0000-4000-8000-000000000001\",\"actionId\":\"correct\",\"actionRevision\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"submissionVersion\":1,\"revision\":2,\"effectDigest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"reviewable\":true,\"subject\":{\"source\":\"proposal-lookup\",\"subjectType\":\"proposal\",\"id\":\"00000000-0000-4000-8000-000000000001\",\"version\":\"1\",\"digest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"},\"context\":{\"reference\":\"opaque\",\"contract\":{\"id\":\"urn:registry:breg:review-context:proposal-lookup:correct:review\",\"revision\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"schemaDigest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"},\"fields\":{},\"messages\":{\"count\":1,\"unread\":1,\"lastSentAt\":\"2026-11-27T00:00:00Z\",\"items\":[{\"id\":\"00000000-0000-4000-8000-000000000002\",\"from\":\"official\",\"mine\":false,\"sentAt\":\"2026-11-27T00:00:00Z\",\"text\":\"Synthetic message\"}],\"links\":{\"list\":{\"method\":\"GET\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":2}},\"message\":{\"method\":\"POST\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":2},\"ifMatch\":\"\\\"condition\\\"\"},\"markRead\":{\"method\":\"POST\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages/read\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":2}}}},\"additionalForms\":{\"extra\":\"extra\"}}}", + "route": "context", + "accept": true + }, + { + "name": "contextForeignProfile-list", + "status": 200, + "body": "{\"id\":\"00000000-0000-4000-8000-000000000001\",\"actionId\":\"correct\",\"actionRevision\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"submissionVersion\":1,\"revision\":2,\"effectDigest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"reviewable\":true,\"subject\":{\"source\":\"proposal-lookup\",\"subjectType\":\"proposal\",\"id\":\"00000000-0000-4000-8000-000000000001\",\"version\":\"1\",\"digest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"},\"context\":{\"reference\":\"opaque\",\"contract\":{\"id\":\"urn:registry:breg:review-context:proposal-lookup:correct:review\",\"revision\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"schemaDigest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"},\"fields\":{},\"messages\":{\"count\":1,\"unread\":1,\"lastSentAt\":\"2026-11-27T00:00:00Z\",\"items\":[{\"id\":\"00000000-0000-4000-8000-000000000002\",\"from\":\"official\",\"mine\":false,\"sentAt\":\"2026-11-27T00:00:00Z\",\"text\":\"Synthetic message\"}],\"links\":{\"list\":{\"method\":\"GET\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"different-profile\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":2}},\"message\":{\"method\":\"POST\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":2},\"ifMatch\":\"\\\"condition\\\"\"},\"markRead\":{\"method\":\"POST\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages/read\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":2}}}},\"additionalForms\":{\"extra\":\"extra\"}}}", + "route": "context", + "accept": false + }, + { + "name": "contextForeignProfile-message", + "status": 200, + "body": "{\"id\":\"00000000-0000-4000-8000-000000000001\",\"actionId\":\"correct\",\"actionRevision\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"submissionVersion\":1,\"revision\":2,\"effectDigest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"reviewable\":true,\"subject\":{\"source\":\"proposal-lookup\",\"subjectType\":\"proposal\",\"id\":\"00000000-0000-4000-8000-000000000001\",\"version\":\"1\",\"digest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"},\"context\":{\"reference\":\"opaque\",\"contract\":{\"id\":\"urn:registry:breg:review-context:proposal-lookup:correct:review\",\"revision\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"schemaDigest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"},\"fields\":{},\"messages\":{\"count\":1,\"unread\":1,\"lastSentAt\":\"2026-11-27T00:00:00Z\",\"items\":[{\"id\":\"00000000-0000-4000-8000-000000000002\",\"from\":\"official\",\"mine\":false,\"sentAt\":\"2026-11-27T00:00:00Z\",\"text\":\"Synthetic message\"}],\"links\":{\"list\":{\"method\":\"GET\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":2}},\"message\":{\"method\":\"POST\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"different-profile\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":2},\"ifMatch\":\"\\\"condition\\\"\"},\"markRead\":{\"method\":\"POST\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages/read\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":2}}}},\"additionalForms\":{\"extra\":\"extra\"}}}", + "route": "context", + "accept": false + }, + { + "name": "contextForeignProfile-markRead", + "status": 200, + "body": "{\"id\":\"00000000-0000-4000-8000-000000000001\",\"actionId\":\"correct\",\"actionRevision\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"submissionVersion\":1,\"revision\":2,\"effectDigest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"reviewable\":true,\"subject\":{\"source\":\"proposal-lookup\",\"subjectType\":\"proposal\",\"id\":\"00000000-0000-4000-8000-000000000001\",\"version\":\"1\",\"digest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"},\"context\":{\"reference\":\"opaque\",\"contract\":{\"id\":\"urn:registry:breg:review-context:proposal-lookup:correct:review\",\"revision\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"schemaDigest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"},\"fields\":{},\"messages\":{\"count\":1,\"unread\":1,\"lastSentAt\":\"2026-11-27T00:00:00Z\",\"items\":[{\"id\":\"00000000-0000-4000-8000-000000000002\",\"from\":\"official\",\"mine\":false,\"sentAt\":\"2026-11-27T00:00:00Z\",\"text\":\"Synthetic message\"}],\"links\":{\"list\":{\"method\":\"GET\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":2}},\"message\":{\"method\":\"POST\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":2},\"ifMatch\":\"\\\"condition\\\"\"},\"markRead\":{\"method\":\"POST\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages/read\",\"accessProfile\":\"different-profile\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":2}}}},\"additionalForms\":{\"extra\":\"extra\"}}}", + "route": "context", + "accept": false + }, + { + "name": "promotedContextKeepsForms", + "status": 200, + "body": "{\"id\":\"00000000-0000-4000-8000-000000000001\",\"actionId\":\"correct\",\"actionRevision\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"submissionVersion\":1,\"revision\":2,\"effectDigest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"reviewable\":true,\"subject\":{\"source\":\"proposal-lookup\",\"subjectType\":\"proposal\",\"id\":\"00000000-0000-4000-8000-000000000001\",\"version\":\"1\",\"digest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"},\"context\":{\"reference\":\"opaque\",\"contract\":{\"id\":\"urn:registry:breg:review-context:proposal-lookup:correct:review\",\"revision\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"schemaDigest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"},\"fields\":{},\"messages\":{\"count\":1,\"unread\":1,\"lastSentAt\":\"2026-11-27T00:00:00Z\",\"items\":[{\"id\":\"00000000-0000-4000-8000-000000000002\",\"from\":\"official\",\"mine\":false,\"sentAt\":\"2026-11-27T00:00:00Z\",\"text\":\"Synthetic message\"}],\"links\":{\"list\":{\"method\":\"GET\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":2}},\"message\":{\"method\":\"POST\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":2},\"ifMatch\":\"\\\"condition\\\"\"},\"markRead\":{\"method\":\"POST\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages/read\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":2}}}},\"additionalForms\":{\"extra\":\"extra\"}}}", + "route": "promotedContext", + "accept": true + }, + { + "name": "promotedContextForeignProfile-list", + "status": 200, + "body": "{\"id\":\"00000000-0000-4000-8000-000000000001\",\"actionId\":\"correct\",\"actionRevision\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"submissionVersion\":1,\"revision\":2,\"effectDigest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"reviewable\":true,\"subject\":{\"source\":\"proposal-lookup\",\"subjectType\":\"proposal\",\"id\":\"00000000-0000-4000-8000-000000000001\",\"version\":\"1\",\"digest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"},\"context\":{\"reference\":\"opaque\",\"contract\":{\"id\":\"urn:registry:breg:review-context:proposal-lookup:correct:review\",\"revision\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"schemaDigest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"},\"fields\":{},\"messages\":{\"count\":1,\"unread\":1,\"lastSentAt\":\"2026-11-27T00:00:00Z\",\"items\":[{\"id\":\"00000000-0000-4000-8000-000000000002\",\"from\":\"official\",\"mine\":false,\"sentAt\":\"2026-11-27T00:00:00Z\",\"text\":\"Synthetic message\"}],\"links\":{\"list\":{\"method\":\"GET\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"different-profile\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":2}},\"message\":{\"method\":\"POST\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":2},\"ifMatch\":\"\\\"condition\\\"\"},\"markRead\":{\"method\":\"POST\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages/read\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":2}}}},\"additionalForms\":{\"extra\":\"extra\"}}}", + "route": "promotedContext", + "accept": false + }, + { + "name": "promotedContextForeignProfile-message", + "status": 200, + "body": "{\"id\":\"00000000-0000-4000-8000-000000000001\",\"actionId\":\"correct\",\"actionRevision\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"submissionVersion\":1,\"revision\":2,\"effectDigest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"reviewable\":true,\"subject\":{\"source\":\"proposal-lookup\",\"subjectType\":\"proposal\",\"id\":\"00000000-0000-4000-8000-000000000001\",\"version\":\"1\",\"digest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"},\"context\":{\"reference\":\"opaque\",\"contract\":{\"id\":\"urn:registry:breg:review-context:proposal-lookup:correct:review\",\"revision\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"schemaDigest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"},\"fields\":{},\"messages\":{\"count\":1,\"unread\":1,\"lastSentAt\":\"2026-11-27T00:00:00Z\",\"items\":[{\"id\":\"00000000-0000-4000-8000-000000000002\",\"from\":\"official\",\"mine\":false,\"sentAt\":\"2026-11-27T00:00:00Z\",\"text\":\"Synthetic message\"}],\"links\":{\"list\":{\"method\":\"GET\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":2}},\"message\":{\"method\":\"POST\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"different-profile\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":2},\"ifMatch\":\"\\\"condition\\\"\"},\"markRead\":{\"method\":\"POST\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages/read\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":2}}}},\"additionalForms\":{\"extra\":\"extra\"}}}", + "route": "promotedContext", + "accept": false + }, + { + "name": "promotedContextForeignProfile-markRead", + "status": 200, + "body": "{\"id\":\"00000000-0000-4000-8000-000000000001\",\"actionId\":\"correct\",\"actionRevision\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"submissionVersion\":1,\"revision\":2,\"effectDigest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"reviewable\":true,\"subject\":{\"source\":\"proposal-lookup\",\"subjectType\":\"proposal\",\"id\":\"00000000-0000-4000-8000-000000000001\",\"version\":\"1\",\"digest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"},\"context\":{\"reference\":\"opaque\",\"contract\":{\"id\":\"urn:registry:breg:review-context:proposal-lookup:correct:review\",\"revision\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"schemaDigest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"},\"fields\":{},\"messages\":{\"count\":1,\"unread\":1,\"lastSentAt\":\"2026-11-27T00:00:00Z\",\"items\":[{\"id\":\"00000000-0000-4000-8000-000000000002\",\"from\":\"official\",\"mine\":false,\"sentAt\":\"2026-11-27T00:00:00Z\",\"text\":\"Synthetic message\"}],\"links\":{\"list\":{\"method\":\"GET\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":2}},\"message\":{\"method\":\"POST\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":2},\"ifMatch\":\"\\\"condition\\\"\"},\"markRead\":{\"method\":\"POST\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages/read\",\"accessProfile\":\"different-profile\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":2}}}},\"additionalForms\":{\"extra\":\"extra\"}}}", + "route": "promotedContext", + "accept": false + }, + { + "name": "statusWithoutForms", + "status": 200, + "body": "{\"id\":\"00000000-0000-4000-8000-000000000001\",\"actionId\":\"correct\",\"actionRevision\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"submissionVersion\":1,\"revision\":2,\"effectDigest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"reviewable\":true,\"subject\":{\"source\":\"proposal-lookup\",\"subjectType\":\"proposal\",\"id\":\"00000000-0000-4000-8000-000000000001\",\"version\":\"1\",\"digest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"},\"context\":{\"reference\":\"opaque\"}}", + "route": "status", + "accept": true + }, + { + "name": "statusFormsPopulated", + "status": 200, + "body": "{\"id\":\"00000000-0000-4000-8000-000000000001\",\"actionId\":\"correct\",\"actionRevision\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"submissionVersion\":1,\"revision\":2,\"effectDigest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"reviewable\":true,\"subject\":{\"source\":\"proposal-lookup\",\"subjectType\":\"proposal\",\"id\":\"00000000-0000-4000-8000-000000000001\",\"version\":\"1\",\"digest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"},\"context\":{\"reference\":\"opaque\",\"additionalForms\":{\"extra\":\"extra\"}}}", + "route": "status", + "accept": false + }, + { + "name": "statusFormsEmpty", + "status": 200, + "body": "{\"id\":\"00000000-0000-4000-8000-000000000001\",\"actionId\":\"correct\",\"actionRevision\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"submissionVersion\":1,\"revision\":2,\"effectDigest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"reviewable\":true,\"subject\":{\"source\":\"proposal-lookup\",\"subjectType\":\"proposal\",\"id\":\"00000000-0000-4000-8000-000000000001\",\"version\":\"1\",\"digest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"},\"context\":{\"reference\":\"opaque\",\"additionalForms\":{}}}", + "route": "status", + "accept": false + }, + { + "name": "statusFormsNull", + "status": 200, + "body": "{\"id\":\"00000000-0000-4000-8000-000000000001\",\"actionId\":\"correct\",\"actionRevision\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"submissionVersion\":1,\"revision\":2,\"effectDigest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"reviewable\":true,\"subject\":{\"source\":\"proposal-lookup\",\"subjectType\":\"proposal\",\"id\":\"00000000-0000-4000-8000-000000000001\",\"version\":\"1\",\"digest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"},\"context\":{\"reference\":\"opaque\",\"additionalForms\":null}}", + "route": "status", + "accept": false + }, + { + "name": "promotedStatusWithoutForms", + "status": 200, + "body": "{\"id\":\"00000000-0000-4000-8000-000000000001\",\"actionId\":\"correct\",\"actionRevision\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"submissionVersion\":1,\"revision\":2,\"effectDigest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"reviewable\":true,\"subject\":{\"source\":\"proposal-lookup\",\"subjectType\":\"proposal\",\"id\":\"00000000-0000-4000-8000-000000000001\",\"version\":\"1\",\"digest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"},\"context\":{\"reference\":\"opaque\"}}", + "route": "promotedStatus", + "accept": true + }, + { + "name": "promotedStatusFormsPopulated", + "status": 200, + "body": "{\"id\":\"00000000-0000-4000-8000-000000000001\",\"actionId\":\"correct\",\"actionRevision\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"submissionVersion\":1,\"revision\":2,\"effectDigest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"reviewable\":true,\"subject\":{\"source\":\"proposal-lookup\",\"subjectType\":\"proposal\",\"id\":\"00000000-0000-4000-8000-000000000001\",\"version\":\"1\",\"digest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"},\"context\":{\"reference\":\"opaque\",\"additionalForms\":{\"extra\":\"extra\"}}}", + "route": "promotedStatus", + "accept": false + }, + { + "name": "promotedStatusFormsEmpty", + "status": 200, + "body": "{\"id\":\"00000000-0000-4000-8000-000000000001\",\"actionId\":\"correct\",\"actionRevision\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"submissionVersion\":1,\"revision\":2,\"effectDigest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"reviewable\":true,\"subject\":{\"source\":\"proposal-lookup\",\"subjectType\":\"proposal\",\"id\":\"00000000-0000-4000-8000-000000000001\",\"version\":\"1\",\"digest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"},\"context\":{\"reference\":\"opaque\",\"additionalForms\":{}}}", + "route": "promotedStatus", + "accept": false + }, + { + "name": "promotedStatusFormsNull", + "status": 200, + "body": "{\"id\":\"00000000-0000-4000-8000-000000000001\",\"actionId\":\"correct\",\"actionRevision\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"submissionVersion\":1,\"revision\":2,\"effectDigest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"reviewable\":true,\"subject\":{\"source\":\"proposal-lookup\",\"subjectType\":\"proposal\",\"id\":\"00000000-0000-4000-8000-000000000001\",\"version\":\"1\",\"digest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"},\"context\":{\"reference\":\"opaque\",\"additionalForms\":null}}", + "route": "promotedStatus", + "accept": false + }, + { + "name": "batchReaderOfficial", + "status": 200, + "body": "{\"items\":[{\"status\":\"visible\",\"id\":\"00000000-0000-4000-8000-000000000001\",\"context\":{\"id\":\"00000000-0000-4000-8000-000000000001\",\"actionId\":\"correct\",\"actionRevision\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"submissionVersion\":1,\"revision\":2,\"effectDigest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"reviewable\":true,\"subject\":{\"source\":\"proposal-lookup\",\"subjectType\":\"proposal\",\"id\":\"00000000-0000-4000-8000-000000000001\",\"version\":\"1\",\"digest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"},\"context\":{\"reference\":\"opaque\",\"contract\":{\"id\":\"urn:registry:breg:review-context:proposal-lookup:correct:review\",\"revision\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"schemaDigest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"},\"fields\":{},\"messages\":{\"count\":1,\"unread\":1,\"lastSentAt\":\"2026-11-27T00:00:00Z\",\"readerSide\":\"official\"},\"additionalForms\":{\"extra\":\"extra\"}},\"authority\":\"casework\",\"policy\":{\"id\":\"policy\",\"version\":\"one\",\"digest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"}}}]}", + "route": "batch", + "accept": true + }, + { + "name": "batchReaderParty", + "status": 200, + "body": "{\"items\":[{\"status\":\"visible\",\"id\":\"00000000-0000-4000-8000-000000000001\",\"context\":{\"id\":\"00000000-0000-4000-8000-000000000001\",\"actionId\":\"correct\",\"actionRevision\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"submissionVersion\":1,\"revision\":2,\"effectDigest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"reviewable\":true,\"subject\":{\"source\":\"proposal-lookup\",\"subjectType\":\"proposal\",\"id\":\"00000000-0000-4000-8000-000000000001\",\"version\":\"1\",\"digest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"},\"context\":{\"reference\":\"opaque\",\"contract\":{\"id\":\"urn:registry:breg:review-context:proposal-lookup:correct:review\",\"revision\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"schemaDigest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"},\"fields\":{},\"messages\":{\"count\":1,\"unread\":1,\"lastSentAt\":\"2026-11-27T00:00:00Z\",\"readerSide\":\"party\"},\"additionalForms\":{\"extra\":\"extra\"}},\"authority\":\"casework\",\"policy\":{\"id\":\"policy\",\"version\":\"one\",\"digest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"}}}]}", + "route": "batch", + "accept": true + }, + { + "name": "batchReaderLegacy", + "status": 200, + "body": "{\"items\":[{\"status\":\"visible\",\"id\":\"00000000-0000-4000-8000-000000000001\",\"context\":{\"id\":\"00000000-0000-4000-8000-000000000001\",\"actionId\":\"correct\",\"actionRevision\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"submissionVersion\":1,\"revision\":2,\"effectDigest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"reviewable\":true,\"subject\":{\"source\":\"proposal-lookup\",\"subjectType\":\"proposal\",\"id\":\"00000000-0000-4000-8000-000000000001\",\"version\":\"1\",\"digest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"},\"context\":{\"reference\":\"opaque\",\"contract\":{\"id\":\"urn:registry:breg:review-context:proposal-lookup:correct:review\",\"revision\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"schemaDigest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"},\"fields\":{},\"messages\":{\"count\":1,\"unread\":1,\"lastSentAt\":\"2026-11-27T00:00:00Z\"},\"additionalForms\":{\"extra\":\"extra\"}},\"authority\":\"casework\",\"policy\":{\"id\":\"policy\",\"version\":\"one\",\"digest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"}}}]}", + "route": "batch", + "accept": true + }, + { + "name": "batchReaderUnknown", + "status": 200, + "body": "{\"items\":[{\"status\":\"visible\",\"id\":\"00000000-0000-4000-8000-000000000001\",\"context\":{\"id\":\"00000000-0000-4000-8000-000000000001\",\"actionId\":\"correct\",\"actionRevision\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"submissionVersion\":1,\"revision\":2,\"effectDigest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"reviewable\":true,\"subject\":{\"source\":\"proposal-lookup\",\"subjectType\":\"proposal\",\"id\":\"00000000-0000-4000-8000-000000000001\",\"version\":\"1\",\"digest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"},\"context\":{\"reference\":\"opaque\",\"contract\":{\"id\":\"urn:registry:breg:review-context:proposal-lookup:correct:review\",\"revision\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"schemaDigest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"},\"fields\":{},\"messages\":{\"count\":1,\"unread\":1,\"lastSentAt\":\"2026-11-27T00:00:00Z\",\"readerSide\":\"observer\"},\"additionalForms\":{\"extra\":\"extra\"}},\"authority\":\"casework\",\"policy\":{\"id\":\"policy\",\"version\":\"one\",\"digest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"}}}]}", + "route": "batch", + "accept": false + }, + { + "name": "batchReaderNull", + "status": 200, + "body": "{\"items\":[{\"status\":\"visible\",\"id\":\"00000000-0000-4000-8000-000000000001\",\"context\":{\"id\":\"00000000-0000-4000-8000-000000000001\",\"actionId\":\"correct\",\"actionRevision\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"submissionVersion\":1,\"revision\":2,\"effectDigest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"reviewable\":true,\"subject\":{\"source\":\"proposal-lookup\",\"subjectType\":\"proposal\",\"id\":\"00000000-0000-4000-8000-000000000001\",\"version\":\"1\",\"digest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"},\"context\":{\"reference\":\"opaque\",\"contract\":{\"id\":\"urn:registry:breg:review-context:proposal-lookup:correct:review\",\"revision\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"schemaDigest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"},\"fields\":{},\"messages\":{\"count\":1,\"unread\":1,\"lastSentAt\":\"2026-11-27T00:00:00Z\",\"readerSide\":null},\"additionalForms\":{\"extra\":\"extra\"}},\"authority\":\"casework\",\"policy\":{\"id\":\"policy\",\"version\":\"one\",\"digest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"}}}]}", + "route": "batch", + "accept": false + }, + { + "name": "batchReaderObject", + "status": 200, + "body": "{\"items\":[{\"status\":\"visible\",\"id\":\"00000000-0000-4000-8000-000000000001\",\"context\":{\"id\":\"00000000-0000-4000-8000-000000000001\",\"actionId\":\"correct\",\"actionRevision\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"submissionVersion\":1,\"revision\":2,\"effectDigest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"reviewable\":true,\"subject\":{\"source\":\"proposal-lookup\",\"subjectType\":\"proposal\",\"id\":\"00000000-0000-4000-8000-000000000001\",\"version\":\"1\",\"digest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"},\"context\":{\"reference\":\"opaque\",\"contract\":{\"id\":\"urn:registry:breg:review-context:proposal-lookup:correct:review\",\"revision\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"schemaDigest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"},\"fields\":{},\"messages\":{\"count\":1,\"unread\":1,\"lastSentAt\":\"2026-11-27T00:00:00Z\",\"readerSide\":{\"official\":null}},\"additionalForms\":{\"extra\":\"extra\"}},\"authority\":\"casework\",\"policy\":{\"id\":\"policy\",\"version\":\"one\",\"digest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"}}}]}", + "route": "batch", + "accept": false + }, + { + "name": "contextForms8", + "status": 200, + "body": "{\"id\":\"00000000-0000-4000-8000-000000000001\",\"actionId\":\"correct\",\"actionRevision\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"submissionVersion\":1,\"revision\":2,\"effectDigest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"reviewable\":true,\"subject\":{\"source\":\"proposal-lookup\",\"subjectType\":\"proposal\",\"id\":\"00000000-0000-4000-8000-000000000001\",\"version\":\"1\",\"digest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"},\"context\":{\"reference\":\"opaque\",\"contract\":{\"id\":\"urn:registry:breg:review-context:proposal-lookup:correct:review\",\"revision\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"schemaDigest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"},\"fields\":{},\"messages\":{\"count\":1,\"unread\":1,\"lastSentAt\":\"2026-11-27T00:00:00Z\",\"items\":[{\"id\":\"00000000-0000-4000-8000-000000000002\",\"from\":\"official\",\"mine\":false,\"sentAt\":\"2026-11-27T00:00:00Z\",\"text\":\"Synthetic message\"}],\"links\":{\"list\":{\"method\":\"GET\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":2}},\"message\":{\"method\":\"POST\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":2},\"ifMatch\":\"\\\"condition\\\"\"},\"markRead\":{\"method\":\"POST\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages/read\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":2}}}},\"additionalForms\":{\"form-1\":\"form-1\",\"form-2\":\"form-2\",\"form-3\":\"form-3\",\"form-4\":\"form-4\",\"form-5\":\"form-5\",\"form-6\":\"form-6\",\"form-7\":\"form-7\",\"form-8\":\"form-8\"}}}", + "route": "context", + "accept": true + }, + { + "name": "contextForms9", + "status": 200, + "body": "{\"id\":\"00000000-0000-4000-8000-000000000001\",\"actionId\":\"correct\",\"actionRevision\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"submissionVersion\":1,\"revision\":2,\"effectDigest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"reviewable\":true,\"subject\":{\"source\":\"proposal-lookup\",\"subjectType\":\"proposal\",\"id\":\"00000000-0000-4000-8000-000000000001\",\"version\":\"1\",\"digest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"},\"context\":{\"reference\":\"opaque\",\"contract\":{\"id\":\"urn:registry:breg:review-context:proposal-lookup:correct:review\",\"revision\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"schemaDigest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"},\"fields\":{},\"messages\":{\"count\":1,\"unread\":1,\"lastSentAt\":\"2026-11-27T00:00:00Z\",\"items\":[{\"id\":\"00000000-0000-4000-8000-000000000002\",\"from\":\"official\",\"mine\":false,\"sentAt\":\"2026-11-27T00:00:00Z\",\"text\":\"Synthetic message\"}],\"links\":{\"list\":{\"method\":\"GET\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":2}},\"message\":{\"method\":\"POST\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":2},\"ifMatch\":\"\\\"condition\\\"\"},\"markRead\":{\"method\":\"POST\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages/read\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":2}}}},\"additionalForms\":{\"form-1\":\"form-1\",\"form-2\":\"form-2\",\"form-3\":\"form-3\",\"form-4\":\"form-4\",\"form-5\":\"form-5\",\"form-6\":\"form-6\",\"form-7\":\"form-7\",\"form-8\":\"form-8\",\"form-9\":\"form-9\"}}}", + "route": "context", + "accept": false + }, + { + "name": "batchForms8", + "status": 200, + "body": "{\"items\":[{\"status\":\"visible\",\"id\":\"00000000-0000-4000-8000-000000000001\",\"context\":{\"id\":\"00000000-0000-4000-8000-000000000001\",\"actionId\":\"correct\",\"actionRevision\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"submissionVersion\":1,\"revision\":2,\"effectDigest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"reviewable\":true,\"subject\":{\"source\":\"proposal-lookup\",\"subjectType\":\"proposal\",\"id\":\"00000000-0000-4000-8000-000000000001\",\"version\":\"1\",\"digest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"},\"context\":{\"reference\":\"opaque\",\"contract\":{\"id\":\"urn:registry:breg:review-context:proposal-lookup:correct:review\",\"revision\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"schemaDigest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"},\"fields\":{},\"messages\":{\"count\":1,\"unread\":1,\"lastSentAt\":\"2026-11-27T00:00:00Z\"},\"additionalForms\":{\"form-1\":\"form-1\",\"form-2\":\"form-2\",\"form-3\":\"form-3\",\"form-4\":\"form-4\",\"form-5\":\"form-5\",\"form-6\":\"form-6\",\"form-7\":\"form-7\",\"form-8\":\"form-8\"}},\"authority\":\"casework\",\"policy\":{\"id\":\"policy\",\"version\":\"one\",\"digest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"}}}]}", + "route": "batch", + "accept": true + }, + { + "name": "batchForms9", + "status": 200, + "body": "{\"items\":[{\"status\":\"visible\",\"id\":\"00000000-0000-4000-8000-000000000001\",\"context\":{\"id\":\"00000000-0000-4000-8000-000000000001\",\"actionId\":\"correct\",\"actionRevision\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"submissionVersion\":1,\"revision\":2,\"effectDigest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"reviewable\":true,\"subject\":{\"source\":\"proposal-lookup\",\"subjectType\":\"proposal\",\"id\":\"00000000-0000-4000-8000-000000000001\",\"version\":\"1\",\"digest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"},\"context\":{\"reference\":\"opaque\",\"contract\":{\"id\":\"urn:registry:breg:review-context:proposal-lookup:correct:review\",\"revision\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"schemaDigest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"},\"fields\":{},\"messages\":{\"count\":1,\"unread\":1,\"lastSentAt\":\"2026-11-27T00:00:00Z\"},\"additionalForms\":{\"form-1\":\"form-1\",\"form-2\":\"form-2\",\"form-3\":\"form-3\",\"form-4\":\"form-4\",\"form-5\":\"form-5\",\"form-6\":\"form-6\",\"form-7\":\"form-7\",\"form-8\":\"form-8\",\"form-9\":\"form-9\"}},\"authority\":\"casework\",\"policy\":{\"id\":\"policy\",\"version\":\"one\",\"digest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"}}}]}", + "route": "batch", + "accept": false + }, + { + "name": "messageForms8", + "status": 200, + "body": "{\"id\":\"00000000-0000-4000-8000-000000000001\",\"actionId\":\"correct\",\"actionRevision\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"submissionVersion\":1,\"revision\":3,\"effectDigest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"reviewable\":true,\"subject\":{\"source\":\"proposal-lookup\",\"subjectType\":\"proposal\",\"id\":\"00000000-0000-4000-8000-000000000001\",\"version\":\"1\",\"digest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"},\"context\":{\"reference\":\"opaque\",\"contract\":{\"id\":\"urn:registry:breg:review-context:proposal-lookup:correct:review\",\"revision\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"schemaDigest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"},\"fields\":{},\"messages\":{\"count\":1,\"unread\":1,\"lastSentAt\":\"2026-11-27T00:00:00Z\",\"items\":[{\"id\":\"00000000-0000-4000-8000-000000000002\",\"mine\":true,\"sentAt\":\"2026-11-27T00:00:00Z\",\"text\":\"Synthetic reply\",\"from\":\"official\"}],\"links\":{\"list\":{\"method\":\"GET\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":3}},\"message\":{\"method\":\"POST\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":3},\"ifMatch\":\"\\\"condition\\\"\"}}},\"additionalForms\":{\"form-1\":\"form-1\",\"form-2\":\"form-2\",\"form-3\":\"form-3\",\"form-4\":\"form-4\",\"form-5\":\"form-5\",\"form-6\":\"form-6\",\"form-7\":\"form-7\",\"form-8\":\"form-8\"}}}", + "route": "send", + "accept": true + }, + { + "name": "messageForms9", + "status": 200, + "body": "{\"id\":\"00000000-0000-4000-8000-000000000001\",\"actionId\":\"correct\",\"actionRevision\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"submissionVersion\":1,\"revision\":3,\"effectDigest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"reviewable\":true,\"subject\":{\"source\":\"proposal-lookup\",\"subjectType\":\"proposal\",\"id\":\"00000000-0000-4000-8000-000000000001\",\"version\":\"1\",\"digest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"},\"context\":{\"reference\":\"opaque\",\"contract\":{\"id\":\"urn:registry:breg:review-context:proposal-lookup:correct:review\",\"revision\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"schemaDigest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"},\"fields\":{},\"messages\":{\"count\":1,\"unread\":1,\"lastSentAt\":\"2026-11-27T00:00:00Z\",\"items\":[{\"id\":\"00000000-0000-4000-8000-000000000002\",\"mine\":true,\"sentAt\":\"2026-11-27T00:00:00Z\",\"text\":\"Synthetic reply\",\"from\":\"official\"}],\"links\":{\"list\":{\"method\":\"GET\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":3}},\"message\":{\"method\":\"POST\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":3},\"ifMatch\":\"\\\"condition\\\"\"}}},\"additionalForms\":{\"form-1\":\"form-1\",\"form-2\":\"form-2\",\"form-3\":\"form-3\",\"form-4\":\"form-4\",\"form-5\":\"form-5\",\"form-6\":\"form-6\",\"form-7\":\"form-7\",\"form-8\":\"form-8\",\"form-9\":\"form-9\"}}}", + "route": "send", + "accept": false + }, + { + "name": "contextFormsWrongNinth", + "status": 200, + "body": "{\"id\":\"00000000-0000-4000-8000-000000000001\",\"actionId\":\"correct\",\"actionRevision\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"submissionVersion\":1,\"revision\":2,\"effectDigest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"reviewable\":true,\"subject\":{\"source\":\"proposal-lookup\",\"subjectType\":\"proposal\",\"id\":\"00000000-0000-4000-8000-000000000001\",\"version\":\"1\",\"digest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"},\"context\":{\"reference\":\"opaque\",\"contract\":{\"id\":\"urn:registry:breg:review-context:proposal-lookup:correct:review\",\"revision\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"schemaDigest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"},\"fields\":{},\"messages\":{\"count\":1,\"unread\":1,\"lastSentAt\":\"2026-11-27T00:00:00Z\",\"items\":[{\"id\":\"00000000-0000-4000-8000-000000000002\",\"from\":\"official\",\"mine\":false,\"sentAt\":\"2026-11-27T00:00:00Z\",\"text\":\"Synthetic message\"}],\"links\":{\"list\":{\"method\":\"GET\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":2}},\"message\":{\"method\":\"POST\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":2},\"ifMatch\":\"\\\"condition\\\"\"},\"markRead\":{\"method\":\"POST\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages/read\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":2}}}},\"additionalForms\":{\"form-1\":\"form-1\",\"form-2\":\"form-2\",\"form-3\":\"form-3\",\"form-4\":\"form-4\",\"form-5\":\"form-5\",\"form-6\":\"form-6\",\"form-7\":\"form-7\",\"form-8\":\"form-8\",\"form-9\":7}}}", + "route": "context", + "accept": false + }, + { + "name": "getCreatedWithValidBody", + "status": 201, + "body": "{\"id\":\"00000000-0000-4000-8000-000000000001\",\"actionId\":\"correct\",\"actionRevision\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"submissionVersion\":1,\"revision\":2,\"state\":\"submitted\",\"links\":{\"self\":{\"method\":\"GET\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001\",\"accessProfile\":\"reader\",\"operation\":\"get\"},\"reviewContext\":{\"method\":\"GET\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/review-context\",\"accessProfile\":\"reader\",\"operation\":\"get-review-context\"},\"reviewStatus\":{\"method\":\"GET\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/review-status\",\"accessProfile\":\"reader\",\"operation\":\"get-review-status\"}},\"additionalForms\":{\"extra\":{\"id\":\"extra\",\"maximumCount\":2,\"items\":[{\"id\":\"00000000-0000-4000-8000-000000000002\",\"submissionVersion\":1,\"addedAt\":\"2026-11-27T00:00:00Z\",\"input\":{\"futureMember\":\"Declared input\"}}]}},\"messages\":{\"count\":1,\"unread\":1,\"lastSentAt\":\"2026-11-27T00:00:00Z\",\"items\":[{\"id\":\"00000000-0000-4000-8000-000000000002\",\"from\":\"official\",\"mine\":false,\"sentAt\":\"2026-11-27T00:00:00Z\",\"text\":\"Synthetic message\"}],\"links\":{\"list\":{\"method\":\"GET\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":2}},\"message\":{\"method\":\"POST\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":2},\"ifMatch\":\"\\\"condition\\\"\"},\"markRead\":{\"method\":\"POST\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages/read\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":2}}}},\"turn\":\"official\",\"effectDigest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"}", + "route": "get" + }, + { + "name": "getCreatedWithMalformedBody", + "status": 201, + "body": "{", + "route": "get" + }, + { + "name": "reviewReplyWithUnusedState", + "route": "send", + "status": 200, + "body": "{\"id\":\"00000000-0000-4000-8000-000000000001\",\"actionId\":\"correct\",\"actionRevision\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"submissionVersion\":1,\"revision\":3,\"effectDigest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"reviewable\":true,\"subject\":{\"source\":\"proposal-lookup\",\"subjectType\":\"proposal\",\"id\":\"00000000-0000-4000-8000-000000000001\",\"version\":\"1\",\"digest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"},\"context\":{\"reference\":\"opaque\",\"contract\":{\"id\":\"urn:registry:breg:review-context:proposal-lookup:correct:review\",\"revision\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"schemaDigest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"},\"fields\":{},\"messages\":{\"count\":1,\"unread\":1,\"lastSentAt\":\"2026-11-27T00:00:00Z\",\"items\":[{\"id\":\"00000000-0000-4000-8000-000000000002\",\"mine\":true,\"sentAt\":\"2026-11-27T00:00:00Z\",\"text\":\"Synthetic reply\",\"from\":\"official\"}],\"links\":{\"list\":{\"method\":\"GET\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":3}},\"message\":{\"method\":\"POST\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":3},\"ifMatch\":\"\\\"condition\\\"\"}}}},\"state\":\"future\",\"future\":true}", + "accept": true + }, + { + "name": "proposalReplyWithUnusedContext", + "route": "send", + "status": 200, + "body": "{\"id\":\"00000000-0000-4000-8000-000000000001\",\"actionId\":\"correct\",\"actionRevision\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"submissionVersion\":1,\"revision\":3,\"state\":\"submitted\",\"links\":{\"self\":{\"method\":\"GET\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001\",\"accessProfile\":\"reader\",\"operation\":\"get\"}},\"additionalForms\":{\"extra\":{\"id\":\"extra\",\"maximumCount\":2,\"items\":[{\"id\":\"00000000-0000-4000-8000-000000000002\",\"submissionVersion\":1,\"addedAt\":\"2026-11-27T00:00:00Z\",\"input\":{\"futureMember\":\"Declared input\"}}]}},\"messages\":{\"count\":1,\"unread\":1,\"lastSentAt\":\"2026-11-27T00:00:00Z\",\"items\":[{\"id\":\"00000000-0000-4000-8000-000000000002\",\"mine\":true,\"sentAt\":\"2026-11-27T00:00:00Z\",\"text\":\"Synthetic reply\",\"from\":\"official\"}],\"links\":{\"list\":{\"method\":\"GET\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":3}},\"message\":{\"method\":\"POST\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":3},\"ifMatch\":\"\\\"condition\\\"\"}}},\"turn\":\"official\",\"effectDigest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"context\":{\"future\":true}}", + "accept": true + }, + { + "name": "threadReplyWithUnusedAction", + "route": "send", + "status": 200, + "body": "{\"count\":1,\"unread\":1,\"lastSentAt\":\"2026-11-27T00:00:00Z\",\"items\":[{\"id\":\"00000000-0000-4000-8000-000000000002\",\"mine\":true,\"sentAt\":\"2026-11-27T00:00:00Z\",\"text\":\"Synthetic reply\",\"from\":\"official\"}],\"links\":{\"list\":{\"method\":\"GET\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":3}},\"message\":{\"method\":\"POST\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":3},\"ifMatch\":\"\\\"condition\\\"\"}},\"actionId\":\"future\"}", + "accept": true + }, + { + "name": "ambiguousReviewAndThreadReply", + "route": "send", + "status": 200, + "body": "{\"id\":\"00000000-0000-4000-8000-000000000001\",\"actionId\":\"correct\",\"actionRevision\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"submissionVersion\":1,\"revision\":3,\"effectDigest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"reviewable\":true,\"subject\":{\"source\":\"proposal-lookup\",\"subjectType\":\"proposal\",\"id\":\"00000000-0000-4000-8000-000000000001\",\"version\":\"1\",\"digest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"},\"context\":{\"reference\":\"opaque\",\"contract\":{\"id\":\"urn:registry:breg:review-context:proposal-lookup:correct:review\",\"revision\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"schemaDigest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"},\"fields\":{},\"messages\":{\"count\":1,\"unread\":1,\"lastSentAt\":\"2026-11-27T00:00:00Z\",\"items\":[{\"id\":\"00000000-0000-4000-8000-000000000002\",\"mine\":true,\"sentAt\":\"2026-11-27T00:00:00Z\",\"text\":\"Synthetic reply\",\"from\":\"official\"}],\"links\":{\"list\":{\"method\":\"GET\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":3}},\"message\":{\"method\":\"POST\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":3},\"ifMatch\":\"\\\"condition\\\"\"}}}},\"count\":1,\"unread\":1,\"lastSentAt\":\"2026-11-27T00:00:00Z\",\"items\":[{\"id\":\"00000000-0000-4000-8000-000000000002\",\"mine\":true,\"sentAt\":\"2026-11-27T00:00:00Z\",\"text\":\"Synthetic reply\",\"from\":\"official\"}],\"links\":{\"list\":{\"method\":\"GET\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":3}},\"message\":{\"method\":\"POST\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":3},\"ifMatch\":\"\\\"condition\\\"\"}}}", + "accept": false + }, + { + "name": "reviewMarkReviewReply", + "route": "reviewMark", + "status": 200, + "body": "{\"id\":\"00000000-0000-4000-8000-000000000001\",\"actionId\":\"correct\",\"actionRevision\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"submissionVersion\":1,\"revision\":3,\"effectDigest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"reviewable\":true,\"subject\":{\"source\":\"proposal-lookup\",\"subjectType\":\"proposal\",\"id\":\"00000000-0000-4000-8000-000000000001\",\"version\":\"1\",\"digest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"},\"context\":{\"reference\":\"opaque\",\"contract\":{\"id\":\"urn:registry:breg:review-context:proposal-lookup:correct:review\",\"revision\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"schemaDigest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"},\"fields\":{},\"messages\":{\"count\":1,\"unread\":1,\"lastSentAt\":\"2026-11-27T00:00:00Z\",\"items\":[{\"id\":\"00000000-0000-4000-8000-000000000002\",\"mine\":true,\"sentAt\":\"2026-11-27T00:00:00Z\",\"text\":\"Synthetic reply\",\"from\":\"official\"}],\"links\":{\"list\":{\"method\":\"GET\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":3}},\"message\":{\"method\":\"POST\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":3},\"ifMatch\":\"\\\"condition\\\"\"}}}}}", + "accept": true + }, + { + "name": "reviewMarkProposalReply", + "route": "reviewMark", + "status": 200, + "body": "{\"id\":\"00000000-0000-4000-8000-000000000001\",\"actionId\":\"correct\",\"actionRevision\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"submissionVersion\":1,\"revision\":3,\"state\":\"submitted\",\"links\":{\"self\":{\"method\":\"GET\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001\",\"accessProfile\":\"reader\",\"operation\":\"get\"}},\"additionalForms\":{\"extra\":{\"id\":\"extra\",\"maximumCount\":2,\"items\":[{\"id\":\"00000000-0000-4000-8000-000000000002\",\"submissionVersion\":1,\"addedAt\":\"2026-11-27T00:00:00Z\",\"input\":{\"futureMember\":\"Declared input\"}}]}},\"messages\":{\"count\":1,\"unread\":1,\"lastSentAt\":\"2026-11-27T00:00:00Z\",\"items\":[{\"id\":\"00000000-0000-4000-8000-000000000002\",\"mine\":true,\"sentAt\":\"2026-11-27T00:00:00Z\",\"text\":\"Synthetic reply\",\"from\":\"official\"}],\"links\":{\"list\":{\"method\":\"GET\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":3}},\"message\":{\"method\":\"POST\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":3},\"ifMatch\":\"\\\"condition\\\"\"}}},\"turn\":\"official\",\"effectDigest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"}", + "accept": true + }, + { + "name": "reviewMarkThreadReply", + "route": "reviewMark", + "status": 200, + "body": "{\"count\":1,\"unread\":1,\"lastSentAt\":\"2026-11-27T00:00:00Z\",\"items\":[{\"id\":\"00000000-0000-4000-8000-000000000002\",\"mine\":true,\"sentAt\":\"2026-11-27T00:00:00Z\",\"text\":\"Synthetic reply\",\"from\":\"official\"}],\"links\":{\"list\":{\"method\":\"GET\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":3}},\"message\":{\"method\":\"POST\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":3},\"ifMatch\":\"\\\"condition\\\"\"}}}", + "accept": true + }, + { + "name": "proposalMarkNoContent", + "route": "mark", + "status": 204, + "body": "", + "accept": true + }, + { + "name": "reviewMarkNoContent", + "route": "reviewMark", + "status": 204, + "body": "", + "accept": true + }, + { + "name": "reviewMarkMediaOnNoContent", + "route": "reviewMark", + "status": 204, + "body": "", + "accept": false, + "headerFault": "media", + "failure": "media-type" + }, + { + "name": "reviewMarkNoContentWithFraming", + "route": "reviewMark", + "status": 204, + "body": "", + "accept": false, + "headerFault": "framing", + "failure": "body" + }, + { + "name": "reviewMarkNoContentWithoutCache", + "route": "reviewMark", + "status": 204, + "body": "", + "accept": false, + "headerFault": "cache", + "failure": "cache-policy" + }, + { + "name": "reviewMarkNoContentWithBadTrace", + "route": "reviewMark", + "status": 204, + "body": "", + "accept": false, + "headerFault": "trace", + "failure": "trace-context" + }, + { + "name": "sendRefusesNoContent", + "route": "send", + "status": 204, + "body": "", + "accept": false, + "failure": "status" + }, + { + "name": "proposalReplyWithUnusedCounts", + "status": 200, + "body": "{\"id\":\"00000000-0000-4000-8000-000000000001\",\"actionId\":\"correct\",\"actionRevision\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"submissionVersion\":1,\"revision\":3,\"state\":\"submitted\",\"links\":{\"self\":{\"method\":\"GET\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001\",\"accessProfile\":\"reader\",\"operation\":\"get\"}},\"additionalForms\":{\"extra\":{\"id\":\"extra\",\"maximumCount\":2,\"items\":[{\"id\":\"00000000-0000-4000-8000-000000000002\",\"submissionVersion\":1,\"addedAt\":\"2026-11-27T00:00:00Z\",\"input\":{\"futureMember\":\"Declared input\"}}]}},\"messages\":{\"count\":1,\"unread\":1,\"lastSentAt\":\"2026-11-27T00:00:00Z\",\"items\":[{\"id\":\"00000000-0000-4000-8000-000000000002\",\"mine\":true,\"sentAt\":\"2026-11-27T00:00:00Z\",\"text\":\"Synthetic reply\",\"from\":\"official\"}],\"links\":{\"list\":{\"method\":\"GET\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":3}},\"message\":{\"method\":\"POST\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":3},\"ifMatch\":\"\\\"condition\\\"\"}}},\"turn\":\"official\",\"effectDigest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"count\":17,\"unread\":7}", + "route": "send", + "accept": true + }, + { + "name": "threadUnavailablePair", + "route": "send", + "status": 200, + "body": "{\"count\":1,\"unread\":1,\"lastSentAt\":\"2026-11-27T00:00:00Z\",\"items\":[{\"id\":\"00000000-0000-4000-8000-000000000002\",\"mine\":true,\"sentAt\":\"2026-11-27T00:00:00Z\",\"text\":\"Synthetic reply\",\"from\":\"official\"}],\"links\":{\"list\":{\"method\":\"GET\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":3}},\"message\":{\"method\":\"POST\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":false,\"observedRevision\":3,\"reason\":\"limit-reached\",\"recovery\":\"receipt-only\"},\"ifMatch\":\"\\\"condition\\\"\"}}}", + "accept": true + }, + { + "name": "threadUnavailableMissingReason", + "route": "send", + "status": 200, + "body": "{\"count\":1,\"unread\":1,\"lastSentAt\":\"2026-11-27T00:00:00Z\",\"items\":[{\"id\":\"00000000-0000-4000-8000-000000000002\",\"mine\":true,\"sentAt\":\"2026-11-27T00:00:00Z\",\"text\":\"Synthetic reply\",\"from\":\"official\"}],\"links\":{\"list\":{\"method\":\"GET\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":3}},\"message\":{\"method\":\"POST\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":false,\"observedRevision\":3,\"recovery\":\"receipt-only\"},\"ifMatch\":\"\\\"condition\\\"\"}}}", + "accept": false + }, + { + "name": "threadUnavailableMissingRecovery", + "route": "send", + "status": 200, + "body": "{\"count\":1,\"unread\":1,\"lastSentAt\":\"2026-11-27T00:00:00Z\",\"items\":[{\"id\":\"00000000-0000-4000-8000-000000000002\",\"mine\":true,\"sentAt\":\"2026-11-27T00:00:00Z\",\"text\":\"Synthetic reply\",\"from\":\"official\"}],\"links\":{\"list\":{\"method\":\"GET\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":3}},\"message\":{\"method\":\"POST\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":false,\"observedRevision\":3,\"reason\":\"limit-reached\"},\"ifMatch\":\"\\\"condition\\\"\"}}}", + "accept": false + }, + { + "name": "threadUnavailableMismatchedRecovery", + "route": "send", + "status": 200, + "body": "{\"count\":1,\"unread\":1,\"lastSentAt\":\"2026-11-27T00:00:00Z\",\"items\":[{\"id\":\"00000000-0000-4000-8000-000000000002\",\"mine\":true,\"sentAt\":\"2026-11-27T00:00:00Z\",\"text\":\"Synthetic reply\",\"from\":\"official\"}],\"links\":{\"list\":{\"method\":\"GET\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":3}},\"message\":{\"method\":\"POST\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":false,\"observedRevision\":3,\"reason\":\"limit-reached\",\"recovery\":\"retry\"},\"ifMatch\":\"\\\"condition\\\"\"}}}", + "accept": false + }, + { + "name": "threadAvailableWithRefusalPair", + "route": "send", + "status": 200, + "body": "{\"count\":1,\"unread\":1,\"lastSentAt\":\"2026-11-27T00:00:00Z\",\"items\":[{\"id\":\"00000000-0000-4000-8000-000000000002\",\"mine\":true,\"sentAt\":\"2026-11-27T00:00:00Z\",\"text\":\"Synthetic reply\",\"from\":\"official\"}],\"links\":{\"list\":{\"method\":\"GET\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":3}},\"message\":{\"method\":\"POST\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":3,\"reason\":\"limit-reached\",\"recovery\":\"receipt-only\"},\"ifMatch\":\"\\\"condition\\\"\"}}}", + "accept": false + }, + { + "name": "reviewReplyWithBrokenOuterThread", + "route": "send", + "status": 200, + "body": "{\"id\":\"00000000-0000-4000-8000-000000000001\",\"actionId\":\"correct\",\"actionRevision\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"submissionVersion\":1,\"revision\":3,\"effectDigest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"reviewable\":true,\"subject\":{\"source\":\"proposal-lookup\",\"subjectType\":\"proposal\",\"id\":\"00000000-0000-4000-8000-000000000001\",\"version\":\"1\",\"digest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"},\"context\":{\"reference\":\"opaque\",\"contract\":{\"id\":\"urn:registry:breg:review-context:proposal-lookup:correct:review\",\"revision\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"schemaDigest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"},\"fields\":{},\"messages\":{\"count\":1,\"unread\":1,\"lastSentAt\":\"2026-11-27T00:00:00Z\",\"items\":[{\"id\":\"00000000-0000-4000-8000-000000000002\",\"mine\":true,\"sentAt\":\"2026-11-27T00:00:00Z\",\"text\":\"Synthetic reply\",\"from\":\"official\"}],\"links\":{\"list\":{\"method\":\"GET\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":3}},\"message\":{\"method\":\"POST\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":3},\"ifMatch\":\"\\\"condition\\\"\"}}}},\"count\":1,\"unread\":1,\"lastSentAt\":\"2026-11-27T00:00:00Z\",\"items\":[{\"id\":\"00000000-0000-4000-8000-000000000002\",\"mine\":true,\"sentAt\":\"2026-11-27T00:00:00Z\",\"text\":\"Synthetic reply\",\"from\":\"official\"}],\"links\":{\"list\":{\"method\":\"GET\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":3}},\"message\":{\"method\":\"POST\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":false,\"observedRevision\":3,\"reason\":\"limit-reached\"},\"ifMatch\":\"\\\"condition\\\"\"}}}", + "accept": true + }, + { + "name": "proposalThreadUnavailableMissingRecovery", + "route": "get", + "status": 200, + "body": "{\"id\":\"00000000-0000-4000-8000-000000000001\",\"actionId\":\"correct\",\"actionRevision\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"submissionVersion\":1,\"revision\":2,\"state\":\"submitted\",\"links\":{\"self\":{\"method\":\"GET\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001\",\"accessProfile\":\"reader\",\"operation\":\"get\"},\"reviewContext\":{\"method\":\"GET\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/review-context\",\"accessProfile\":\"reader\",\"operation\":\"get-review-context\"},\"reviewStatus\":{\"method\":\"GET\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/review-status\",\"accessProfile\":\"reader\",\"operation\":\"get-review-status\"}},\"additionalForms\":{\"extra\":{\"id\":\"extra\",\"maximumCount\":2,\"items\":[{\"id\":\"00000000-0000-4000-8000-000000000002\",\"submissionVersion\":1,\"addedAt\":\"2026-11-27T00:00:00Z\",\"input\":{\"futureMember\":\"Declared input\"}}]}},\"messages\":{\"count\":1,\"unread\":1,\"lastSentAt\":\"2026-11-27T00:00:00Z\",\"items\":[{\"id\":\"00000000-0000-4000-8000-000000000002\",\"from\":\"official\",\"mine\":false,\"sentAt\":\"2026-11-27T00:00:00Z\",\"text\":\"Synthetic message\"}],\"links\":{\"list\":{\"method\":\"GET\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":2}},\"message\":{\"method\":\"POST\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":false,\"observedRevision\":2,\"reason\":\"limit-reached\"},\"ifMatch\":\"\\\"condition\\\"\"},\"markRead\":{\"method\":\"POST\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages/read\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":2}}}},\"turn\":\"official\",\"effectDigest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"}", + "accept": false + }, + { + "name": "contextThreadUnavailableMissingRecovery", + "route": "context", + "status": 200, + "body": "{\"id\":\"00000000-0000-4000-8000-000000000001\",\"actionId\":\"correct\",\"actionRevision\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"submissionVersion\":1,\"revision\":2,\"effectDigest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"reviewable\":true,\"subject\":{\"source\":\"proposal-lookup\",\"subjectType\":\"proposal\",\"id\":\"00000000-0000-4000-8000-000000000001\",\"version\":\"1\",\"digest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"},\"context\":{\"reference\":\"opaque\",\"contract\":{\"id\":\"urn:registry:breg:review-context:proposal-lookup:correct:review\",\"revision\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"schemaDigest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"},\"fields\":{},\"messages\":{\"count\":1,\"unread\":1,\"lastSentAt\":\"2026-11-27T00:00:00Z\",\"items\":[{\"id\":\"00000000-0000-4000-8000-000000000002\",\"from\":\"official\",\"mine\":false,\"sentAt\":\"2026-11-27T00:00:00Z\",\"text\":\"Synthetic message\"}],\"links\":{\"list\":{\"method\":\"GET\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":2}},\"message\":{\"method\":\"POST\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":false,\"observedRevision\":2,\"reason\":\"limit-reached\"},\"ifMatch\":\"\\\"condition\\\"\"},\"markRead\":{\"method\":\"POST\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages/read\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":2}}}},\"additionalForms\":{\"extra\":\"extra\"}}}", + "accept": false + }, + { + "name": "pageThreadUnavailablePair", + "route": "page", + "status": 200, + "body": "{\"items\":[{\"id\":\"00000000-0000-4000-8000-000000000002\",\"mine\":true,\"sentAt\":\"2026-11-27T00:00:00Z\",\"text\":\"Synthetic reply\",\"from\":\"official\"}],\"links\":{\"list\":{\"method\":\"GET\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":3}},\"message\":{\"method\":\"POST\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":false,\"observedRevision\":3,\"reason\":\"limit-reached\",\"recovery\":\"receipt-only\"},\"ifMatch\":\"\\\"condition\\\"\"}}}", + "accept": true + }, + { + "name": "pageThreadUnavailableMissingRecovery", + "route": "page", + "status": 200, + "body": "{\"items\":[{\"id\":\"00000000-0000-4000-8000-000000000002\",\"mine\":true,\"sentAt\":\"2026-11-27T00:00:00Z\",\"text\":\"Synthetic reply\",\"from\":\"official\"}],\"links\":{\"list\":{\"method\":\"GET\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":3}},\"message\":{\"method\":\"POST\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":false,\"observedRevision\":3,\"reason\":\"limit-reached\"},\"ifMatch\":\"\\\"condition\\\"\"}}}", + "accept": false + }, + { + "name": "reviewSendIdOnlyPolicy", + "route": "send", + "status": 200, + "body": "{\"id\":\"00000000-0000-4000-8000-000000000001\",\"actionId\":\"correct\",\"actionRevision\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"submissionVersion\":1,\"revision\":3,\"effectDigest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"reviewable\":true,\"subject\":{\"source\":\"proposal-lookup\",\"subjectType\":\"proposal\",\"id\":\"00000000-0000-4000-8000-000000000001\",\"version\":\"1\",\"digest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"},\"context\":{\"reference\":\"opaque\",\"contract\":{\"id\":\"urn:registry:breg:review-context:proposal-lookup:correct:review\",\"revision\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"schemaDigest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"},\"fields\":{},\"messages\":{\"count\":1,\"unread\":1,\"lastSentAt\":\"2026-11-27T00:00:00Z\",\"items\":[{\"id\":\"00000000-0000-4000-8000-000000000002\",\"mine\":true,\"sentAt\":\"2026-11-27T00:00:00Z\",\"text\":\"Synthetic reply\",\"from\":\"official\"}],\"links\":{\"list\":{\"method\":\"GET\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":3}},\"message\":{\"method\":\"POST\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":3},\"ifMatch\":\"\\\"condition\\\"\"}}}},\"authority\":\"provider\",\"policy\":{\"id\":\"case-review\"}}", + "accept": true + }, + { + "name": "reviewSendPinnedPolicy", + "route": "send", + "status": 200, + "body": "{\"id\":\"00000000-0000-4000-8000-000000000001\",\"actionId\":\"correct\",\"actionRevision\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"submissionVersion\":1,\"revision\":3,\"effectDigest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"reviewable\":true,\"subject\":{\"source\":\"proposal-lookup\",\"subjectType\":\"proposal\",\"id\":\"00000000-0000-4000-8000-000000000001\",\"version\":\"1\",\"digest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"},\"context\":{\"reference\":\"opaque\",\"contract\":{\"id\":\"urn:registry:breg:review-context:proposal-lookup:correct:review\",\"revision\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"schemaDigest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"},\"fields\":{},\"messages\":{\"count\":1,\"unread\":1,\"lastSentAt\":\"2026-11-27T00:00:00Z\",\"items\":[{\"id\":\"00000000-0000-4000-8000-000000000002\",\"mine\":true,\"sentAt\":\"2026-11-27T00:00:00Z\",\"text\":\"Synthetic reply\",\"from\":\"official\"}],\"links\":{\"list\":{\"method\":\"GET\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":3}},\"message\":{\"method\":\"POST\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":3},\"ifMatch\":\"\\\"condition\\\"\"}}}},\"authority\":\"provider\",\"policy\":{\"id\":\"case-review\",\"version\":\"2\",\"digest\":\"sha256:bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\"}}", + "accept": true + }, + { + "name": "reviewSendPolicyMissingDigest", + "route": "send", + "status": 200, + "body": "{\"id\":\"00000000-0000-4000-8000-000000000001\",\"actionId\":\"correct\",\"actionRevision\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"submissionVersion\":1,\"revision\":3,\"effectDigest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"reviewable\":true,\"subject\":{\"source\":\"proposal-lookup\",\"subjectType\":\"proposal\",\"id\":\"00000000-0000-4000-8000-000000000001\",\"version\":\"1\",\"digest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"},\"context\":{\"reference\":\"opaque\",\"contract\":{\"id\":\"urn:registry:breg:review-context:proposal-lookup:correct:review\",\"revision\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"schemaDigest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"},\"fields\":{},\"messages\":{\"count\":1,\"unread\":1,\"lastSentAt\":\"2026-11-27T00:00:00Z\",\"items\":[{\"id\":\"00000000-0000-4000-8000-000000000002\",\"mine\":true,\"sentAt\":\"2026-11-27T00:00:00Z\",\"text\":\"Synthetic reply\",\"from\":\"official\"}],\"links\":{\"list\":{\"method\":\"GET\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":3}},\"message\":{\"method\":\"POST\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":3},\"ifMatch\":\"\\\"condition\\\"\"}}}},\"authority\":\"provider\",\"policy\":{\"id\":\"case-review\",\"version\":\"2\"}}", + "accept": false + }, + { + "name": "reviewSendPolicyMissingVersion", + "route": "send", + "status": 200, + "body": "{\"id\":\"00000000-0000-4000-8000-000000000001\",\"actionId\":\"correct\",\"actionRevision\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"submissionVersion\":1,\"revision\":3,\"effectDigest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"reviewable\":true,\"subject\":{\"source\":\"proposal-lookup\",\"subjectType\":\"proposal\",\"id\":\"00000000-0000-4000-8000-000000000001\",\"version\":\"1\",\"digest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"},\"context\":{\"reference\":\"opaque\",\"contract\":{\"id\":\"urn:registry:breg:review-context:proposal-lookup:correct:review\",\"revision\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"schemaDigest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"},\"fields\":{},\"messages\":{\"count\":1,\"unread\":1,\"lastSentAt\":\"2026-11-27T00:00:00Z\",\"items\":[{\"id\":\"00000000-0000-4000-8000-000000000002\",\"mine\":true,\"sentAt\":\"2026-11-27T00:00:00Z\",\"text\":\"Synthetic reply\",\"from\":\"official\"}],\"links\":{\"list\":{\"method\":\"GET\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":3}},\"message\":{\"method\":\"POST\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":3},\"ifMatch\":\"\\\"condition\\\"\"}}}},\"authority\":\"provider\",\"policy\":{\"id\":\"case-review\",\"digest\":\"sha256:bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\"}}", + "accept": false + }, + { + "name": "threadProblemInvalidLimit", + "route": "page", + "status": 400, + "body": "{\"type\":\"https://id.registrystack.org/problems/registry-breg/request/invalid\",\"title\":\"Bad Request\",\"status\":400,\"detail\":\"The request is invalid.\",\"code\":\"request.invalid\",\"traceId\":\"4bf92f3577b34da6a3ce929d0e0e4736\",\"fieldPath\":\"limit\"}", + "accept": true + }, + { + "name": "threadProblemDuplicateCursor", + "route": "page", + "status": 400, + "body": "{\"type\":\"https://id.registrystack.org/problems/registry-breg/request/invalid\",\"title\":\"Bad Request\",\"status\":400,\"detail\":\"The request is invalid.\",\"code\":\"request.invalid\",\"traceId\":\"4bf92f3577b34da6a3ce929d0e0e4736\",\"fieldPath\":\"cursor\"}", + "accept": true + }, + { + "name": "threadProblemInvalidCursor", + "route": "page", + "status": 400, + "body": "{\"type\":\"https://id.registrystack.org/problems/registry-breg/query/cursor-invalid\",\"title\":\"Bad Request\",\"status\":400,\"detail\":\"The request is invalid.\",\"code\":\"query.cursor-invalid\",\"traceId\":\"4bf92f3577b34da6a3ce929d0e0e4736\",\"fieldPath\":\"cursor\"}", + "accept": true + }, + { + "name": "threadProblemCursorCodeAtLimit", + "route": "page", + "status": 400, + "body": "{\"type\":\"https://id.registrystack.org/problems/registry-breg/query/cursor-invalid\",\"title\":\"Bad Request\",\"status\":400,\"detail\":\"The request is invalid.\",\"code\":\"query.cursor-invalid\",\"traceId\":\"4bf92f3577b34da6a3ce929d0e0e4736\",\"fieldPath\":\"limit\"}", + "accept": false + }, + { + "name": "threadProblemInvalidAtStatus", + "route": "page", + "status": 400, + "body": "{\"type\":\"https://id.registrystack.org/problems/registry-breg/request/invalid\",\"title\":\"Bad Request\",\"status\":400,\"detail\":\"The request is invalid.\",\"code\":\"request.invalid\",\"traceId\":\"4bf92f3577b34da6a3ce929d0e0e4736\",\"fieldPath\":\"status\"}", + "accept": false + }, + { + "name": "threadProblemLimitOnProposalGet", + "route": "get", + "status": 400, + "body": "{\"type\":\"https://id.registrystack.org/problems/registry-breg/request/invalid\",\"title\":\"Bad Request\",\"status\":400,\"detail\":\"The request is invalid.\",\"code\":\"request.invalid\",\"traceId\":\"4bf92f3577b34da6a3ce929d0e0e4736\",\"fieldPath\":\"limit\"}", + "accept": false + }, + { + "name": "threadProblemLimitOnSend", + "route": "send", + "status": 400, + "body": "{\"type\":\"https://id.registrystack.org/problems/registry-breg/request/invalid\",\"title\":\"Bad Request\",\"status\":400,\"detail\":\"The request is invalid.\",\"code\":\"request.invalid\",\"traceId\":\"4bf92f3577b34da6a3ce929d0e0e4736\",\"fieldPath\":\"limit\"}", + "accept": false + } + ], + "heldProposal": "{\"id\":\"00000000-0000-4000-8000-000000000001\",\"actionId\":\"correct\",\"actionRevision\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"submissionVersion\":1,\"revision\":2,\"state\":\"submitted\",\"links\":{\"self\":{\"method\":\"GET\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001\",\"accessProfile\":\"reader\",\"operation\":\"get\"},\"reviewContext\":{\"method\":\"GET\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/review-context\",\"accessProfile\":\"reader\",\"operation\":\"get-review-context\"},\"reviewStatus\":{\"method\":\"GET\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/review-status\",\"accessProfile\":\"reader\",\"operation\":\"get-review-status\"}},\"additionalForms\":{\"extra\":{\"id\":\"extra\",\"maximumCount\":2,\"items\":[{\"id\":\"00000000-0000-4000-8000-000000000002\",\"submissionVersion\":1,\"addedAt\":\"2026-11-27T00:00:00Z\",\"input\":{\"futureMember\":\"Declared input\"}}]}},\"messages\":{\"count\":1,\"unread\":1,\"lastSentAt\":\"2026-11-27T00:00:00Z\",\"items\":[{\"id\":\"00000000-0000-4000-8000-000000000002\",\"from\":\"official\",\"mine\":false,\"sentAt\":\"2026-11-27T00:00:00Z\",\"text\":\"Synthetic message\"}],\"links\":{\"list\":{\"method\":\"GET\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":2}},\"message\":{\"method\":\"POST\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":2},\"ifMatch\":\"\\\"condition\\\"\"},\"markRead\":{\"method\":\"POST\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages/read\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":2}}}},\"turn\":\"official\",\"effectDigest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"}", + "heldReview": "{\"id\":\"00000000-0000-4000-8000-000000000001\",\"actionId\":\"correct\",\"actionRevision\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"submissionVersion\":1,\"revision\":2,\"effectDigest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"reviewable\":true,\"subject\":{\"source\":\"proposal-lookup\",\"subjectType\":\"proposal\",\"id\":\"00000000-0000-4000-8000-000000000001\",\"version\":\"1\",\"digest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"},\"context\":{\"reference\":\"opaque\",\"contract\":{\"id\":\"urn:registry:breg:review-context:proposal-lookup:correct:review\",\"revision\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"schemaDigest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"},\"fields\":{},\"messages\":{\"count\":1,\"unread\":1,\"lastSentAt\":\"2026-11-27T00:00:00Z\",\"items\":[{\"id\":\"00000000-0000-4000-8000-000000000002\",\"from\":\"official\",\"mine\":false,\"sentAt\":\"2026-11-27T00:00:00Z\",\"text\":\"Synthetic message\"}],\"links\":{\"list\":{\"method\":\"GET\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":2}},\"message\":{\"method\":\"POST\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":2},\"ifMatch\":\"\\\"condition\\\"\"},\"markRead\":{\"method\":\"POST\",\"path\":\"/v1/proposals/00000000-0000-4000-8000-000000000001/messages/read\",\"accessProfile\":\"reader\",\"operation\":\"message\",\"availability\":{\"available\":true,\"observedRevision\":2}}}}}}" +} diff --git a/crates/registry-breg-client/tests/http_boundary.rs b/crates/registry-breg-client/tests/http_boundary.rs index e7ebbd994a..eef33f4c0b 100644 --- a/crates/registry-breg-client/tests/http_boundary.rs +++ b/crates/registry-breg-client/tests/http_boundary.rs @@ -58,6 +58,7 @@ enum Mode { TraceUppercase, TraceDuplicate, ChangedProblemProse, + DuplicateProbeExtension, UnknownProblem(u16, Option), Redirect, ConcealedNotFound, @@ -110,6 +111,12 @@ async fn handler(State(state): State, request: Request) -> Resp } Mode::Redirect => redirect_response(), Mode::ChangedProblemProse => changed_problem_prose(), + Mode::DuplicateProbeExtension => response( + StatusCode::OK, + "application/json", + br#"{"status":"alive","future":{"flag":true,"flag":false}}"#, + Some(TRACEPARENT), + ), Mode::UnknownProblem(status, change) => unknown_problem(status, change), Mode::ConcealedNotFound => registered_problem(BRegProblemCode::ResourceNotFound), Mode::TraceMissing => response( @@ -1026,6 +1033,18 @@ async fn derived_response_limits_retain_credentials_and_leave_the_original_bound assert_eq!(requests[0].authorization, requests[1].authorization); } +#[tokio::test] +async fn probe_status_rejects_duplicate_members_in_ignored_extensions() { + let (client, _) = test_client(Mode::DuplicateProbeExtension, None, 1024).await; + assert!(matches!( + client.health().await, + Err(BaseRegistryClientError::Protocol { + failure: BRegProtocolFailure::Body, + .. + }) + )); +} + #[test] fn probe_status_ignores_members_it_does_not_know() { let status: registry_breg_client::BRegProbeStatus = serde_json::from_str( diff --git a/crates/registry-breg-client/tests/proposal_document_boundary.rs b/crates/registry-breg-client/tests/proposal_document_boundary.rs index 29b93a97bf..1e5a475427 100644 --- a/crates/registry-breg-client/tests/proposal_document_boundary.rs +++ b/crates/registry-breg-client/tests/proposal_document_boundary.rs @@ -63,6 +63,23 @@ impl Fixture { })) .fallback(any(|State((value, requests)): State<(Arc>, Arc)>| async move { requests.fetch_add(1, Ordering::SeqCst); + let mut value = value.lock().unwrap().clone(); + let supply_current_turn = |proposal: &mut Value| { + let turn = match proposal["state"].as_str() { + Some("draft") => "party", + Some("submitted") => "official", + Some("applied" | "cancelled" | "rejected") => "nobody", + _ => return, + }; + if proposal.get("turn").is_none() { + proposal["turn"] = json!(turn); + } + }; + if let Some(items) = value.get_mut("items").and_then(Value::as_array_mut) { + items.iter_mut().for_each(supply_current_turn); + } else { + supply_current_turn(&mut value); + } ( [ ( @@ -72,7 +89,7 @@ impl Fixture { ("cache-control", "no-store"), ("vary", "authorization, accept"), ], - Json(value.lock().unwrap().clone()), + Json(value), ) })) .with_state((response.clone(), requests.clone())); @@ -213,7 +230,7 @@ async fn retained_decision_follows_its_review_result() { cases.push((Value::Null, false)); for (review, expected) in cases { fixture.answer(json!({"id":ID,"actionId":"correct","submissionVersion":1, - "current":true,"effectDigest":DIGEST,"review":review,"decision":decision})); + "current":true,"effectDigest":DIGEST,"review":review,"application":null,"decision":decision})); if fixture .client .read_proposal_submission(&held, 1) @@ -641,7 +658,7 @@ async fn public_reasons_follow_the_review_text_rules_in_current_and_retained_rea let mut current = proposal("rejected"); current["decision"] = decision.clone(); let submission = json!({"id":ID,"actionId":"correct","submissionVersion":1, - "current":true,"effectDigest":DIGEST,"review":terminal("rejected"),"decision":decision}); + "current":true,"effectDigest":DIGEST,"review":terminal("rejected"),"application":null,"decision":decision}); (current, submission) }; for reason in ["Public reason", " Padded, with \u{e9}", &"x".repeat(2000)] { @@ -1712,13 +1729,17 @@ async fn application_ids_require_canonical_non_nil_identity_and_preserve_exact_r let mut invalid = receipt.clone(); invalid["application"]["applicationId"] = json!(id); fixture.answer(invalid.clone()); - for observed in [ - fixture.client.get_proposal(&binding, ID).await, - fixture.client.read_proposal(&held).await, + for (observed, kind, unknown) in [ + ( + fixture.client.get_proposal(&binding, ID).await, + "protocol", + true, + ), + (fixture.client.read_proposal(&held).await, "protocol", true), ] { let error = observed.expect_err("malformed application identity must be refused"); - assert_eq!(error.kind(), "invalid-request"); - assert!(!error.is_outcome_unknown()); + assert_eq!(error.kind(), kind); + assert_eq!(error.is_outcome_unknown(), unknown); assert!(!format!("{error:?}").contains(&id)); } let error = fixture @@ -1802,7 +1823,7 @@ async fn attachment_availability_uses_the_same_complete_unavailable_contract_as_ .err() .unwrap() .kind(), - "invalid-request" + "protocol" ); assert_eq!( fixture @@ -1812,7 +1833,7 @@ async fn attachment_availability_uses_the_same_complete_unavailable_contract_as_ .err() .unwrap() .kind(), - "invalid-request" + "protocol" ); fixture.answer(json!({"items":[invalid.clone()]})); assert!(fixture @@ -1903,9 +1924,16 @@ async fn handoff_refusal_reads_only_an_allowlisted_code_on_a_submitted_proposal( let mut extra = with_refusal("submitted", "review.refused"); extra["handoffRefusal"]["detail"] = json!("authority text"); fixture.answer(extra); - if fixture.client.get_proposal(&binding, ID).await.is_ok() { - accepted.push("extra member".into()); - } + let read = fixture + .client + .get_proposal(&binding, ID) + .await + .unwrap() + .value; + assert_eq!( + serde_json::to_value(&read).unwrap()["handoffRefusal"], + json!({"code": "review.refused"}) + ); assert!(accepted.is_empty(), "accepted: {accepted:?}"); } @@ -1950,10 +1978,22 @@ async fn submission_read_carries_only_an_allowlisted_handoff_refusal() { .unwrap() .get("handoffRefusal") .is_none()); + fixture.answer(submission(Some( + json!({"code": "review.refused", "detail": "authority text"}), + ))); + let read = fixture + .client + .read_proposal_submission(&held, 1) + .await + .unwrap() + .value; + assert_eq!( + serde_json::to_value(&read).unwrap()["handoffRefusal"], + json!({"code": "review.refused"}) + ); let mut accepted = vec![]; for refusal in [ json!({"code": "review.authority-text"}), - json!({"code": "review.refused", "detail": "authority text"}), json!("review.refused"), ] { fixture.answer(submission(Some(refusal.clone()))); diff --git a/crates/registry-breg-client/tests/proposal_response_http_boundary.rs b/crates/registry-breg-client/tests/proposal_response_http_boundary.rs new file mode 100644 index 0000000000..46ce4d12a2 --- /dev/null +++ b/crates/registry-breg-client/tests/proposal_response_http_boundary.rs @@ -0,0 +1,626 @@ +// SPDX-License-Identifier: Apache-2.0 +use axum::{ + extract::State, + http::{Method, StatusCode}, + response::IntoResponse, + Router, +}; +use registry_breg_client::{ + BRegIdempotencyKey, BRegProposalMessageOutcome, BRegProposalMessageTarget, BRegProtocolFailure, + BaseRegistryClient, BaseRegistryClientConfig, BaseRegistryClientError, +}; +use serde::Deserialize; +use serde_json::Value; +use std::sync::{ + atomic::{AtomicBool, Ordering}, + Arc, +}; + +#[derive(Clone, Deserialize)] +#[serde(rename_all = "camelCase")] +struct Fixtures { + id: String, + metadata: Value, + held_proposal: String, + held_review: String, + cases: Vec, +} + +#[derive(Clone, Deserialize)] +struct Case { + name: String, + status: u16, + body: String, + route: Option, + #[serde(rename = "headerFault")] + header_fault: Option, + #[serde(default)] + accept: bool, +} + +#[tokio::test] +async fn proposal_get_projects_shared_raw_successes() { + check_fixtures(|case| case.name == "additive").await; +} + +#[tokio::test] +async fn proposal_get_refuses_malformed_successes() { + check_fixtures(|case| { + case.status == 200 + && case.name != "additive" + && case.route.as_deref().is_none_or(|route| route == "get") + }) + .await; +} + +#[tokio::test] +async fn proposal_get_classifies_shared_raw_problems() { + check_fixtures(|case| case.status >= 400).await; +} + +#[tokio::test] +async fn proposal_get_refuses_unexpected_success_status() { + check_fixtures(|case| case.status == 201).await; +} + +#[tokio::test] +async fn proposal_thread_page_checks_shared_responses() { + check_fixtures(|case| case.status == 200 && case.route.as_deref() == Some("page")).await; +} + +#[tokio::test] +async fn proposal_review_context_checks_shared_responses() { + check_fixtures(|case| case.route.as_deref() == Some("context")).await; +} + +#[tokio::test] +async fn reviewer_message_receipt_preserves_shared_pins() { + check_fixtures(|case| case.status == 200 && case.route.as_deref() == Some("send")).await; +} + +#[tokio::test] +async fn current_proposal_list_requires_the_served_turn() { + check_fixtures(|case| case.route.as_deref() == Some("list")).await; +} + +#[tokio::test] +async fn promoted_proposal_get_requires_the_served_turn() { + check_fixtures(|case| case.route.as_deref() == Some("promoted")).await; +} + +#[tokio::test] +async fn review_mark_read_projects_command_replies() { + check_fixtures(|case| case.status == 200 && case.route.as_deref() == Some("reviewMark")).await; +} + +#[tokio::test] +async fn only_mark_read_accepts_valid_bodyless_success() { + // The binding fixtures also send illegal Content-Length on a 204. + // Hyper's serving transport strips that header for empty Axum replies. + check_fixtures(|case| case.status == 204 && case.header_fault.as_deref() != Some("framing")) + .await; +} + +#[tokio::test] +async fn other_current_routes_check_their_projections() { + check_fixtures(|case| { + case.status == 200 && matches!(case.route.as_deref(), Some("mark" | "batch")) + }) + .await; +} + +#[tokio::test] +async fn scalar_review_context_and_status_check_route_and_profile() { + check_fixtures(|case| { + matches!( + case.route.as_deref(), + Some("promotedContext" | "status" | "promotedStatus") + ) + }) + .await; +} + +async fn check_fixtures(includes: fn(&Case) -> bool) { + let fixtures: Fixtures = + serde_json::from_str(include_str!("fixtures/proposal-response-tolerance.json")).unwrap(); + for case in fixtures.cases.iter().filter(|case| includes(case)) { + let router = Router::new() + .fallback( + |State((fixtures, case, promoted)): State<(Fixtures, Case, Arc)>, + method: Method, + uri: axum::http::Uri| async move { + let (status, media_type, body) = if uri.path() == "/v1/registry" { + (200, "application/json", fixtures.metadata.to_string()) + } else if (case.route.as_deref() == Some("promoted") + && !promoted.swap(true, Ordering::SeqCst)) + || (case.route.as_deref() == Some("page") + && !uri.path().ends_with("/messages")) + || (case.route.as_deref() == Some("mark") && method == Method::GET) + || (matches!( + case.route.as_deref(), + Some("promotedContext" | "promotedStatus") + ) && uri.path().ends_with(fixtures.id.as_str())) + { + (200, "application/json", fixtures.held_proposal) + } else if matches!(case.route.as_deref(), Some("send" | "reviewMark")) + && method == Method::GET + { + (200, "application/json", fixtures.held_review) + } else { + let media_type = if case.status < 300 { + "application/json" + } else { + "application/problem+json" + }; + (case.status, media_type, case.body) + }; + let mut reply = (StatusCode::from_u16(status).unwrap(), body).into_response(); + let headers = reply.headers_mut(); + use axum::http::{header, HeaderValue}; + let fault = if status == 204 { + case.header_fault.as_deref() + } else { + None + }; + if status == 204 && fault != Some("media") { + headers.remove(header::CONTENT_TYPE); + } else { + headers.insert(header::CONTENT_TYPE, HeaderValue::from_static(media_type)); + } + let trace = if fault == Some("trace") { + "invalid" + } else { + "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01" + }; + headers.insert("traceparent", HeaderValue::from_static(trace)); + if fault != Some("cache") { + headers.insert(header::CACHE_CONTROL, HeaderValue::from_static("no-store")); + } + headers.insert( + header::VARY, + HeaderValue::from_static("authorization, accept"), + ); + reply + }, + ) + .with_state(( + fixtures.clone(), + case.clone(), + Arc::new(AtomicBool::new(false)), + )); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + let server = tokio::spawn(async move { axum::serve(listener, router).await.unwrap() }); + let client = BaseRegistryClient::new(BaseRegistryClientConfig::new_without_peer_policy( + format!("http://{addr}/").parse().unwrap(), + )) + .unwrap(); + let metadata = client + .registry_contract(Some("reader")) + .await + .unwrap() + .value; + let result = match case.route.as_deref() { + Some("list") => { + let binding = metadata.select_proposals("reader").unwrap(); + client + .list_proposals(&binding, &Default::default()) + .await + .map(|complete| serde_json::to_value(complete.value).unwrap()) + } + Some("promoted") => { + let binding = metadata.select_proposal_get("reader").unwrap(); + let held = client + .get_proposal(&binding, &fixtures.id) + .await + .unwrap() + .value; + client + .read_proposal(&held) + .await + .map(|complete| serde_json::to_value(complete.value).unwrap()) + } + Some("page") => { + let binding = metadata.select_proposal_get("reader").unwrap(); + let held = client + .get_proposal(&binding, &fixtures.id) + .await + .unwrap() + .value; + client + .list_proposal_messages(BRegProposalMessageTarget::Proposal(&held), None, 2) + .await + .map(|complete| serde_json::to_value(complete.value).unwrap()) + } + Some("mark") => { + let binding = metadata.select_proposal_get("reader").unwrap(); + let held = client + .get_proposal(&binding, &fixtures.id) + .await + .unwrap() + .value; + client + .mark_proposal_messages_read( + BRegProposalMessageTarget::Proposal(&held), + "00000000-0000-4000-8000-000000000002", + ) + .await + .map(|complete| { + assert_eq!( + complete.metadata.trace_id().as_str(), + "4bf92f3577b34da6a3ce929d0e0e4736" + ); + match complete.value { + BRegProposalMessageOutcome::Proposal(document) => { + serde_json::to_value(document).unwrap() + } + _ => Value::Null, + } + }) + } + Some("batch") => { + let binding = metadata + .select_proposal_review_context("reader", "correct") + .unwrap(); + client + .read_proposal_review_context_batch(&binding, &[&fixtures.id]) + .await + .map(|complete| serde_json::to_value(complete.value).unwrap()) + } + Some("promotedContext" | "promotedStatus") => { + let binding = metadata.select_proposal_get("reader").unwrap(); + let held = client + .get_proposal(&binding, &fixtures.id) + .await + .unwrap() + .value; + let result = if case.route.as_deref() == Some("promotedContext") { + client.read_proposal_review_context(&held).await + } else { + client.read_proposal_review_status(&held).await + }; + result.map(|complete| serde_json::to_value(complete.value).unwrap()) + } + Some("status") => { + let binding = metadata + .select_proposal_review_status("reader", "correct") + .unwrap(); + client + .read_proposal_review_by_id(&binding, &fixtures.id) + .await + .map(|complete| serde_json::to_value(complete.value).unwrap()) + } + Some("context" | "send" | "reviewMark") => { + let binding = metadata + .select_proposal_review_context("reader", "correct") + .unwrap(); + let document = client + .read_proposal_review_by_id(&binding, &fixtures.id) + .await; + if case.route.as_deref() == Some("reviewMark") { + let held = document.unwrap().value; + client + .mark_proposal_messages_read( + BRegProposalMessageTarget::Review { + binding: &binding, + document: &held, + }, + "00000000-0000-4000-8000-000000000002", + ) + .await + .map(|complete| { + assert_eq!( + complete.metadata.trace_id().as_str(), + "4bf92f3577b34da6a3ce929d0e0e4736" + ); + match complete.value { + BRegProposalMessageOutcome::Proposal(document) => { + serde_json::to_value(document).unwrap() + } + BRegProposalMessageOutcome::Review(document) => { + serde_json::to_value(document).unwrap() + } + BRegProposalMessageOutcome::Thread(thread) => { + serde_json::to_value(thread).unwrap() + } + _ => Value::Null, + } + }) + } else if case.route.as_deref() == Some("send") { + let held = document.unwrap().value; + client + .send_proposal_message( + BRegProposalMessageTarget::Review { + binding: &binding, + document: &held, + }, + "Synthetic reply", + &BRegIdempotencyKey::parse("response-fixture").unwrap(), + ) + .await + .map(|complete| match complete.value { + BRegProposalMessageOutcome::Review(document) => { + serde_json::to_value(document).unwrap() + } + BRegProposalMessageOutcome::Proposal(document) => { + serde_json::to_value(document).unwrap() + } + BRegProposalMessageOutcome::Thread(thread) => { + serde_json::to_value(thread).unwrap() + } + _ => Value::Null, + }) + } else { + document.map(|complete| serde_json::to_value(complete.value).unwrap()) + } + } + _ => { + let binding = metadata.select_proposal_get("reader").unwrap(); + client + .get_proposal(&binding, &fixtures.id) + .await + .map(|complete| serde_json::to_value(complete.value).unwrap()) + } + }; + server.abort(); + match case.name.as_str() { + "additive" => { + let proposal = result.unwrap(); + assert!(proposal.get("futureMember").is_none()); + assert!(proposal["links"].get("future-relation").is_none()); + assert!(proposal["links"]["self"].get("futureMember").is_none()); + let entry = &proposal["additionalForms"]["extra"]["items"][0]; + assert_eq!(entry["input"]["futureMember"], "Declared input"); + assert!(entry.get("futureMember").is_none()); + assert!(proposal["messages"]["items"][0] + .get("futureMember") + .is_none()); + } + "validCitedForm" => { + let document = result.unwrap(); + let entry = &document["context"]["asks"][0]["answer"]["formEntries"][0]; + assert_eq!(entry["input"]["futureMember"], "Declared input"); + assert!(entry.get("futureMember").is_none()); + } + "emptyPageLinks" => assert_eq!(result.unwrap()["links"], serde_json::json!({})), + "additivePage" => { + let document = result.unwrap(); + assert!(document["links"].get("future").is_none()); + assert!(document["items"][0].get("futureMember").is_none()); + } + "listCurrentTurn" | "promotedCurrentTurn" => { + let document = result.unwrap(); + let proposal = if case.route.as_deref() == Some("list") { + &document["items"][0] + } else { + &document + }; + assert_eq!(proposal["turn"], "official"); + assert!(proposal.get("futureMember").is_none()); + } + "contextKeepsForms" | "promotedContextKeepsForms" => { + assert_eq!( + result.unwrap()["context"]["additionalForms"]["extra"], + "extra" + ); + } + "batchReaderOfficial" | "batchReaderParty" | "batchReaderLegacy" => { + let value = result.unwrap(); + let thread = &value[0]["context"]["messages"]; + assert_eq!(thread["unread"], 1); + match case.name.as_str() { + "batchReaderOfficial" => assert_eq!(thread["readerSide"], "official"), + "batchReaderParty" => assert_eq!(thread["readerSide"], "party"), + _ => assert!(thread.get("readerSide").is_none()), + } + } + "contextForms8" | "batchForms8" | "messageForms8" => { + let value = result.unwrap(); + let document = if case.route.as_deref() == Some("batch") { + &value[0] + } else { + &value + }; + let forms = document["context"]["additionalForms"].as_object().unwrap(); + assert_eq!(forms.len(), 8); + assert_eq!(forms["form-8"], "form-8"); + } + "threadUnavailablePair" | "pageThreadUnavailablePair" => { + let value = result.unwrap(); + assert_eq!( + value["links"]["message"]["availability"], + serde_json::json!({"available":false,"observedRevision":3,"reason":"limit-reached","recovery":"receipt-only"}), + ); + } + "reviewReplyWithBrokenOuterThread" => { + let value = result.unwrap(); + assert!(value["context"]["messages"].is_object()); + assert!(value.get("count").is_none()); + } + "reviewSendIdOnlyPolicy" => { + assert_eq!( + result.unwrap()["policy"], + serde_json::json!({"id":"case-review"}) + ); + } + "reviewSendPinnedPolicy" => { + assert_eq!( + result.unwrap()["policy"], + serde_json::from_str::(&case.body).unwrap()["policy"] + ); + } + "proposalReplyWithUnusedCounts" => { + let value = result.unwrap(); + assert_eq!(value["state"], "submitted"); + assert!(value.get("count").is_none()); + assert!(value.get("unread").is_none()); + } + "reviewMarkReviewReply" => assert!(result.unwrap().get("context").is_some()), + "reviewMarkProposalReply" => assert!(result.unwrap().get("state").is_some()), + "reviewMarkThreadReply" => assert!(result.unwrap().get("count").is_some()), + "proposalMarkNoContent" | "reviewMarkNoContent" => assert!(result.unwrap().is_null()), + _ if case.status == 204 => { + let error = result.expect_err(&case.name); + let expected = match case.header_fault.as_deref() { + Some("trace") => BRegProtocolFailure::TraceContext, + Some("cache") => BRegProtocolFailure::CachePolicy, + Some("media") => BRegProtocolFailure::MediaType, + _ => BRegProtocolFailure::Status, + }; + assert!( + matches!(error, BaseRegistryClientError::Protocol { status: 204, failure, .. } if failure == expected), + "{}: {error:?}", + case.name + ); + assert_eq!( + error.trace_id().map(|trace| trace.as_str()), + (expected != BRegProtocolFailure::TraceContext) + .then_some("4bf92f3577b34da6a3ce929d0e0e4736"), + ); + } + _ if case.status == 201 => { + let error = result.expect_err(&case.name); + assert!( + matches!( + error, + BaseRegistryClientError::Protocol { + status: 201, + failure: BRegProtocolFailure::Status, + .. + } + ), + "{}: {error:?}", + case.name + ); + assert_eq!( + error.trace_id().unwrap().as_str(), + "4bf92f3577b34da6a3ce929d0e0e4736" + ); + } + _ if !case.accept + && matches!( + case.route.as_deref(), + Some("context" | "batch" | "promotedContext" | "status" | "promotedStatus") + ) => + { + let error = result.expect_err(&case.name); + assert!( + matches!(error, BaseRegistryClientError::InvalidRequest { .. }), + "{}: {error:?}", + case.name + ); + assert!(!error.is_outcome_unknown()); + } + _ if case.accept && case.status == 200 => { + result.unwrap_or_else(|error| panic!("{}: {error}", case.name)); + } + _ if case.status == 200 => { + let error = result.expect_err(&case.name); + assert!( + matches!( + &error, + BaseRegistryClientError::Protocol { + status: 200, + failure: BRegProtocolFailure::Body, + .. + } + ), + "{}: {error:?}", + case.name + ); + assert!(error.is_outcome_unknown()); + assert_eq!( + error.trace_id().unwrap().as_str(), + "4bf92f3577b34da6a3ce929d0e0e4736" + ); + } + name if name.starts_with("threadProblem") => { + let error = result.expect_err(name); + assert_eq!(error.status(), Some(400), "{name}"); + assert_eq!( + error.trace_id().unwrap().as_str(), + "4bf92f3577b34da6a3ce929d0e0e4736", + "{name}", + ); + if case.accept { + let fixture: Value = serde_json::from_str(&case.body).unwrap(); + assert_eq!(error.kind(), "problem", "{name}"); + assert_eq!(error.problem_code_str(), fixture["code"].as_str(), "{name}"); + assert_eq!( + error.field_path().map(|path| path.as_str()), + fixture["fieldPath"].as_str(), + "{name}", + ); + } else { + assert!( + matches!( + error, + BaseRegistryClientError::Protocol { + failure: BRegProtocolFailure::Problem, + .. + } + ), + "{name}: {error:?}" + ); + assert!(error.field_path().is_none()); + } + } + "unknown" + | "unknownServerError" + | "futureSuffixRefused" + | "futureSuffixServerError" => { + let fixture: Value = serde_json::from_str(&case.body).unwrap(); + let code = fixture["code"].as_str().unwrap(); + let type_uri = fixture["type"].as_str().unwrap(); + let error = result.unwrap_err(); + assert_eq!(error.kind(), "problem"); + assert_eq!(error.problem_code_str(), Some(code)); + assert_eq!(error.problem_type(), Some(type_uri)); + assert_eq!(error.status(), Some(case.status)); + assert_eq!( + error.trace_id().unwrap().as_str(), + "4bf92f3577b34da6a3ce929d0e0e4736" + ); + assert_eq!(error.is_outcome_unknown(), case.status >= 500); + let formatted = format!("{error} {error:?}"); + for value in [code, "https://", "Synthetic", "Reworded"] { + assert!(!formatted.contains(value)); + } + } + "legacyPlanRefusal" => { + let error = result.unwrap_err(); + assert_eq!(error.kind(), "problem"); + assert_eq!(error.status(), Some(400)); + assert_eq!(error.problem_code_str(), None); + assert_eq!(error.problem_type(), None); + assert!(!error.is_outcome_unknown()); + assert!(!format!("{error} {error:?}").contains("request.plan_refused")); + } + "rewordedKnown" => { + let error = result.unwrap_err(); + assert_eq!(error.kind(), "not-found"); + assert_eq!(error.status(), Some(404)); + assert!(!error.is_outcome_unknown()); + } + "badCode" + | "duplicateProblem" + | "contradictoryKnown" + | "mismatchedType" + | "overlongCode" + | "futureFirstDigit" + | "futureSecondDigit" + | "futureLeadingHyphen" => assert!( + matches!( + result, + Err(BaseRegistryClientError::Protocol { + failure: BRegProtocolFailure::Problem, + .. + }) + ), + "{}", + case.name + ), + unknown => panic!("missing assertions for {unknown}"), + } + } +} diff --git a/crates/registry-breg-client/tests/read_parity.rs b/crates/registry-breg-client/tests/read_parity.rs index d57200dea9..8aba1ffe73 100644 --- a/crates/registry-breg-client/tests/read_parity.rs +++ b/crates/registry-breg-client/tests/read_parity.rs @@ -308,11 +308,23 @@ async fn read_routes_retain_operation_representation_and_snapshot_identity() { .await .unwrap(); - let as_of = BRegAsOfListRequest::new("2026-09-10T00:00:00Z").unwrap(); - client + let as_of = BRegAsOfListRequest::new("2026-09-10T00:00:00Z") + .unwrap() + .options( + BRegRecordOptions::default() + .access_profile("reader") + .unwrap(), + ); + let first_as_of = client .list_records_as_of("companies", &as_of) .await .unwrap(); + let continuation = first_as_of + .value + .continuation + .as_ref() + .expect("next as-of page"); + client.continue_as_of_list(continuation).await.unwrap(); let relationship = BRegRelationshipListRequest::default().limit(1).unwrap(); client .list_relationship_records("companies", RECORD_ID, "related", &relationship) @@ -343,9 +355,11 @@ async fn read_routes_retain_operation_representation_and_snapshot_identity() { assert!(captured.iter().any(|value| value == "application/geo+json /prefix/v1/records/companies?accessProfile=map&limit=1&bbox=100.1%2C13.1%2C100.2%2C13.2")); assert!(captured.iter().any(|value| value == "application/geo+json /prefix/v1/records/companies?accessProfile=map&cursor=geo-next")); + assert!(captured.iter().any(|value| value + .ends_with("/companies:as-of?accessProfile=reader&asOf=2026-09-10T00%3A00%3A00Z"))); assert!(captured .iter() - .any(|value| value.contains("/companies:as-of?asOf=2026-09-10T00%3A00%3A00Z"))); + .any(|value| value.ends_with("/companies:as-of?accessProfile=reader&cursor=next"))); assert!(captured .iter() .any(|value| value.contains(&format!("/companies/{RECORD_ID}/related?limit=1")))); diff --git a/crates/registry-breg-client/tests/write_http_boundary.rs b/crates/registry-breg-client/tests/write_http_boundary.rs index 2371d821b2..14b0a3a149 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") @@ -1050,7 +1058,7 @@ async fn retired_plan_problems_have_only_generic_unknown_problem_semantics() { .unwrap_err(); assert!(matches!( &error, - BaseRegistryClientError::UnrecognizedProblem { status: 400, trace_id } + BaseRegistryClientError::UnrecognizedProblem { status: 400, trace_id, .. } if trace_id.as_str() == TRACE_ID )); assert_eq!(error.kind(), "problem"); @@ -1816,9 +1824,7 @@ async fn record_and_query_problem_paths_are_closed_bounded_and_retained_without_ "$select", "$filter", "$orderby", - "$top", "$count", - "$skiptoken", "bbox", "accessProfile", "asOf", @@ -1835,9 +1841,7 @@ async fn record_and_query_problem_paths_are_closed_bounded_and_retained_without_ "pendingManualApplication", "target", "cursor", - "top", "inputDigest", - "after", "query", ] { accepted.push(( @@ -1884,6 +1888,10 @@ async fn record_and_query_problem_paths_are_closed_bounded_and_retained_without_ "/values", "Idempotency-Key", "If-Match", + "$top", + "$skiptoken", + "top", + "after", "$expand", "select", "fields", @@ -1980,12 +1988,12 @@ async fn registered_problem_identity_ignores_bounded_title_and_detail_prose() { "A record listing takes `$top` for its page size; `limit` is not accepted.", ), ( - "top", + "query", "Bad Request", "The Proposal list takes `limit` for its page size; `top` is not accepted.", ), ( - "after", + "query", "Bad Request", "An ingestion run listing takes `cursor` for its keyset cursor; `after` is not accepted.", ), @@ -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,9 +3224,179 @@ 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))); +} + +const ORDINARY_RECEIPT: &str = include_str!("fixtures/ordinary-ingestion-receipt.json"); + +#[tokio::test] +async fn ordinary_batch_projects_additions_and_refuses_malformed_results() { + let mut batch = ingestion_receipt_wire()["batch"].clone(); + batch["futureBatch"] = json!(null); + batch["results"][0]["futureItem"] = json!({"marker": 1}); + + let batch_reply = |body| { + MockResponse::json(StatusCode::OK, body) + .with_header("cache-control", "no-store") + .with_header("vary", "authorization, accept") + }; + let mut replies = vec![ + MockResponse::json(StatusCode::OK, metadata_fixture_with_create_batch()), + batch_reply(batch.clone()), + ]; + for (field, invalid) in [ + ("operation", json!("patch")), + ("recordId", json!("bad-id")), + ("revisionIdentifier", json!(1)), + ("etag", json!(null)), + ("domainData", json!({"unreadable": true})), + ] { + let mut malformed = batch.clone(); + malformed["results"][0][field] = invalid; + replies.push(batch_reply(malformed)); + } + let mut missing = batch.clone(); + missing["results"][0] + .as_object_mut() + .unwrap() + .remove("etag"); + replies.push(batch_reply(missing)); + let mut wrong_count = batch.clone(); + wrong_count["results"] = json!([]); + replies.push(batch_reply(wrong_count)); + let mut duplicate = batch_reply(batch); + duplicate.body = String::from_utf8(duplicate.body) + .unwrap() + .replace(r#""marker":1"#, r#""marker":1,"marker":2"#) + .into_bytes(); + replies.push(duplicate); + + let fixture = single_attempt_client(replies).await; + let client = &fixture.client; + let metadata = client + .registry_contract(Some("company-writer")) + .await + .unwrap() + .value; + let binding = metadata.select_batch("company", "company-writer").unwrap(); + let request = BRegBatchBuilder::new(&binding) + .create(&create_request()) + .unwrap() + .build() + .unwrap(); + let receipt = client + .batch_records(&binding, &request, &key("batch-ordinary")) + .await + .unwrap() + .value; + assert_eq!( + serde_json::to_value(receipt).unwrap(), + ingestion_receipt_wire()["batch"] + ); + for index in 0..8 { + let error = client + .batch_records( + &binding, + &request, + &key(&format!("batch-malformed-{index}")), + ) + .await + .unwrap_err(); + assert!(matches!( + error, + BaseRegistryClientError::Protocol { + failure: BRegProtocolFailure::Body, + .. + } + )); + } + assert_eq!(fixture.requests.lock().unwrap().len(), 10); +} + +#[tokio::test] +async fn ordinary_ingestion_receipt_projects_shared_bare_reply_and_refuses_malformed_bodies() { + let replies = [ + ORDINARY_RECEIPT.to_owned(), + ORDINARY_RECEIPT.replace(r#""marker": 1"#, r#""marker": 1, "marker": 2"#), + ORDINARY_RECEIPT.replace(r#""erased": false,"#, ""), + ORDINARY_RECEIPT.replace(r#""replayed": true"#, r#""replayed": "true""#), + format!(r#"{{"receipt": {ORDINARY_RECEIPT}}}"#), + ]; + let fixture = test_client( + replies + .into_iter() + .map(|body| { + let mut response = ingestion_response(StatusCode::OK, Value::Null); + response.body = body.into_bytes(); + response + }) + .collect(), + ) + .await; + let client = &fixture.client; + let run_id = Uuid::parse_str(RECORD_ID).unwrap(); + let receipt = client + .ingestion_chunk_receipt("company", run_id, 0, INGESTION_PROFILE) + .await + .unwrap() + .value; + let mut expected: Value = serde_json::from_str(ORDINARY_RECEIPT).unwrap(); + expected.as_object_mut().unwrap().remove("futureReceipt"); + expected["batch"] + .as_object_mut() + .unwrap() + .remove("futureBatch"); + assert_eq!(serde_json::to_value(receipt).unwrap(), expected); + for _ in 0..4 { + let error = client + .ingestion_chunk_receipt("company", run_id, 0, INGESTION_PROFILE) + .await + .unwrap_err(); + assert!(matches!( + error, + BaseRegistryClientError::Protocol { + failure: BRegProtocolFailure::Body, + .. + } + )); + } + assert_eq!(fixture.requests.lock().unwrap().len(), 5); +} + #[tokio::test] async fn ingestion_exchanges_select_the_announced_run_access_profile() { - let page = json!({"runs": [], "hasMore": false, "nextCursor": null}); + let mut run = ingestion_run_wire("open"); + run["futureRun"] = json!(true); + let mut submitted_run = run.clone(); + submitted_run["nextChunkIndex"] = json!(1); + submitted_run["committedItems"] = json!(1); + submitted_run["lastAttempt"] = + json!({"outcome": "committed", "chunkIndex": 0, "futureAttempt": true}); + let page = json!({"runs": [], "hasMore": false, "nextCursor": null, "futurePage": true}); + let mut retained_receipt = ingestion_receipt_wire(); + retained_receipt["replayed"] = json!(true); let fixture = test_client(vec![ ingestion_response( StatusCode::CREATED, @@ -3206,10 +3404,10 @@ async fn ingestion_exchanges_select_the_announced_run_access_profile() { ), ingestion_response( StatusCode::OK, - json!({"run": ingestion_run_wire("open"), "receipt": ingestion_receipt_wire()}), + json!({"run": submitted_run, "receipt": ingestion_receipt_wire(), "futureSubmission": true}), ), - ingestion_response(StatusCode::OK, json!({"receipt": ingestion_receipt_wire()})), - ingestion_response(StatusCode::OK, json!({"run": ingestion_run_wire("open")})), + ingestion_response(StatusCode::OK, retained_receipt), + ingestion_response(StatusCode::OK, json!({"run": run, "futureEnvelope": true})), ingestion_response(StatusCode::OK, json!({"run": ingestion_run_wire("open")})), ingestion_response( StatusCode::OK, @@ -3220,8 +3418,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 +3438,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 +3471,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 +3486,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 +3508,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"); @@ -3470,7 +3706,7 @@ async fn ingestion_answers_are_bound_to_the_requested_run_and_chunk() { ), (json!({"run": other_run.clone()}), Exchange::Read), (json!({"run": other_run}), Exchange::Cancel), - (json!({"receipt": other_chunk_receipt}), Exchange::Receipt), + (other_chunk_receipt, Exchange::Receipt), ] { let fixture = test_client(vec![ingestion_response(StatusCode::OK, body)]).await; let error = match exchange { 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-mcp/tests/support/mock_registry.rs b/crates/registry-breg-mcp/tests/support/mock_registry.rs index 8d5243726a..dd0328cc7c 100644 --- a/crates/registry-breg-mcp/tests/support/mock_registry.rs +++ b/crates/registry-breg-mcp/tests/support/mock_registry.rs @@ -418,6 +418,23 @@ fn application_record(identifier: Uuid, application: &Application, headers: &Hea value } +fn current_application_record( + identifier: Uuid, + application: &Application, + headers: &HeaderMap, +) -> Value { + let mut value = application_record(identifier, application, headers); + let turn = match value["state"].as_str() { + Some("draft") => "party", + // The submitted fixtures model a submission waiting for review. + Some("submitted") => "official", + Some("applied" | "cancelled" | "rejected") => "nobody", + state => panic!("unexpected fixture proposal state: {state:?}"), + }; + value["turn"] = json!(turn); + value +} + async fn metadata( State(state): State, RawQuery(query): RawQuery, @@ -595,7 +612,7 @@ async fn get_application( with_etag( json_response( StatusCode::OK, - &application_record(identifier, &application, &headers), + ¤t_application_record(identifier, &application, &headers), None, ), application.revision, @@ -688,7 +705,7 @@ async fn list_applications( .get("target") .is_none_or(|target| app.data["address"].as_str() == Some(target.as_ref())) }) - .map(|(id, app)| application_record(*id, app, &headers)) + .map(|(id, app)| current_application_record(*id, app, &headers)) .collect(); json_response(StatusCode::OK, &json!({"items":items}), None) } diff --git a/crates/registry-breg-review/tests/support/mod.rs b/crates/registry-breg-review/tests/support/mod.rs index 04eacacd8b..bab162a520 100644 --- a/crates/registry-breg-review/tests/support/mod.rs +++ b/crates/registry-breg-review/tests/support/mod.rs @@ -679,7 +679,9 @@ async fn read_draft( if caller.as_deref() != Some(draft.owner) || !selects_profile(query.as_deref()) { return problem(BRegProblemCode::ResourceNotFound); } - receipt_response(&draft_record(&identifier, draft)) + let mut current = draft_record(&identifier, draft); + current["turn"] = json!(if draft.submitted { "official" } else { "party" }); + receipt_response(¤t) } async fn read_address( 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/ingestion.rs b/crates/registry-breg/src/api/ingestion.rs index 7546df70e3..d6ce97f69b 100644 --- a/crates/registry-breg/src/api/ingestion.rs +++ b/crates/registry-breg/src/api/ingestion.rs @@ -300,7 +300,7 @@ async fn list_runs( Ok(query) => query, Err(QueryParseError::InvalidAt("after")) => { return invalid_query_at_with_detail( - "after", + "query", "An ingestion run listing takes `cursor` for its keyset cursor; `after` is not accepted.", ); } @@ -1013,7 +1013,6 @@ fn ingestion_list_parameter(name: &str) -> Option<&'static str> { "accessProfile" => Some("accessProfile"), "limit" => Some("limit"), "cursor" => Some("cursor"), - "after" => Some("after"), "status" => Some("status"), "inputDigest" => Some("inputDigest"), _ => None, @@ -1042,6 +1041,9 @@ fn parse_list_query(raw: Option<&str>) -> Result { @@ -1066,7 +1068,6 @@ fn parse_list_query(raw: Option<&str>) -> Result return Err(QueryParseError::InvalidAt("after")), "status" => { if crate::ingestion_store::IngestionRunStatus::parse(&value).is_none() || status.replace(value).is_some() @@ -1321,7 +1322,13 @@ pub(super) fn append_openapi( &input_schema_id, batch, allow_create, - allow_patch, + allow_patch.then(|| { + crate::artifacts::json_patch_array_schema( + surface.entity, + [surface.context.selected_profile()], + ) + .0 + }), ) } } @@ -1582,13 +1589,13 @@ fn submit_chunk_schema( input_schema_id: &str, batch: &crate::contract::BatchSource, allow_create: bool, - allow_patch: bool, + patch_schema: Option, ) -> Value { let items = crate::artifacts::openapi_batch_items_schema( json!({"$ref": format!("#/components/schemas/{input_schema_id}")}), batch.maximum_items, allow_create, - allow_patch, + patch_schema, ); json!({ "type": "object", diff --git a/crates/registry-breg/src/api/metadata.rs b/crates/registry-breg/src/api/metadata.rs index 59275501e0..32d540b74a 100644 --- a/crates/registry-breg/src/api/metadata.rs +++ b/crates/registry-breg/src/api/metadata.rs @@ -43,16 +43,26 @@ fn operation( || (surface.route.operation == Operation::Batch && profile.operations.contains(&Operation::Patch)) { - &profile.writable_fields + surface + .entity + .stored_fields + .iter() + .filter(|field| { + crate::artifacts::is_patch_writable_field( + surface.entity, + &profile.writable_fields, + field, + ) + }) + .map(|field| field.logical.id.clone()) + .collect::>() } else { - &empty + BTreeSet::new() }; - let create = create.clone(); - let patch = patch.clone(); let fields = surface .readable_fields .iter() - .chain(&create) + .chain(create) .chain(&patch) .cloned() .collect::>(); @@ -309,7 +319,8 @@ fn temporal_metadata(query: &CompiledQueryOperation) -> Value { CompiledQueryKind::AsOf => json!({ "mode": "as-of", "parameter": "asOf", - "required": true, + "required": false, + "requiredOnFirstPage": true, "schema": query .temporal .as_ref() @@ -399,12 +410,16 @@ fn request(surface: &AuthorizedSurface<'_>, query: Option<&CompiledQueryOperatio value["body"] = json!("json_patch"); value["contentType"] = json!("application/json-patch+json"); value["patchPathPrefix"] = json!("/data/"); - value["patchOperations"] = json!(["add", "replace", "remove", "test"]); + let (schema, operations) = crate::artifacts::json_patch_array_schema( + surface.entity, + [surface.context.selected_profile()], + ); + value["patchOperations"] = json!(operations); value["removeSemantics"] = json!("set_null"); value["ifMatchRequired"] = json!(true); value["idempotencyKeyRequired"] = json!(true); value["mutationSemantics"] = json!("direct"); - value["schema"] = crate::artifacts::json_patch_array_schema(); + value["schema"] = schema; } Operation::Tombstone => { value["body"] = json!("none"); @@ -432,7 +447,13 @@ fn request(surface: &AuthorizedSurface<'_>, query: Option<&CompiledQueryOperatio Some(&profile_batch_writable_fields(surface)), batch.maximum_items, profile.operations.contains(&Operation::Create), - profile.operations.contains(&Operation::Patch), + profile.operations.contains(&Operation::Patch).then(|| { + crate::artifacts::json_patch_array_schema( + surface.entity, + [surface.context.selected_profile()], + ) + .0 + }), ); } Operation::Lookup => { 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 66df030f3d..27b567b81e 100644 --- a/crates/registry-breg/src/artifacts.rs +++ b/crates/registry-breg/src/artifacts.rs @@ -2617,7 +2617,7 @@ fn openapi_document(input: OpenApiDocumentInput<'_>) -> Result) -> Option { "data": {"$ref": format!("#/components/schemas/{}", spec.request_schema_ref)} } }))), - Operation::Patch => Some(json_patch_request_body()), + Operation::Patch => Some(json_patch_request_body(route_patch_schema(spec))), Operation::Lookup => Some(json_request_body(json!({ "type": "object", "additionalProperties": false, @@ -3629,7 +3637,7 @@ fn operation_request_body(spec: OpenApiOperationSpec<'_>) -> Option { spec.request_schema_ref, batch.maximum_items, allow_create, - allow_patch, + allow_patch.then(|| route_patch_schema(spec)), )) } Operation::Get @@ -3652,10 +3660,10 @@ fn json_request_body(schema: Value) -> Value { }) } -fn json_patch_request_body() -> Value { +fn json_patch_request_body(schema: Value) -> Value { json!({ "required": true, - "content": {"application/json-patch+json": {"schema": json_patch_array_schema()}} + "content": {"application/json-patch+json": {"schema": schema}} }) } @@ -3663,13 +3671,13 @@ fn batch_request_body( schema_ref: &str, maximum_items: u16, allow_create: bool, - allow_patch: bool, + patch_schema: Option, ) -> Value { json_request_body(batch_input_schema( json!({"$ref": format!("#/components/schemas/{schema_ref}")}), maximum_items, allow_create, - allow_patch, + patch_schema, )) } @@ -3679,13 +3687,13 @@ pub(crate) fn openapi_batch_input_schema( writable_fields: Option<&BTreeSet>, maximum_items: u16, allow_create: bool, - allow_patch: bool, + patch_schema: Option, ) -> Value { batch_input_schema( openapi_entity_input_schema(entity, writable_fields), maximum_items, allow_create, - allow_patch, + patch_schema, ) } @@ -3693,7 +3701,7 @@ fn batch_input_schema( create_data_schema: Value, maximum_items: u16, allow_create: bool, - allow_patch: bool, + patch_schema: Option, ) -> Value { json!({ "type": "object", @@ -3705,7 +3713,7 @@ fn batch_input_schema( create_data_schema, maximum_items, allow_create, - allow_patch, + patch_schema, ) } }) @@ -3717,7 +3725,7 @@ pub(crate) fn openapi_batch_items_schema( create_data_schema: Value, maximum_items: u16, allow_create: bool, - allow_patch: bool, + patch_schema: Option, ) -> Value { let mut item_schemas = Vec::new(); if allow_create { @@ -3731,7 +3739,7 @@ pub(crate) fn openapi_batch_items_schema( } })); } - if allow_patch { + if let Some(patch_schema) = patch_schema { item_schemas.push(json!({ "type": "object", "additionalProperties": false, @@ -3740,7 +3748,7 @@ pub(crate) fn openapi_batch_items_schema( "operation": {"const": "patch"}, "recordId": {"type": "string", "format": "uuid"}, "ifMatch": {"type": "string", "minLength": 6, "maxLength": 256, "pattern": "^\\\"breg-[\\x21\\x23-\\x7E]+\\\"$"}, - "patch": json_patch_array_schema(), + "patch": patch_schema, } })); } @@ -3794,25 +3802,106 @@ fn bounded_text_schema(max_bytes: usize) -> Value { }) } -pub(crate) fn json_patch_array_schema() -> Value { - json!({ - "type": "array", - "minItems": 1, - "maxItems": 128, - "items": { +fn route_patch_schema(spec: OpenApiOperationSpec<'_>) -> Value { + match spec.access_profiles { + OpenApiAccessProfiles::All => json_patch_array_schema( + spec.entity, + spec.route.access_profiles.iter().map(String::as_str), + ), + OpenApiAccessProfiles::Selected(profile_id) => { + json_patch_array_schema(spec.entity, [profile_id]) + } + } + .0 +} + +pub(crate) fn is_patch_writable_field( + entity: &CompiledEntity, + writable_fields: &BTreeSet, + field: &crate::model::CompiledStoredField, +) -> bool { + writable_fields.contains(&field.logical.id) + && !entity.is_generated_identifier_immutable(&field.logical.id) +} + +pub(crate) fn json_patch_array_schema<'a>( + entity: &CompiledEntity, + profile_ids: impl IntoIterator, +) -> (Value, Vec<&'static str>) { + let mut writable_paths = BTreeSet::new(); + let mut removable_paths = BTreeSet::new(); + let mut testable_paths = BTreeSet::new(); + for profile_id in profile_ids { + let profile = &entity.access_profiles[profile_id]; + if !profile.operations.contains(&Operation::Patch) { + continue; + } + let readable = + crate::disclosure::plan(entity, profile_id).response_fields(&profile.readable_fields); + for field in &entity.stored_fields { + let id = &field.logical.id; + let path = format!( + "/data/{}", + registry_platform_yaml::escape_pointer_segment(&field.logical.api_name) + ); + if is_patch_writable_field(entity, &profile.writable_fields, field) { + writable_paths.insert(path.clone()); + if !field.required { + removable_paths.insert(path.clone()); + } + } + if field.logical.encryption.is_none() && readable.contains(id) { + testable_paths.insert(path); + } + } + } + + let mut operations = Vec::new(); + let mut branches = Vec::new(); + for (operation, paths) in [ + ("add", &writable_paths), + ("replace", &writable_paths), + ("remove", &removable_paths), + ("test", &testable_paths), + ] { + if paths.is_empty() { + continue; + } + operations.push(operation); + let mut branch = json!({ "type": "object", "additionalProperties": false, "required": ["op", "path"], "properties": { - "op": {"type": "string", "enum": ["add", "replace", "remove", "test"]}, - "path": {"type": "string"}, - "value": true - }, - "if": {"properties": {"op": {"const": "remove"}}}, - "then": {"not": {"required": ["value"]}}, - "else": {"required": ["value"]} + "op": {"const": operation}, + "path": {"type": "string", "enum": paths} + } + }); + if operation != "remove" { + branch["required"] = json!(["op", "path", "value"]); + branch["properties"]["value"] = json!(true); } - }) + branches.push(branch); + } + + let items = if branches.is_empty() { + json!(false) + } else { + json!({"oneOf": branches}) + }; + ( + json!({ + "type": "array", + "minItems": 1, + "maxItems": 128, + "items": items, + "not": {"items": { + "required": ["op"], + "properties": {"op": {"const": "test"}} + }} + }), + operations, + ) } fn operation_responses(spec: OpenApiOperationSpec<'_>) -> Value { @@ -5104,11 +5193,15 @@ fn batch_permissions(spec: OpenApiOperationSpec<'_>) -> (bool, bool) { } } -fn writable_fields_for_route(route: &CompiledRoute, entity: &CompiledEntity) -> BTreeSet { +fn create_writable_fields_for_route( + route: &CompiledRoute, + entity: &CompiledEntity, +) -> BTreeSet { route .access_profiles .iter() .filter_map(|profile_id| entity.access_profiles.get(profile_id)) + .filter(|profile| profile.operations.contains(&Operation::Create)) .flat_map(|profile| profile.writable_fields.iter().cloned()) .collect() } 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..34d6e4863d 100644 --- a/crates/registry-breg/src/problem_location.rs +++ b/crates/registry-breg/src/problem_location.rs @@ -32,11 +32,10 @@ pub const PROPOSAL_LIST_QUERY_PARAMETERS: &[&str] = &[ "pendingManualApplication", "target", "cursor", - "top", ]; /// Fixed query locations unique to the ingestion-run collection surface. -pub const INGESTION_LIST_QUERY_PARAMETERS: &[&str] = &["inputDigest", "after"]; +pub const INGESTION_LIST_QUERY_PARAMETERS: &[&str] = &["inputDigest"]; /// The fixed container used when an unrecognized query name cannot be echoed. pub const QUERY_CONTAINER: &str = "query"; @@ -182,6 +181,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 +197,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, @@ -423,9 +428,11 @@ mod tests { assert!(is_query_parameter_location("cursor")); assert!(is_query_parameter_location("pendingManualApplication")); assert!(is_query_parameter_location("inputDigest")); - assert!(is_query_parameter_location("top")); - assert!(is_query_parameter_location("after")); + assert!(is_query_parameter_location("status")); assert!(is_query_parameter_location("query")); + for retired in ["$top", "$skiptoken", "top", "after"] { + assert!(!is_query_parameter_location(retired), "{retired}"); + } assert!(!is_query_parameter_location("$expand")); assert!(!is_query_parameter_location("select")); assert!(!is_query_parameter_location("unknownCanary")); diff --git a/crates/registry-breg/src/proposal_artifacts.rs b/crates/registry-breg/src/proposal_artifacts.rs index 450b1ad498..54b0482fb4 100644 --- a/crates/registry-breg/src/proposal_artifacts.rs +++ b/crates/registry-breg/src/proposal_artifacts.rs @@ -488,7 +488,7 @@ pub(crate) fn append_proposal_openapi( "type":"object","additionalProperties":false,"required":["items"],"properties":{"items":{ "type":"array","minItems":1,"maxItems":100,"items":{"oneOf":[ {"type":"object","additionalProperties":false,"required":["id","status","context"],"properties":{ - "id":{"type":"string","format":"uuid"},"status":{"const":"visible"},"context":task_review_document_schema()}}, + "id":{"type":"string","format":"uuid"},"status":{"const":"visible"},"context":compact_review_document_schema()}}, {"type":"object","additionalProperties":false,"required":["id","status"],"properties":{ "id":{"type":"string","format":"uuid"},"status":{"const":"concealed"}}} ]}}}}); @@ -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); @@ -1102,6 +1106,12 @@ fn operation_document( } fn task_review_document_schema() -> Value { + let mut schema = compact_review_document_schema(); + schema["properties"]["policy"] = review_policy_binding_schema(); + schema +} + +fn compact_review_document_schema() -> Value { let mut schema = review_document_schema(true); schema["properties"]["context"]["properties"] .as_object_mut() @@ -1110,8 +1120,18 @@ fn task_review_document_schema() -> Value { schema } +fn review_policy_binding_schema() -> Value { + json!({"type":"object","additionalProperties":false,"required":["id","version","digest"], + "properties":{"id":{"type":"string"},"version":{"type":"string"},"digest":{"type":"string"}}}) +} + fn review_document_schema(context: bool) -> Value { - let mut properties = json!({"id":{"type":"string","format":"uuid"},"actionId":{"type":"string"},"actionRevision":{"type":"string"},"submissionVersion":{"type":"integer","minimum":1},"revision":{"type":"integer","minimum":1},"effectDigest":{"type":"string"},"subject":{"type":"object","additionalProperties":false,"required":["source","subjectType","id","version","digest"],"properties":{"source":{"type":"string"},"subjectType":{"const":"proposal"},"id":{"type":"string","format":"uuid"},"version":{"type":"string"},"digest":{"type":"string"}}},"context":{"type":"object","additionalProperties":false,"required":["reference"],"properties":{"reference":{"type":"string"}}},"authority":{"type":"string"},"policy":{"type":"object","additionalProperties":false,"required":["id","version","digest"],"properties":{"id":{"type":"string"},"version":{"type":"string"},"digest":{"type":"string"}}},"reviewable":{"type":"boolean"},"result":{"type":"object","additionalProperties":false,"required":["state"],"properties":{"state":{"enum":["pending","approved","rejected","changes-requested","answered","cancelled","superseded","expired"]},"resultId":{"type":"string","format":"uuid"},"completedAt":{"type":"string","format":"date-time"},"availableUntil":{"type":"string","format":"date-time"}}}}); + let mut properties = json!({"id":{"type":"string","format":"uuid"},"actionId":{"type":"string"},"actionRevision":{"type":"string"},"submissionVersion":{"type":"integer","minimum":1},"revision":{"type":"integer","minimum":1},"effectDigest":{"type":"string"},"subject":{"type":"object","additionalProperties":false,"required":["source","subjectType","id","version","digest"],"properties":{"source":{"type":"string"},"subjectType":{"const":"proposal"},"id":{"type":"string","format":"uuid"},"version":{"type":"string"},"digest":{"type":"string"}}},"context":{"type":"object","additionalProperties":false,"required":["reference"],"properties":{"reference":{"type":"string"}}},"authority":{"type":"string"},"reviewable":{"type":"boolean"},"result":{"type":"object","additionalProperties":false,"required":["state"],"properties":{"state":{"enum":["pending","approved","rejected","changes-requested","answered","cancelled","superseded","expired"]},"resultId":{"type":"string","format":"uuid"},"completedAt":{"type":"string","format":"date-time"},"availableUntil":{"type":"string","format":"date-time"}}}}); + properties["policy"] = json!({"oneOf":[ + {"type":"object","additionalProperties":false,"required":["id"], + "properties":{"id":{"type":"string"}}}, + review_policy_binding_schema() + ]}); properties["context"]["properties"]["contract"] = json!({ "type":"object","additionalProperties":false, "required":["id","revision","schemaDigest"], 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/compiled_ddl_pins.rs b/crates/registry-breg/tests/compiled_ddl_pins.rs index 8d427d63c1..a81e7b9fda 100644 --- a/crates/registry-breg/tests/compiled_ddl_pins.rs +++ b/crates/registry-breg/tests/compiled_ddl_pins.rs @@ -110,6 +110,10 @@ //! canonical artifact inventory produces a different revision for each fixture //! even when it declares no Proposal Actions. DDL and Action definition //! fingerprints are computed independently of OpenAPI. +//! Effective PATCH request schemas in OpenAPI move the compiled revisions of +//! Organization Membership Access, Facility, and Household Contact. Asset +//! Registration exposes no PATCH operation and retains its exact revision. +//! DDL and Action fingerprints stay fixed. use registry_breg::compiler::{compile_project, CompileProfile}; use registry_breg::contract::{parse_module_yaml, parse_project_yaml}; @@ -154,7 +158,7 @@ const FIXTURES: &[Fixture] = &[ "../../../products/breg/fixtures/facility-registry-actions/modules/facility-registry-actions-core/module.yaml" )), ddl_sha256: "6439a877ee6508b999a77242542695d8ccddc6d80518699d90eddc32b305780b", - revision: "sha256:b645293f26040f1cb62f8d445b22bff0bb4a030dcfd2dd8f9d5330dc09e88d03", + revision: "sha256:7793a749c1ff75b9767cea3787adfc268bd38e9ba1ef906f0c700b2632ba9e2e", }, Fixture { name: "household-contact-actions", @@ -165,7 +169,7 @@ const FIXTURES: &[Fixture] = &[ "../../../products/breg/fixtures/household-contact-actions/modules/household-contact-actions-core/module.yaml" )), ddl_sha256: "f82f2f8376df97fb184c04d31c8e42c291f7a03dbd909828e1bf61612106de35", - revision: "sha256:c432a662014b64d65be228e667b5b48b8b164f661aabe6711e44c07c365ce1c8", + revision: "sha256:bd6519bef876a12c56f66351d35f90eccff4c3b176a56fa7801ad8d1489ca06c", }, ]; diff --git a/crates/registry-breg/tests/compiler_contract.rs b/crates/registry-breg/tests/compiler_contract.rs index 088839a2f2..593d0a68e3 100644 --- a/crates/registry-breg/tests/compiler_contract.rs +++ b/crates/registry-breg/tests/compiler_contract.rs @@ -2323,11 +2323,14 @@ fn batch_route_requires_explicit_bounds_and_compiles_bounded_openapi() { "kind":"BRegProject", "project":{{"id":"batch-contract","version":"1","defaultLanguage":"en","canonicalBaseIri":"https://authoring.example.test"}}, "recordTypes":{{"record":{{"primaryDataset":"test-dataset","route":"records","mutationMode":"mutable"{batch}, - "fields":[{{"id":"label","type":"string","maximumLength":32,"required":true,"classification":"internal"}}] + "fields":[ + {{"id":"label","type":"string","maximumLength":32,"required":true,"classification":"internal"}}, + {{"id":"read-only","type":"string","maximumLength":32,"classification":"internal"}} + ] }}}}, "accessProfiles":{{"writer":{{"principalClaim":"principal","requiredScopes":["records:write"],"permissions":{{"records":[{{ "rowBoundaries": "unrestricted", "recordType":"record","operations":{operations}, - "readableFields":["label"],"writableFields":["label"] + "readableFields":["label","read-only"],"writableFields":["label"] }}]}} }}}} }}"# @@ -2465,6 +2468,30 @@ fn batch_route_requires_explicit_bounds_and_compiles_bounded_openapi() { assert!(patch_item_schema["properties"] .get("recordIdentifier") .is_none()); + let batch_patch = &patch_item_schema["properties"]["patch"]; + let direct_patch = &openapi["paths"]["/v1/records/records/{record_id}"]["patch"]["requestBody"] + ["content"]["application/json-patch+json"]["schema"]; + assert_eq!(batch_patch, direct_patch); + let branches = batch_patch["items"]["oneOf"] + .as_array() + .expect("patch branches"); + let paths = branches + .iter() + .map(|branch| { + ( + branch["properties"]["op"]["const"].as_str().unwrap(), + branch["properties"]["path"]["enum"].clone(), + ) + }) + .collect::>(); + assert_eq!( + paths, + [ + ("add", json!(["/data/label"])), + ("replace", json!(["/data/label"])), + ("test", json!(["/data/label", "/data/readOnly"])), + ] + ); let batch_response_schema = &batch_operation["responses"]["200"]["content"]["application/json"]["schema"]; assert!(batch_response_schema["required"] @@ -6861,9 +6888,23 @@ fn generated_openapi_routes_and_physical_names_share_one_compiled_inventory() { "traceparent" ] ); - assert!(patch["requestBody"]["content"] - .get("application/json-patch+json") - .is_some()); + let schema = &patch["requestBody"]["content"]["application/json-patch+json"]["schema"]; + let branches = schema["items"]["oneOf"] + .as_array() + .expect("patch operation branches"); + assert!(branches + .iter() + .any(|branch| branch["properties"]["op"]["const"] == "replace")); + for branch in branches { + let paths = branch["properties"]["path"]["enum"] + .as_array() + .expect("bounded paths"); + assert!(!paths.is_empty()); + assert!(paths + .iter() + .all(|path| path.as_str().unwrap().starts_with("/data/"))); + } + assert_eq!(schema["not"]["items"]["properties"]["op"]["const"], "test"); assert!(patch["responses"]["428"]["headers"] .get("traceparent") .is_some()); @@ -7708,8 +7749,11 @@ fn compiled_query_inventory_is_profile_scoped_bounded_and_temporal() { .iter() .find(|parameter| parameter["name"] == "asOf") .expect("asOf parameter is rendered"); - assert_eq!(as_of["required"], true); + assert_eq!(as_of["required"], false); assert_eq!(as_of["schema"], json!({"type": "string", "format": "date"})); + let as_of_description = as_of["description"].as_str().expect("asOf query guidance"); + assert!(as_of_description.contains("Required on the first page")); + assert!(as_of_description.contains("only cursor and the applicable access profile")); let page_size = as_of_parameters .iter() .find(|parameter| parameter["name"] == "limit") 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/generated_identifier_compiler.rs b/crates/registry-breg/tests/generated_identifier_compiler.rs index 51059389cb..1537935fb3 100644 --- a/crates/registry-breg/tests/generated_identifier_compiler.rs +++ b/crates/registry-breg/tests/generated_identifier_compiler.rs @@ -166,6 +166,66 @@ fn generated_identifiers_are_read_only_in_generated_contracts() { ); } +#[test] +fn patch_inventories_preserve_generated_scope_as_test_only_and_isolate_batch_create() { + let mut project = project_value(); + let record = &mut project["recordTypes"]["record"]; + record["batch"] = json!({"maximumItems": 7, "maximumBytes": 8192}); + record["fields"].as_array_mut().unwrap().push(json!({ + "id": "patch-note", "type": "string", "maximumLength": 32, + "classification": "internal" + })); + let editor = &mut project["accessProfiles"]["editor"]; + editor["permissions"]["records"][0]["operations"] = json!(["create", "get", "batch"]); + let mut patcher = editor.clone(); + let grant = &mut patcher["permissions"]["records"][0]; + grant["operations"] = json!(["patch", "batch"]); + grant["writableFields"] = json!(["jurisdiction", "patch-note"]); + grant["readableFields"] = json!(["jurisdiction", "patch-note"]); + project["accessProfiles"]["patcher"] = patcher; + + let compiled = compile(&project).expect("separate Batch grants compile"); + let document = parse_json_strict( + &compiled + .artifacts() + .get("generated/openapi.json") + .unwrap() + .bytes, + ) + .expect("generated OpenAPI parses"); + let direct = &document["paths"]["/v1/records/records/{record_id}"]["patch"]["requestBody"] + ["content"]["application/json-patch+json"]["schema"]; + let batch = &document["paths"]["/v1/records/records:batch"]["post"]["requestBody"]["content"] + ["application/json"]["schema"]["properties"]["items"]; + assert_eq!(batch["maxItems"], 7); + let branches = batch["items"]["oneOf"].as_array().unwrap(); + let patch = branches + .iter() + .find(|item| item["properties"]["operation"]["const"] == "patch") + .unwrap(); + assert_eq!(&patch["properties"]["patch"], direct); + let create = branches + .iter() + .find(|item| item["properties"]["operation"]["const"] == "create") + .unwrap(); + let schema_ref = create["properties"]["data"]["$ref"].as_str().unwrap(); + let input = document + .pointer(schema_ref.strip_prefix('#').unwrap()) + .unwrap(); + assert!(input["properties"].get("patchNote").is_none()); + assert_eq!(input["required"], json!(["jurisdiction"])); + let paths = direct["items"]["oneOf"].as_array().unwrap(); + for branch in paths { + let operation = branch["properties"]["op"]["const"].as_str().unwrap(); + let paths = &branch["properties"]["path"]["enum"]; + if operation == "test" { + assert_eq!(paths, &json!(["/data/jurisdiction", "/data/patchNote"])); + } else { + assert_eq!(paths, &json!(["/data/patchNote"])); + } + } +} + #[test] fn generated_identifier_semantics_are_strictly_validated() { let cases = [ diff --git a/crates/registry-breg/tests/golden/membership-revision.txt b/crates/registry-breg/tests/golden/membership-revision.txt index 69e7c1ff86..db58a08a58 100644 --- a/crates/registry-breg/tests/golden/membership-revision.txt +++ b/crates/registry-breg/tests/golden/membership-revision.txt @@ -1 +1 @@ -sha256:abf7076e7ca40d96d8f750f0e2e015d4a56b46ade222d94ae7a0cfae45b344bd +sha256:4395d39189ea8825194621cdbf291fcf05effc691ca5caff0b35703120edc0a1 diff --git a/crates/registry-breg/tests/http_read_only.rs b/crates/registry-breg/tests/http_read_only.rs index eb555471c8..07bdf9ec71 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; @@ -1079,7 +1252,21 @@ async fn closed_query_grammar_reaches_record_service_as_compiled_query() { ) .await; assert_eq!(bad_operator.status(), StatusCode::BAD_REQUEST); - assert_eq!(body_json(bad_operator).await["code"], "query.invalid"); + let problem = body_json(bad_operator).await; + assert_eq!(problem["code"], "query.invalid"); + assert_eq!(problem["fieldPath"], "$filter"); + + let mis_cased_filter = harness + .send( + Method::GET, + "/v1/records/cases?$Filter=label%20eq%20'Visible'", + Some(public_claims()), + ) + .await; + assert_eq!(mis_cased_filter.status(), StatusCode::BAD_REQUEST); + let problem = body_json(mis_cased_filter).await; + assert_eq!(problem["code"], "query.invalid"); + assert!(problem.get("fieldPath").is_none()); assert_eq!(harness.records.calls(), before); } @@ -1115,7 +1302,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 +1877,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 +2234,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 +2245,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 +2305,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 +2322,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 +2336,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 +2351,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 +2502,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 +2637,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 +2646,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 +2673,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 +2767,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 +3488,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 +4112,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 +4202,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; @@ -4736,7 +4931,8 @@ async fn workspace_temporal_capabilities_and_no_store_cover_success_and_refusal( .find(|operation| operation["query"]["kind"] == "as-of") .unwrap(); assert_eq!(as_of["query"]["temporal"]["parameter"], "asOf"); - assert_eq!(as_of["query"]["temporal"]["required"], true); + assert_eq!(as_of["query"]["temporal"]["required"], false); + assert_eq!(as_of["query"]["temporal"]["requiredOnFirstPage"], true); assert_eq!( as_of["query"]["temporal"]["schema"], json!({"type": "string", "format": "date"}), @@ -4754,7 +4950,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 +5042,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_contract.rs b/crates/registry-breg/tests/postgres_ingestion_contract.rs index 42c0fc68a8..280581a82e 100644 --- a/crates/registry-breg/tests/postgres_ingestion_contract.rs +++ b/crates/registry-breg/tests/postgres_ingestion_contract.rs @@ -149,6 +149,209 @@ async fn read_run_publishes_the_profile_mismatch_response() { assert_eq!(example["value"]["status"], 403); } +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn ingestion_and_selected_metadata_publish_the_same_patch_paths() { + let harness = ContractHarness::create(compiled_registry()).await; + let claims = operator_claims(PRINCIPAL, "zone-a"); + let response = harness + .get_json("/openapi.json?accessProfile=operator", &claims) + .await; + assert_eq!(response.status(), StatusCode::OK); + let document = body_json(response).await; + let items = &document["paths"]["/v1/records/widgets/ingestion-runs/{run_id}/chunks"]["post"] + ["requestBody"]["content"]["application/json"]["schema"]["properties"]["items"]["items"] + ["oneOf"]; + let patch = items + .as_array() + .unwrap() + .iter() + .find(|item| item["properties"]["operation"]["const"] == "patch") + .expect("selected operator can submit patch items"); + let ingestion_patch = &patch["properties"]["patch"]; + let direct = &document["paths"]["/v1/records/widgets/{record_id}"]["patch"]["requestBody"] + ["content"]["application/json-patch+json"]["schema"]; + assert_eq!(direct, ingestion_patch); + let response = harness + .get_json("/v1/registry?accessProfile=operator", &claims) + .await; + assert_eq!(response.status(), StatusCode::OK); + let metadata = body_json(response).await; + let operations = metadata["operations"] + .as_array() + .expect("metadata operations"); + let operation = |suffix: &str| { + let id = format!("records.widget.{suffix}"); + operations + .iter() + .find(|operation| operation["id"] == id.as_str()) + .expect("selected operation is visible") + }; + let expected_patch = json!(["label", "payload", "quantity"]); + assert_eq!( + [ + &operation("patch")["patchWritableFields"], + &operation("batch")["patchWritableFields"] + ], + [&expected_patch, &expected_patch], + ); + let expected_create = json!(["jurisdiction", "label", "payload", "quantity"]); + for suffix in ["create", "batch"] { + assert_eq!(operation(suffix)["createWritableFields"], expected_create); + } + for suffix in ["get", "create"] { + assert_eq!(operation(suffix)["patchWritableFields"], json!([])); + } + assert_eq!(operation("patch")["createWritableFields"], json!([])); + assert!(operation("patch")["readableFields"] + .as_array() + .unwrap() + .contains(&json!("jurisdiction"))); + let request = &operations + .iter() + .find(|operation| operation["id"] == "records.widget.patch") + .expect("selected operator can patch directly")["request"]; + assert_eq!(&request["schema"], ingestion_patch); + assert_eq!( + request["patchOperations"], + json!(["add", "replace", "remove", "test"]) + ); + let branches = ingestion_patch["items"]["oneOf"] + .as_array() + .expect("patch operation branches"); + for branch in branches { + let operation = branch["properties"]["op"]["const"].as_str().unwrap(); + let paths = branch["properties"]["path"]["enum"].as_array().unwrap(); + assert_eq!( + paths.contains(&json!("/data/jurisdiction")), + operation == "test", + "{operation}" + ); + } + let remove = branches + .iter() + .find(|branch| branch["properties"]["op"]["const"] == "remove") + .expect("payload can be removed"); + assert_eq!( + remove["properties"]["path"]["enum"], + json!(["/data/payload"]) + ); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn sdk_preflight_uses_effective_writes_from_live_generated_scope_metadata() { + use registry_breg_client::{ + BRegBatchBuilder, BRegBatchError, BRegCreateRequest, BRegDirectWrite, BRegIdempotencyKey, + BRegPatchRequest, BRegRecordFormat, BaseRegistryClient, BaseRegistryClientConfig, + StaticToken, + }; + + let harness = ContractHarness::create(compiled_registry()).await; + let claims = operator_claims(PRINCIPAL, "zone-a"); + let app = harness.app.layer(axum::Extension(claims)); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = listener.local_addr().unwrap(); + let server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() }); + let client = BaseRegistryClient::new( + BaseRegistryClientConfig::new_without_peer_policy( + format!("http://{address}").parse().unwrap(), + ) + .with_token_provider(Arc::new(StaticToken::new("test-bearer").unwrap())), + ) + .unwrap(); + let metadata = client + .registry_contract(Some("operator")) + .await + .unwrap() + .value; + let BRegDirectWrite::Create(create) = metadata + .select_direct_write("records.widget.create", "operator") + .unwrap() + else { + panic!("direct Create is selected"); + }; + let BRegDirectWrite::Patch(patch) = metadata + .select_direct_write("records.widget.patch", "operator") + .unwrap() + else { + panic!("direct Patch is selected"); + }; + let batch = metadata.select_batch("widget", "operator").unwrap(); + let created = client + .create_record( + &create, + &BRegCreateRequest::new(serde_json::Map::from_iter([ + ("jurisdiction".to_owned(), json!("zone-a")), + ("label".to_owned(), json!("metadata-scope")), + ("quantity".to_owned(), json!(1)), + ])) + .unwrap(), + &BRegIdempotencyKey::parse("metadata-scope-create").unwrap(), + BRegRecordFormat::Json, + ) + .await + .unwrap(); + let id = created.value.data.record_id.parse().unwrap(); + let etag = created + .metadata + .etag() + .expect("Create supplies its strong ETag"); + + let write = BRegPatchRequest::builder() + .replace("jurisdiction", json!("zone-a")) + .unwrap() + .build() + .unwrap(); + let batch_error = BRegBatchBuilder::new(&batch).patch(id, etag, &write).err(); + let direct_error = client + .patch_record( + &patch, + id, + etag, + &write, + &BRegIdempotencyKey::parse("metadata-scope-immutable").unwrap(), + BRegRecordFormat::Json, + ) + .await + .unwrap_err(); + assert_eq!( + ( + matches!(batch_error, Some(BRegBatchError::ItemContractMismatch)), + direct_error.kind(), + direct_error.status() + ), + (true, "invalid-request", None), + "both preflights refuse the write before HTTP", + ); + + let test_and_write = BRegPatchRequest::builder() + .test("jurisdiction", json!("zone-a")) + .unwrap() + .replace("label", json!("metadata-scope-updated")) + .unwrap() + .build() + .unwrap(); + assert!(BRegBatchBuilder::new(&batch) + .patch(id, etag, &test_and_write) + .is_ok()); + let updated = client + .patch_record( + &patch, + id, + etag, + &test_and_write, + &BRegIdempotencyKey::parse("metadata-scope-test-and-write").unwrap(), + BRegRecordFormat::Json, + ) + .await + .unwrap(); + assert_eq!(updated.value.data.domain_data["jurisdiction"], "zone-a"); + assert_eq!( + updated.value.data.domain_data["label"], + "metadata-scope-updated" + ); + server.abort(); +} + /// The run creation document publishes the count range the service enforces. /// The run store admits only a positive announced source size, so a schema /// that admitted zero would advertise a request the service always answers @@ -550,6 +753,11 @@ fn fixture_registry(batch_maximum_bytes: u32) -> Arc, + 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); + + // Read the bare receipt through the SDK while the run has a committed prefix. + let http = ClientHttp::start(harness.app.clone(), claims.clone()).await; + let reason = BRegAccessReason::new("Verify the announced input 🧭").unwrap(); + let typed_receipt = http + .client + .ingestion_chunk_receipt_with_access_reason( + "widgets", + Uuid::parse_str(run_id).unwrap(), + 0, + "operator", + Some(&reason), + ) + .await + .expect("the SDK accepts the committed receipt from the public endpoint") + .value; + assert_eq!(typed_receipt.chunk_index(), 0); + assert_eq!(typed_receipt.digest(), chunks.digests[0]); + assert!(typed_receipt.replayed()); + drop(http); + 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()) @@ -4783,7 +5080,8 @@ async fn ingestion_list_query_refusals_follow_authority() { ("limit=0", "limit"), ("cursor=not-a-uuid", "cursor"), ("status=unknown", "status"), - ("after=00000000-0000-4000-8000-000000000001", "after"), + ("after=00000000-0000-4000-8000-000000000001", "query"), + ("limit=1&%61fter=%FF", "query"), ] { let response = harness .get_json( 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..0ebabc175d 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,75 @@ 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 metadata = send( + &app, + "/v1/registry?accessProfile=operator", + Some(read_claims(["zone-a"])), + ) + .await; + assert_eq!(metadata.status(), StatusCode::OK); + let metadata = body_json(metadata).await; + let operation = metadata["operations"] + .as_array() + .unwrap() + .iter() + .find(|operation| operation["path"] == "/v1/records/assignments:as-of") + .expect("admitted as-of operation appears in metadata"); + assert_eq!(operation["query"]["temporal"]["required"], false); + assert_eq!(operation["query"]["temporal"]["requiredOnFirstPage"], true); + assert_eq!(operation["query"]["pagination"]["parameter"], "cursor"); + assert_eq!(operation["query"]["pagination"]["exclusive"], true); + + let missing = send( + &app, + "/v1/records/assignments:as-of?accessProfile=operator", + Some(read_claims(["zone-a"])), + ) + .await; + assert_eq!(missing.status(), StatusCode::BAD_REQUEST); + + 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 +877,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 +894,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 +905,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 +925,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 +949,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 +994,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 +1018,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 +1040,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 +1059,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 +1572,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