diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index ec0ea39c7c..4e7905196d 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -2012,7 +2012,7 @@ jobs: # of this feature set. - name: Base Registry Engine schema-gated tests if: matrix.lane == 'contracts' - run: cargo test --locked -p registry-breg --features runtime,tooling,schema --lib --test action_evidence_compiler --test proposal_hooks --test value_type_consistency + run: cargo test --locked -p registry-breg --features runtime,tooling,schema --lib --test action_evidence_compiler --test proposal_additional_forms --test proposal_hooks --test value_type_consistency - name: BReg client contract consistency if: matrix.lane == 'contracts' 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 03de78ac6f..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 04e9cb0a48a7f056eea904829bf26257ecd384e04b0b619c87fd0bd758629ef8 -// 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" @@ -10,12 +14,12 @@ import { listPage, listQuery, type FieldValue, type Filter, type ListPage, type export type Schema_ImmediateActionPrecondition = ({ "ifMatch": (string) }) export type Schema_ImmediateActionResultReference = ({ "recordId": (string); "recordType": (string); "revision": (number) }) -export type Schema_Problem = (({ "code"?: "access-profile.ambiguous"; "status"?: 400; "type"?: "https://id.registrystack.org/problems/registry-breg/access-profile/ambiguous" }) | ({ "code"?: "action.evidence-failed"; "status"?: 503; "type"?: "https://id.registrystack.org/problems/registry-breg/action/evidence-failed" }) | ({ "code"?: "action.guard-failed"; "status"?: 412; "type"?: "https://id.registrystack.org/problems/registry-breg/action/guard-failed" }) | ({ "code"?: "action.handler-failed"; "status"?: 500; "type"?: "https://id.registrystack.org/problems/registry-breg/action/handler-failed" }) | ({ "code"?: "action.refused"; "status"?: 422; "type"?: "https://id.registrystack.org/problems/registry-breg/action/refused" }) | ({ "code"?: "attachment.content-type"; "status"?: 415; "type"?: "https://id.registrystack.org/problems/registry-breg/attachment/content-type" }) | ({ "code"?: "attachment.digest-mismatch"; "status"?: 422; "type"?: "https://id.registrystack.org/problems/registry-breg/attachment/digest-mismatch" }) | ({ "code"?: "attachment.limit-reached"; "status"?: 409; "type"?: "https://id.registrystack.org/problems/registry-breg/attachment/limit-reached" }) | ({ "code"?: "attachment.required"; "status"?: 422; "type"?: "https://id.registrystack.org/problems/registry-breg/attachment/required" }) | ({ "code"?: "attachment.slot-write-once"; "status"?: 409; "type"?: "https://id.registrystack.org/problems/registry-breg/attachment/slot-write-once" }) | ({ "code"?: "attachment.too-large"; "status"?: 413; "type"?: "https://id.registrystack.org/problems/registry-breg/attachment/too-large" }) | ({ "code"?: "attachment.verification-pending"; "status"?: 409; "type"?: "https://id.registrystack.org/problems/registry-breg/attachment/verification-pending" }) | ({ "code"?: "attachment.verification-rejected"; "status"?: 422; "type"?: "https://id.registrystack.org/problems/registry-breg/attachment/verification-rejected" }) | ({ "code"?: "authentication.refused"; "status"?: 401; "type"?: "https://id.registrystack.org/problems/registry-breg/authentication/refused" }) | ({ "code"?: "idempotency.expired"; "status"?: 410; "type"?: "https://id.registrystack.org/problems/registry-breg/idempotency/expired" }) | ({ "code"?: "idempotency.key-reused"; "status"?: 409; "type"?: "https://id.registrystack.org/problems/registry-breg/idempotency/key-reused" }) | ({ "code"?: "ingestion.chunk-mismatch"; "status"?: 409; "type"?: "https://id.registrystack.org/problems/registry-breg/ingestion/chunk-mismatch" }) | ({ "code"?: "ingestion.profile-mismatch"; "status"?: 403; "type"?: "https://id.registrystack.org/problems/registry-breg/ingestion/profile-mismatch" }) | ({ "code"?: "ingestion.receipt-erased"; "status"?: 410; "type"?: "https://id.registrystack.org/problems/registry-breg/ingestion/receipt-erased" }) | ({ "code"?: "ingestion.run-blocked"; "status"?: 409; "type"?: "https://id.registrystack.org/problems/registry-breg/ingestion/run-blocked" }) | ({ "code"?: "ingestion.run-not-open"; "status"?: 409; "type"?: "https://id.registrystack.org/problems/registry-breg/ingestion/run-not-open" }) | ({ "code"?: "lookup.unresolved"; "status"?: 404; "type"?: "https://id.registrystack.org/problems/registry-breg/lookup/unresolved" }) | ({ "code"?: "mutation.conflict"; "status"?: 409; "type"?: "https://id.registrystack.org/problems/registry-breg/mutation/conflict" }) | ({ "code"?: "precondition.failed"; "status"?: 412; "type"?: "https://id.registrystack.org/problems/registry-breg/precondition/failed" }) | ({ "code"?: "precondition.required"; "status"?: 428; "type"?: "https://id.registrystack.org/problems/registry-breg/precondition/required" }) | ({ "code"?: "profile.not-authorized"; "status"?: 403; "type"?: "https://id.registrystack.org/problems/registry-breg/profile/not-authorized" }) | ({ "code"?: "proposal.rejected"; "status"?: 409; "type"?: "https://id.registrystack.org/problems/registry-breg/proposal/rejected" }) | ({ "code"?: "proposal.review-result-mismatch"; "status"?: 412; "type"?: "https://id.registrystack.org/problems/registry-breg/proposal/review-result-mismatch" }) | ({ "code"?: "proposal.submission-expired"; "status"?: 410; "type"?: "https://id.registrystack.org/problems/registry-breg/proposal/submission-expired" }) | ({ "code"?: "query.cursor-invalid"; "status"?: 400; "type"?: "https://id.registrystack.org/problems/registry-breg/query/cursor-invalid" }) | ({ "code"?: "query.filter-required"; "status"?: 400; "type"?: "https://id.registrystack.org/problems/registry-breg/query/filter-required" }) | ({ "code"?: "query.invalid"; "status"?: 400; "type"?: "https://id.registrystack.org/problems/registry-breg/query/invalid" }) | ({ "code"?: "request.access-reason-required"; "status"?: 400; "type"?: "https://id.registrystack.org/problems/registry-breg/request/access-reason-required" }) | ({ "code"?: "request.invalid"; "status"?: 400; "type"?: "https://id.registrystack.org/problems/registry-breg/request/invalid" }) | ({ "code"?: "request.timeout"; "status"?: 504; "type"?: "https://id.registrystack.org/problems/registry-breg/request/timeout" }) | ({ "code"?: "resource.not-found"; "status"?: 404; "type"?: "https://id.registrystack.org/problems/registry-breg/resource/not-found" }) | ({ "code"?: "runtime.field-encryption.unavailable"; "status"?: 503; "type"?: "https://id.registrystack.org/problems/registry-breg/runtime/field-encryption/unavailable" }) | ({ "code"?: "service.unavailable"; "status"?: 503; "type"?: "https://id.registrystack.org/problems/registry-breg/service/unavailable" }) | ({ "code"?: "source.unavailable"; "status"?: 503; "type"?: "https://id.registrystack.org/problems/registry-breg/source/unavailable" }) | ({ "code"?: "statistical-dataset.domain-violation"; "status"?: 500; "type"?: "https://id.registrystack.org/problems/registry-breg/statistical-dataset/domain-violation" }) | ({ "code"?: "statistical-dataset.release-refused"; "status"?: 422; "type"?: "https://id.registrystack.org/problems/registry-breg/statistical-dataset/release-refused" }) | ({ "code"?: "statistical-dataset.version-conflict"; "status"?: 409; "type"?: "https://id.registrystack.org/problems/registry-breg/statistical-dataset/version-conflict" }) | ({ "code"?: "statistical-dataset.version-withdrawn"; "status"?: 410; "type"?: "https://id.registrystack.org/problems/registry-breg/statistical-dataset/version-withdrawn" }) | ({ "code"?: "unsupported.media-type"; "status"?: 415; "type"?: "https://id.registrystack.org/problems/registry-breg/unsupported/media-type" }) | ({ "code"?: "write.outside-boundary"; "status"?: 403; "type"?: "https://id.registrystack.org/problems/registry-breg/write/outside-boundary" })) & ({ "accessProfiles"?: (Array<(string)>); "atField"?: (string); "code": ("access-profile.ambiguous" | "action.evidence-failed" | "action.guard-failed" | "action.handler-failed" | "action.refused" | "attachment.content-type" | "attachment.digest-mismatch" | "attachment.limit-reached" | "attachment.required" | "attachment.slot-write-once" | "attachment.too-large" | "attachment.verification-pending" | "attachment.verification-rejected" | "authentication.refused" | "idempotency.expired" | "idempotency.key-reused" | "ingestion.chunk-mismatch" | "ingestion.profile-mismatch" | "ingestion.receipt-erased" | "ingestion.run-blocked" | "ingestion.run-not-open" | "lookup.unresolved" | "mutation.conflict" | "precondition.failed" | "precondition.required" | "profile.not-authorized" | "proposal.rejected" | "proposal.review-result-mismatch" | "proposal.submission-expired" | "query.cursor-invalid" | "query.filter-required" | "query.invalid" | "request.access-reason-required" | "request.invalid" | "request.timeout" | "resource.not-found" | "runtime.field-encryption.unavailable" | "service.unavailable" | "source.unavailable" | "statistical-dataset.domain-violation" | "statistical-dataset.release-refused" | "statistical-dataset.version-conflict" | "statistical-dataset.version-withdrawn" | "unsupported.media-type" | "write.outside-boundary") & (string); "constraintId"?: (string); "constraintKind"?: ("compare" | "int-range" | "vocabulary") & (string); "detail": (string); "failedCheck"?: (string); "field"?: (string); "fieldId"?: (string); "fieldPath"?: (string); "guardReason"?: (string); "left"?: (string); "notAfterField"?: (string); "reasonCode"?: ("computation-error" | "source-data-error" | "disclosure-risk") & (string); "recordType"?: (string); "refusalCode"?: (string); "requiredFilters"?: (Array<(Array<(string)>)>); "right"?: (string); "status": (number); "title": (string); "traceId": (string); "type": (string) }) & (({ "code": "access-profile.ambiguous" } & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & ({ "status"?: 400; "accessProfiles": {} | null })) | ({ "code": "action.evidence-failed" } & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never } & ({ "detail"?: "The declared Evidence dependency could not be accepted."; "fieldPath"?: (string); "status"?: 503 })) | ({ "code": "action.guard-failed" } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "action.handler-failed" } & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never } & ({ "status"?: 500 })) | ({ "code": "action.refused" } & { "guardReason"?: never } & ({ "status"?: 422; "refusalCode": {} | null }) & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "attachment.content-type" } & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "attachment.digest-mismatch" } & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "attachment.limit-reached" } & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "attachment.required" } & ({ "fieldPath": (string) }) & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "attachment.slot-write-once" } & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "attachment.too-large" } & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "attachment.verification-pending" } & ({ "fieldPath": (string) }) & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "attachment.verification-rejected" } & ({ "fieldPath": (string) }) & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "authentication.refused" } & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "idempotency.expired" } & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "idempotency.key-reused" } & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "ingestion.chunk-mismatch" } & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "ingestion.profile-mismatch" } & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "ingestion.receipt-erased" } & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "ingestion.run-blocked" } & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "ingestion.run-not-open" } & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "lookup.unresolved" } & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "mutation.conflict" } & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "precondition.failed" } & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "precondition.required" } & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "profile.not-authorized" } & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "proposal.rejected" } & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "proposal.review-result-mismatch" } & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "proposal.submission-expired" } & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "query.cursor-invalid" } & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "query.filter-required" } & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "query.invalid" } & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "request.access-reason-required" } & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "request.invalid" } & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "request.timeout" } & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "resource.not-found" } & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "runtime.field-encryption.unavailable" } & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "service.unavailable" } & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "source.unavailable" } & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "statistical-dataset.domain-violation" } & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "statistical-dataset.release-refused" } & { "guardReason"?: never } & ({ "refusalCode": ("period-not-ended" | "before-first-period" | "provisional-after-final" | "already-withdrawn" | "negative-value"); "status"?: 422 }) & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "statistical-dataset.version-conflict" } & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "statistical-dataset.version-withdrawn" } & { "guardReason"?: never } & { "refusalCode"?: never } & ({ "status"?: 410; "reasonCode": {} | null }) & { "accessProfiles"?: never }) | ({ "code": "unsupported.media-type" } & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "write.outside-boundary" } & ({ "code"?: "write.outside-boundary"; "detail"?: "The write falls outside what the selected access profile may write: its row boundary or a disclosure condition."; "status"?: 403; "title"?: "Forbidden"; "type"?: "https://id.registrystack.org/problems/registry-breg/write/outside-boundary" }) & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never })) +export type Schema_Problem = (({ "code"?: "access-profile.ambiguous"; "status"?: 400; "type"?: "https://id.registrystack.org/problems/registry-breg/access-profile/ambiguous" }) | ({ "code"?: "action.evidence-failed"; "status"?: 503; "type"?: "https://id.registrystack.org/problems/registry-breg/action/evidence-failed" }) | ({ "code"?: "action.guard-failed"; "status"?: 412; "type"?: "https://id.registrystack.org/problems/registry-breg/action/guard-failed" }) | ({ "code"?: "action.handler-failed"; "status"?: 500; "type"?: "https://id.registrystack.org/problems/registry-breg/action/handler-failed" }) | ({ "code"?: "action.refused"; "status"?: 422; "type"?: "https://id.registrystack.org/problems/registry-breg/action/refused" }) | ({ "code"?: "attachment.content-type"; "status"?: 415; "type"?: "https://id.registrystack.org/problems/registry-breg/attachment/content-type" }) | ({ "code"?: "attachment.digest-mismatch"; "status"?: 422; "type"?: "https://id.registrystack.org/problems/registry-breg/attachment/digest-mismatch" }) | ({ "code"?: "attachment.limit-reached"; "status"?: 409; "type"?: "https://id.registrystack.org/problems/registry-breg/attachment/limit-reached" }) | ({ "code"?: "attachment.required"; "status"?: 422; "type"?: "https://id.registrystack.org/problems/registry-breg/attachment/required" }) | ({ "code"?: "attachment.slot-write-once"; "status"?: 409; "type"?: "https://id.registrystack.org/problems/registry-breg/attachment/slot-write-once" }) | ({ "code"?: "attachment.too-large"; "status"?: 413; "type"?: "https://id.registrystack.org/problems/registry-breg/attachment/too-large" }) | ({ "code"?: "attachment.verification-pending"; "status"?: 409; "type"?: "https://id.registrystack.org/problems/registry-breg/attachment/verification-pending" }) | ({ "code"?: "attachment.verification-rejected"; "status"?: 422; "type"?: "https://id.registrystack.org/problems/registry-breg/attachment/verification-rejected" }) | ({ "code"?: "authentication.refused"; "status"?: 401; "type"?: "https://id.registrystack.org/problems/registry-breg/authentication/refused" }) | ({ "code"?: "idempotency.expired"; "status"?: 410; "type"?: "https://id.registrystack.org/problems/registry-breg/idempotency/expired" }) | ({ "code"?: "idempotency.key-reused"; "status"?: 409; "type"?: "https://id.registrystack.org/problems/registry-breg/idempotency/key-reused" }) | ({ "code"?: "ingestion.chunk-mismatch"; "status"?: 409; "type"?: "https://id.registrystack.org/problems/registry-breg/ingestion/chunk-mismatch" }) | ({ "code"?: "ingestion.profile-mismatch"; "status"?: 403; "type"?: "https://id.registrystack.org/problems/registry-breg/ingestion/profile-mismatch" }) | ({ "code"?: "ingestion.receipt-erased"; "status"?: 410; "type"?: "https://id.registrystack.org/problems/registry-breg/ingestion/receipt-erased" }) | ({ "code"?: "ingestion.run-blocked"; "status"?: 409; "type"?: "https://id.registrystack.org/problems/registry-breg/ingestion/run-blocked" }) | ({ "code"?: "ingestion.run-not-open"; "status"?: 409; "type"?: "https://id.registrystack.org/problems/registry-breg/ingestion/run-not-open" }) | ({ "code"?: "lookup.unresolved"; "status"?: 404; "type"?: "https://id.registrystack.org/problems/registry-breg/lookup/unresolved" }) | ({ "code"?: "mutation.conflict"; "status"?: 409; "type"?: "https://id.registrystack.org/problems/registry-breg/mutation/conflict" }) | ({ "code"?: "precondition.failed"; "status"?: 412; "type"?: "https://id.registrystack.org/problems/registry-breg/precondition/failed" }) | ({ "code"?: "precondition.required"; "status"?: 428; "type"?: "https://id.registrystack.org/problems/registry-breg/precondition/required" }) | ({ "code"?: "profile.not-authorized"; "status"?: 403; "type"?: "https://id.registrystack.org/problems/registry-breg/profile/not-authorized" }) | ({ "code"?: "proposal.form-limit-reached"; "status"?: 409; "type"?: "https://id.registrystack.org/problems/registry-breg/proposal/form-limit-reached" }) | ({ "code"?: "proposal.form-undeclared"; "status"?: 404; "type"?: "https://id.registrystack.org/problems/registry-breg/proposal/form-undeclared" }) | ({ "code"?: "proposal.message-limit-reached"; "status"?: 409; "type"?: "https://id.registrystack.org/problems/registry-breg/proposal/message-limit-reached" }) | ({ "code"?: "proposal.rejected"; "status"?: 409; "type"?: "https://id.registrystack.org/problems/registry-breg/proposal/rejected" }) | ({ "code"?: "proposal.review-result-mismatch"; "status"?: 412; "type"?: "https://id.registrystack.org/problems/registry-breg/proposal/review-result-mismatch" }) | ({ "code"?: "proposal.subject-changed"; "status"?: 409; "type"?: "https://id.registrystack.org/problems/registry-breg/proposal/subject-changed" }) | ({ "code"?: "proposal.subject-not-caller"; "status"?: 403; "type"?: "https://id.registrystack.org/problems/registry-breg/proposal/subject-not-caller" }) | ({ "code"?: "proposal.submission-expired"; "status"?: 410; "type"?: "https://id.registrystack.org/problems/registry-breg/proposal/submission-expired" }) | ({ "code"?: "query.cursor-invalid"; "status"?: 400; "type"?: "https://id.registrystack.org/problems/registry-breg/query/cursor-invalid" }) | ({ "code"?: "query.filter-required"; "status"?: 400; "type"?: "https://id.registrystack.org/problems/registry-breg/query/filter-required" }) | ({ "code"?: "query.invalid"; "status"?: 400; "type"?: "https://id.registrystack.org/problems/registry-breg/query/invalid" }) | ({ "code"?: "request.access-reason-required"; "status"?: 400; "type"?: "https://id.registrystack.org/problems/registry-breg/request/access-reason-required" }) | ({ "code"?: "request.invalid"; "status"?: 400; "type"?: "https://id.registrystack.org/problems/registry-breg/request/invalid" }) | ({ "code"?: "request.timeout"; "status"?: 504; "type"?: "https://id.registrystack.org/problems/registry-breg/request/timeout" }) | ({ "code"?: "resource.not-found"; "status"?: 404; "type"?: "https://id.registrystack.org/problems/registry-breg/resource/not-found" }) | ({ "code"?: "runtime.field-encryption.unavailable"; "status"?: 503; "type"?: "https://id.registrystack.org/problems/registry-breg/runtime/field-encryption/unavailable" }) | ({ "code"?: "service.unavailable"; "status"?: 503; "type"?: "https://id.registrystack.org/problems/registry-breg/service/unavailable" }) | ({ "code"?: "source.unavailable"; "status"?: 503; "type"?: "https://id.registrystack.org/problems/registry-breg/source/unavailable" }) | ({ "code"?: "statistical-dataset.domain-violation"; "status"?: 500; "type"?: "https://id.registrystack.org/problems/registry-breg/statistical-dataset/domain-violation" }) | ({ "code"?: "statistical-dataset.release-refused"; "status"?: 422; "type"?: "https://id.registrystack.org/problems/registry-breg/statistical-dataset/release-refused" }) | ({ "code"?: "statistical-dataset.version-conflict"; "status"?: 409; "type"?: "https://id.registrystack.org/problems/registry-breg/statistical-dataset/version-conflict" }) | ({ "code"?: "statistical-dataset.version-withdrawn"; "status"?: 410; "type"?: "https://id.registrystack.org/problems/registry-breg/statistical-dataset/version-withdrawn" }) | ({ "code"?: "unsupported.media-type"; "status"?: 415; "type"?: "https://id.registrystack.org/problems/registry-breg/unsupported/media-type" }) | ({ "code"?: "write.outside-boundary"; "status"?: 403; "type"?: "https://id.registrystack.org/problems/registry-breg/write/outside-boundary" })) & ({ "accessProfiles"?: (Array<(string)>); "atField"?: (string); "code": ("access-profile.ambiguous" | "action.evidence-failed" | "action.guard-failed" | "action.handler-failed" | "action.refused" | "attachment.content-type" | "attachment.digest-mismatch" | "attachment.limit-reached" | "attachment.required" | "attachment.slot-write-once" | "attachment.too-large" | "attachment.verification-pending" | "attachment.verification-rejected" | "authentication.refused" | "idempotency.expired" | "idempotency.key-reused" | "ingestion.chunk-mismatch" | "ingestion.profile-mismatch" | "ingestion.receipt-erased" | "ingestion.run-blocked" | "ingestion.run-not-open" | "lookup.unresolved" | "mutation.conflict" | "precondition.failed" | "precondition.required" | "profile.not-authorized" | "proposal.form-limit-reached" | "proposal.form-undeclared" | "proposal.message-limit-reached" | "proposal.rejected" | "proposal.review-result-mismatch" | "proposal.subject-changed" | "proposal.subject-not-caller" | "proposal.submission-expired" | "query.cursor-invalid" | "query.filter-required" | "query.invalid" | "request.access-reason-required" | "request.invalid" | "request.timeout" | "resource.not-found" | "runtime.field-encryption.unavailable" | "service.unavailable" | "source.unavailable" | "statistical-dataset.domain-violation" | "statistical-dataset.release-refused" | "statistical-dataset.version-conflict" | "statistical-dataset.version-withdrawn" | "unsupported.media-type" | "write.outside-boundary") & (string); "constraintId"?: (string); "constraintKind"?: ("compare" | "int-range" | "vocabulary") & (string); "detail": (string); "failedCheck"?: (string); "field"?: (string); "fieldId"?: (string); "fieldPath"?: (string); "guardReason"?: (string); "left"?: (string); "notAfterField"?: (string); "reasonCode"?: ("computation-error" | "source-data-error" | "disclosure-risk") & (string); "recordType"?: (string); "refusalCode"?: (string); "requiredFilters"?: (Array<(Array<(string)>)>); "right"?: (string); "status": (number); "title": (string); "traceId": (string); "type": (string) }) & (({ "code": "access-profile.ambiguous" } & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & ({ "status"?: 400; "accessProfiles": {} | null })) | ({ "code": "action.evidence-failed" } & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never } & ({ "detail"?: "The declared Evidence dependency could not be accepted."; "fieldPath"?: (string); "status"?: 503 })) | ({ "code": "action.guard-failed" } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "action.handler-failed" } & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never } & ({ "status"?: 500 })) | ({ "code": "action.refused" } & { "guardReason"?: never } & ({ "status"?: 422; "refusalCode": {} | null }) & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "attachment.content-type" } & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "attachment.digest-mismatch" } & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "attachment.limit-reached" } & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "attachment.required" } & ({ "fieldPath": (string) }) & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "attachment.slot-write-once" } & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "attachment.too-large" } & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "attachment.verification-pending" } & ({ "fieldPath": (string) }) & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "attachment.verification-rejected" } & ({ "fieldPath": (string) }) & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "authentication.refused" } & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "idempotency.expired" } & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "idempotency.key-reused" } & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "ingestion.chunk-mismatch" } & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "ingestion.profile-mismatch" } & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "ingestion.receipt-erased" } & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "ingestion.run-blocked" } & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "ingestion.run-not-open" } & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "lookup.unresolved" } & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "mutation.conflict" } & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "precondition.failed" } & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "precondition.required" } & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "profile.not-authorized" } & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "proposal.form-limit-reached" } & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "proposal.form-undeclared" } & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "proposal.message-limit-reached" } & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "proposal.rejected" } & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "proposal.review-result-mismatch" } & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "proposal.subject-changed" } & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "proposal.subject-not-caller" } & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "proposal.submission-expired" } & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "query.cursor-invalid" } & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "query.filter-required" } & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "query.invalid" } & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "request.access-reason-required" } & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "request.invalid" } & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "request.timeout" } & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "resource.not-found" } & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "runtime.field-encryption.unavailable" } & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "service.unavailable" } & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "source.unavailable" } & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "statistical-dataset.domain-violation" } & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "statistical-dataset.release-refused" } & { "guardReason"?: never } & ({ "refusalCode": ("period-not-ended" | "before-first-period" | "provisional-after-final" | "already-withdrawn" | "negative-value"); "status"?: 422 }) & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "statistical-dataset.version-conflict" } & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "statistical-dataset.version-withdrawn" } & { "guardReason"?: never } & { "refusalCode"?: never } & ({ "status"?: 410; "reasonCode": {} | null }) & { "accessProfiles"?: never }) | ({ "code": "unsupported.media-type" } & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "write.outside-boundary" } & ({ "code"?: "write.outside-boundary"; "detail"?: "The write falls outside what the selected access profile may write: its row boundary or a disclosure condition."; "status"?: 403; "title"?: "Forbidden"; "type"?: "https://id.registrystack.org/problems/registry-breg/write/outside-boundary" }) & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never })) export type Schema_ReviewCompletion = ({ "completedAt": (string); "eventId": (string); "requestId": (string); "resultId": (string); "type": "review.completed" }) export type Schema_action_correct_address_invoke_input = ({ "input": ({ "addressLine"?: (string); "city"?: (string); "facilityId"?: (string); "postalCode"?: (string) }) }) -export type Schema_action_correct_address_invoke_response = ({ "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); "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") })>) })>); "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); "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") }) +export type Schema_action_correct_address_invoke_response = ({ "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") }) export type Schema_action_deactivate_facility_invoke_input = ({ "input": ({ "facilityId"?: (string) }) }) -export type Schema_action_deactivate_facility_invoke_response = ({ "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); "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") })>) })>); "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); "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") }) +export type Schema_action_deactivate_facility_invoke_response = ({ "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") }) export type Schema_action_register_facility_availability_input = (({ "input"?: ({ "operatorId": (string) }); "targetInput"?: "operatorId" })) & ({ "input": ({ "addressLine"?: (string); "city"?: (string); "facilityCode"?: (string); "jurisdiction"?: (string); "name"?: (string); "operatorId"?: (string); "postalCode"?: (string) }); "targetInput": ("operatorId") & (string) }) export type Schema_action_register_facility_availability_response = ({ "availability": (({ "available": true; "observedRevision": (number) }) | ({ "available": false; "guardLabel"?: (string); "guardReason"?: (string); "observedRevision": (number); "reason": "guard-not-satisfied"; "recovery": "none" }) | ({ "available": (null); "missingInputs": (Array<("facilityCode" | "name" | "addressLine" | "city" | "postalCode" | "operatorId" | "jurisdiction") & (string)>); "observedRevision": (number); "reason": "input-required"; "recovery": "correct-input" }) | ({ "available": (null); "observedRevision": (null); "reason": "not-disclosed"; "recovery": "none" })) }) export type Schema_action_register_facility_invoke_input = ({ "input": ({ "addressLine": (string); "city": (string); "facilityCode": (string); "jurisdiction": (string); "name": (string); "operatorId": (string); "postalCode": (string) }); "preconditions"?: (Record) }) @@ -32,26 +36,26 @@ export interface Operations { "actions.deactivate-facility.start": { input: CallOptions & { query?: { "accessProfile"?: "facility-correction-author" } } & { headers?: { "traceparent"?: (string) } } & ({ body: Schema_action_deactivate_facility_invoke_input }) & { accept?: "application/json" | "*/*" }; required: true; output: Schema_action_deactivate_facility_invoke_response } "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); "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") })>) })>); "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); "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": { 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); "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") })>) })>); "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); "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); "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") })>) })>); "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); "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); "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") })>) })>); "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); "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.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"?: (({ "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") }) } "proposals.attachments.supporting-document.get": { input: CallOptions & { path: { "proposal_id": (string) } } & { query: { "accessProfile"?: "facility-correction-author" | "proposal-reviewer"; "submissionVersion": (number); "reviewContextField"?: (string); "effectDigest"?: (string); "contextSchemaDigest"?: (string) } } & { accept?: "*/*" }; required: true; output: WireBytes } - "proposals.attachments.supporting-document.patch": { input: CallOptions & { path: { "proposal_id": (string) } } & { query?: { "accessProfile"?: "facility-correction-author" } } & { headers: { "If-Match": (string) } } & ({ body: Uint8Array | Blob | 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); "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") })>) })>); "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); "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.cancel": { 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); "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") })>) })>); "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); "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.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); "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") })>) })>); "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); "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); "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") })>) })>); "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); "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); "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") })>) })>); "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); "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") })>); "text"?: (string) }); "askedAt": (string); "dueAt"?: (string); "id": (string); "state": ("open" | "answered" | "expired" | "closed"); "text": (string); "wants": (Array<({ "kind": ("answer" | "document") })>) })>); "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.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); "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") })>) })>); "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); "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.patch": { input: CallOptions & { path: { "proposal_id": (string) } } & { query?: { "accessProfile"?: "facility-correction-author" } } & { headers: { "If-Match": (string) } } & ({ body: Uint8Array | Blob | 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.cancel": { 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.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"?: (({ "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); "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") })>) })>); "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); "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.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 } } @@ -105,12 +109,12 @@ function recordRow(record: RecordEnvelope & { domainData: Data }): RecordR } const rules: Record = Object.fromEntries([ - ["/components/schemas/Problem", JSON.parse("{\"additionalProperties\":false,\"allOf\":[{\"if\":{\"properties\":{\"code\":{\"enum\":[\"attachment.required\",\"attachment.verification-pending\",\"attachment.verification-rejected\"]}}},\"then\":{\"allOf\":[{\"else\":{\"properties\":{\"status\":{\"const\":422}}},\"if\":{\"properties\":{\"code\":{\"const\":\"attachment.verification-pending\"}}},\"then\":{\"properties\":{\"status\":{\"const\":409}}}}],\"properties\":{\"fieldPath\":{\"pattern\":\"^/attachments/[a-z][a-z0-9_-]{0,63}$\",\"type\":\"string\"}},\"propertyNames\":{\"enum\":[\"type\",\"title\",\"status\",\"detail\",\"code\",\"traceId\",\"fieldPath\"]},\"required\":[\"fieldPath\"]}},{\"if\":{\"properties\":{\"code\":{\"const\":\"write.outside-boundary\"}}},\"then\":{\"properties\":{\"code\":{\"const\":\"write.outside-boundary\"},\"detail\":{\"const\":\"The write falls outside what the selected access profile may write: its row boundary or a disclosure condition.\"},\"status\":{\"const\":403},\"title\":{\"const\":\"Forbidden\"},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/write/outside-boundary\"}},\"propertyNames\":{\"enum\":[\"type\",\"title\",\"status\",\"detail\",\"code\",\"traceId\",\"failedCheck\"]}}},{\"if\":{\"properties\":{\"code\":{\"not\":{\"const\":\"action.guard-failed\"}}}},\"then\":{\"not\":{\"required\":[\"guardReason\"]}}},{\"if\":{\"properties\":{\"code\":{\"const\":\"action.refused\"}}},\"then\":{\"properties\":{\"status\":{\"const\":422}},\"required\":[\"refusalCode\"]}},{\"if\":{\"properties\":{\"code\":{\"const\":\"statistical-dataset.release-refused\"}}},\"then\":{\"properties\":{\"refusalCode\":{\"enum\":[\"period-not-ended\",\"before-first-period\",\"provisional-after-final\",\"already-withdrawn\",\"negative-value\"]},\"status\":{\"const\":422}},\"required\":[\"refusalCode\"]}},{\"if\":{\"properties\":{\"code\":{\"not\":{\"enum\":[\"action.refused\",\"statistical-dataset.release-refused\"]}}}},\"then\":{\"not\":{\"required\":[\"refusalCode\"]}}},{\"if\":{\"properties\":{\"code\":{\"const\":\"statistical-dataset.version-withdrawn\"}}},\"then\":{\"properties\":{\"status\":{\"const\":410}},\"required\":[\"reasonCode\"]}},{\"if\":{\"properties\":{\"code\":{\"not\":{\"const\":\"statistical-dataset.version-withdrawn\"}}}},\"then\":{\"not\":{\"required\":[\"reasonCode\"]}}},{\"if\":{\"properties\":{\"code\":{\"const\":\"access-profile.ambiguous\"}}},\"then\":{\"additionalProperties\":true,\"not\":{\"required\":[\"failedCheck\"]},\"properties\":{\"status\":{\"const\":400}},\"required\":[\"accessProfiles\"]}},{\"if\":{\"properties\":{\"code\":{\"not\":{\"const\":\"access-profile.ambiguous\"}}}},\"then\":{\"not\":{\"required\":[\"accessProfiles\"]}}},{\"if\":{\"properties\":{\"code\":{\"const\":\"action.evidence-failed\"}}},\"then\":{\"properties\":{\"detail\":{\"const\":\"The declared Evidence dependency could not be accepted.\"},\"fieldPath\":{\"pattern\":\"^/evidence/[a-z][a-z0-9_-]{0,63}$\",\"type\":\"string\"},\"status\":{\"const\":503}}}},{\"if\":{\"properties\":{\"code\":{\"const\":\"action.handler-failed\"}}},\"then\":{\"properties\":{\"status\":{\"const\":500}}}},{\"if\":{\"anyOf\":[{\"required\":[\"atField\"]},{\"required\":[\"notAfterField\"]}]},\"then\":{\"properties\":{\"code\":{\"const\":\"request.invalid\"},\"status\":{\"const\":400}},\"required\":[\"atField\",\"notAfterField\"]}},{\"if\":{\"anyOf\":[{\"required\":[\"recordType\"]},{\"required\":[\"fieldId\"]},{\"required\":[\"constraintId\"]},{\"required\":[\"constraintKind\"]},{\"required\":[\"left\"]},{\"required\":[\"right\"]},{\"required\":[\"field\"]}]},\"then\":{\"oneOf\":[{\"not\":{\"anyOf\":[{\"required\":[\"constraintId\"]},{\"required\":[\"constraintKind\"]},{\"required\":[\"left\"]},{\"required\":[\"right\"]},{\"required\":[\"field\"]}]},\"required\":[\"fieldId\"]},{\"not\":{\"required\":[\"fieldId\"]},\"oneOf\":[{\"not\":{\"required\":[\"field\"]},\"properties\":{\"constraintKind\":{\"const\":\"compare\"}},\"required\":[\"left\",\"right\"]},{\"not\":{\"anyOf\":[{\"required\":[\"left\"]},{\"required\":[\"right\"]}]},\"properties\":{\"constraintKind\":{\"enum\":[\"int-range\",\"vocabulary\"]}},\"required\":[\"field\"]}],\"required\":[\"constraintId\",\"constraintKind\"]}],\"properties\":{\"code\":{\"const\":\"mutation.conflict\"},\"status\":{\"const\":409}},\"required\":[\"recordType\"]}}],\"anyOf\":[{\"properties\":{\"code\":{\"const\":\"access-profile.ambiguous\"},\"status\":{\"const\":400},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/access-profile/ambiguous\"}}},{\"properties\":{\"code\":{\"const\":\"action.evidence-failed\"},\"status\":{\"const\":503},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/action/evidence-failed\"}}},{\"properties\":{\"code\":{\"const\":\"action.guard-failed\"},\"status\":{\"const\":412},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/action/guard-failed\"}}},{\"properties\":{\"code\":{\"const\":\"action.handler-failed\"},\"status\":{\"const\":500},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/action/handler-failed\"}}},{\"properties\":{\"code\":{\"const\":\"action.refused\"},\"status\":{\"const\":422},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/action/refused\"}}},{\"properties\":{\"code\":{\"const\":\"attachment.content-type\"},\"status\":{\"const\":415},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/attachment/content-type\"}}},{\"properties\":{\"code\":{\"const\":\"attachment.digest-mismatch\"},\"status\":{\"const\":422},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/attachment/digest-mismatch\"}}},{\"properties\":{\"code\":{\"const\":\"attachment.limit-reached\"},\"status\":{\"const\":409},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/attachment/limit-reached\"}}},{\"properties\":{\"code\":{\"const\":\"attachment.required\"},\"status\":{\"const\":422},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/attachment/required\"}}},{\"properties\":{\"code\":{\"const\":\"attachment.slot-write-once\"},\"status\":{\"const\":409},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/attachment/slot-write-once\"}}},{\"properties\":{\"code\":{\"const\":\"attachment.too-large\"},\"status\":{\"const\":413},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/attachment/too-large\"}}},{\"properties\":{\"code\":{\"const\":\"attachment.verification-pending\"},\"status\":{\"const\":409},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/attachment/verification-pending\"}}},{\"properties\":{\"code\":{\"const\":\"attachment.verification-rejected\"},\"status\":{\"const\":422},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/attachment/verification-rejected\"}}},{\"properties\":{\"code\":{\"const\":\"authentication.refused\"},\"status\":{\"const\":401},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/authentication/refused\"}}},{\"properties\":{\"code\":{\"const\":\"idempotency.expired\"},\"status\":{\"const\":410},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/idempotency/expired\"}}},{\"properties\":{\"code\":{\"const\":\"idempotency.key-reused\"},\"status\":{\"const\":409},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/idempotency/key-reused\"}}},{\"properties\":{\"code\":{\"const\":\"ingestion.chunk-mismatch\"},\"status\":{\"const\":409},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/ingestion/chunk-mismatch\"}}},{\"properties\":{\"code\":{\"const\":\"ingestion.profile-mismatch\"},\"status\":{\"const\":403},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/ingestion/profile-mismatch\"}}},{\"properties\":{\"code\":{\"const\":\"ingestion.receipt-erased\"},\"status\":{\"const\":410},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/ingestion/receipt-erased\"}}},{\"properties\":{\"code\":{\"const\":\"ingestion.run-blocked\"},\"status\":{\"const\":409},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/ingestion/run-blocked\"}}},{\"properties\":{\"code\":{\"const\":\"ingestion.run-not-open\"},\"status\":{\"const\":409},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/ingestion/run-not-open\"}}},{\"properties\":{\"code\":{\"const\":\"lookup.unresolved\"},\"status\":{\"const\":404},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/lookup/unresolved\"}}},{\"properties\":{\"code\":{\"const\":\"mutation.conflict\"},\"status\":{\"const\":409},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/mutation/conflict\"}}},{\"properties\":{\"code\":{\"const\":\"precondition.failed\"},\"status\":{\"const\":412},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/precondition/failed\"}}},{\"properties\":{\"code\":{\"const\":\"precondition.required\"},\"status\":{\"const\":428},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/precondition/required\"}}},{\"properties\":{\"code\":{\"const\":\"profile.not-authorized\"},\"status\":{\"const\":403},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/profile/not-authorized\"}}},{\"properties\":{\"code\":{\"const\":\"proposal.rejected\"},\"status\":{\"const\":409},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/proposal/rejected\"}}},{\"properties\":{\"code\":{\"const\":\"proposal.review-result-mismatch\"},\"status\":{\"const\":412},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/proposal/review-result-mismatch\"}}},{\"properties\":{\"code\":{\"const\":\"proposal.submission-expired\"},\"status\":{\"const\":410},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/proposal/submission-expired\"}}},{\"properties\":{\"code\":{\"const\":\"query.cursor-invalid\"},\"status\":{\"const\":400},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/query/cursor-invalid\"}}},{\"properties\":{\"code\":{\"const\":\"query.filter-required\"},\"status\":{\"const\":400},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/query/filter-required\"}}},{\"properties\":{\"code\":{\"const\":\"query.invalid\"},\"status\":{\"const\":400},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/query/invalid\"}}},{\"properties\":{\"code\":{\"const\":\"request.access-reason-required\"},\"status\":{\"const\":400},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/request/access-reason-required\"}}},{\"properties\":{\"code\":{\"const\":\"request.invalid\"},\"status\":{\"const\":400},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/request/invalid\"}}},{\"properties\":{\"code\":{\"const\":\"request.timeout\"},\"status\":{\"const\":504},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/request/timeout\"}}},{\"properties\":{\"code\":{\"const\":\"resource.not-found\"},\"status\":{\"const\":404},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/resource/not-found\"}}},{\"properties\":{\"code\":{\"const\":\"runtime.field-encryption.unavailable\"},\"status\":{\"const\":503},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/runtime/field-encryption/unavailable\"}}},{\"properties\":{\"code\":{\"const\":\"service.unavailable\"},\"status\":{\"const\":503},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/service/unavailable\"}}},{\"properties\":{\"code\":{\"const\":\"source.unavailable\"},\"status\":{\"const\":503},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/source/unavailable\"}}},{\"properties\":{\"code\":{\"const\":\"statistical-dataset.domain-violation\"},\"status\":{\"const\":500},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/statistical-dataset/domain-violation\"}}},{\"properties\":{\"code\":{\"const\":\"statistical-dataset.release-refused\"},\"status\":{\"const\":422},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/statistical-dataset/release-refused\"}}},{\"properties\":{\"code\":{\"const\":\"statistical-dataset.version-conflict\"},\"status\":{\"const\":409},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/statistical-dataset/version-conflict\"}}},{\"properties\":{\"code\":{\"const\":\"statistical-dataset.version-withdrawn\"},\"status\":{\"const\":410},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/statistical-dataset/version-withdrawn\"}}},{\"properties\":{\"code\":{\"const\":\"unsupported.media-type\"},\"status\":{\"const\":415},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/unsupported/media-type\"}}},{\"properties\":{\"code\":{\"const\":\"write.outside-boundary\"},\"status\":{\"const\":403},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/write/outside-boundary\"}}}],\"properties\":{\"accessProfiles\":{\"items\":{\"maxLength\":128,\"minLength\":1,\"type\":\"string\"},\"minItems\":2,\"type\":\"array\",\"uniqueItems\":true},\"atField\":{\"maxLength\":128,\"minLength\":1,\"type\":\"string\"},\"code\":{\"enum\":[\"access-profile.ambiguous\",\"action.evidence-failed\",\"action.guard-failed\",\"action.handler-failed\",\"action.refused\",\"attachment.content-type\",\"attachment.digest-mismatch\",\"attachment.limit-reached\",\"attachment.required\",\"attachment.slot-write-once\",\"attachment.too-large\",\"attachment.verification-pending\",\"attachment.verification-rejected\",\"authentication.refused\",\"idempotency.expired\",\"idempotency.key-reused\",\"ingestion.chunk-mismatch\",\"ingestion.profile-mismatch\",\"ingestion.receipt-erased\",\"ingestion.run-blocked\",\"ingestion.run-not-open\",\"lookup.unresolved\",\"mutation.conflict\",\"precondition.failed\",\"precondition.required\",\"profile.not-authorized\",\"proposal.rejected\",\"proposal.review-result-mismatch\",\"proposal.submission-expired\",\"query.cursor-invalid\",\"query.filter-required\",\"query.invalid\",\"request.access-reason-required\",\"request.invalid\",\"request.timeout\",\"resource.not-found\",\"runtime.field-encryption.unavailable\",\"service.unavailable\",\"source.unavailable\",\"statistical-dataset.domain-violation\",\"statistical-dataset.release-refused\",\"statistical-dataset.version-conflict\",\"statistical-dataset.version-withdrawn\",\"unsupported.media-type\",\"write.outside-boundary\"],\"type\":\"string\"},\"constraintId\":{\"maxLength\":128,\"minLength\":1,\"type\":\"string\"},\"constraintKind\":{\"enum\":[\"compare\",\"int-range\",\"vocabulary\"],\"type\":\"string\"},\"detail\":{\"maxLength\":256,\"type\":\"string\"},\"failedCheck\":{\"type\":\"string\"},\"field\":{\"maxLength\":128,\"minLength\":1,\"type\":\"string\"},\"fieldId\":{\"maxLength\":128,\"minLength\":1,\"type\":\"string\"},\"fieldPath\":{\"maxLength\":256,\"type\":\"string\"},\"guardReason\":{\"pattern\":\"^[a-z][a-z0-9_-]{0,63}$\",\"type\":\"string\"},\"left\":{\"maxLength\":128,\"minLength\":1,\"type\":\"string\"},\"notAfterField\":{\"maxLength\":128,\"minLength\":1,\"type\":\"string\"},\"reasonCode\":{\"enum\":[\"computation-error\",\"source-data-error\",\"disclosure-risk\"],\"type\":\"string\"},\"recordType\":{\"maxLength\":128,\"minLength\":1,\"type\":\"string\"},\"refusalCode\":{\"maxLength\":128,\"minLength\":1,\"type\":\"string\"},\"requiredFilters\":{\"items\":{\"items\":{\"maxLength\":64,\"minLength\":1,\"type\":\"string\"},\"maxItems\":32,\"minItems\":1,\"type\":\"array\",\"uniqueItems\":true},\"maxItems\":8,\"minItems\":1,\"type\":\"array\"},\"right\":{\"maxLength\":128,\"minLength\":1,\"type\":\"string\"},\"status\":{\"maximum\":599,\"minimum\":400,\"type\":\"integer\"},\"title\":{\"maxLength\":128,\"type\":\"string\"},\"traceId\":{\"maxLength\":32,\"minLength\":32,\"pattern\":\"^[0-9a-f]{32}$\",\"type\":\"string\"},\"type\":{\"maxLength\":256,\"type\":\"string\"}},\"required\":[\"type\",\"title\",\"status\",\"detail\",\"code\",\"traceId\"],\"type\":\"object\"}")], + ["/components/schemas/Problem", JSON.parse("{\"additionalProperties\":false,\"allOf\":[{\"if\":{\"properties\":{\"code\":{\"enum\":[\"attachment.required\",\"attachment.verification-pending\",\"attachment.verification-rejected\"]}}},\"then\":{\"allOf\":[{\"else\":{\"properties\":{\"status\":{\"const\":422}}},\"if\":{\"properties\":{\"code\":{\"const\":\"attachment.verification-pending\"}}},\"then\":{\"properties\":{\"status\":{\"const\":409}}}}],\"properties\":{\"fieldPath\":{\"pattern\":\"^/attachments/[a-z][a-z0-9_-]{0,63}$\",\"type\":\"string\"}},\"propertyNames\":{\"enum\":[\"type\",\"title\",\"status\",\"detail\",\"code\",\"traceId\",\"fieldPath\"]},\"required\":[\"fieldPath\"]}},{\"if\":{\"properties\":{\"code\":{\"const\":\"write.outside-boundary\"}}},\"then\":{\"properties\":{\"code\":{\"const\":\"write.outside-boundary\"},\"detail\":{\"const\":\"The write falls outside what the selected access profile may write: its row boundary or a disclosure condition.\"},\"status\":{\"const\":403},\"title\":{\"const\":\"Forbidden\"},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/write/outside-boundary\"}},\"propertyNames\":{\"enum\":[\"type\",\"title\",\"status\",\"detail\",\"code\",\"traceId\",\"failedCheck\"]}}},{\"if\":{\"properties\":{\"code\":{\"not\":{\"const\":\"action.guard-failed\"}}}},\"then\":{\"not\":{\"required\":[\"guardReason\"]}}},{\"if\":{\"properties\":{\"code\":{\"const\":\"action.refused\"}}},\"then\":{\"properties\":{\"status\":{\"const\":422}},\"required\":[\"refusalCode\"]}},{\"if\":{\"properties\":{\"code\":{\"const\":\"statistical-dataset.release-refused\"}}},\"then\":{\"properties\":{\"refusalCode\":{\"enum\":[\"period-not-ended\",\"before-first-period\",\"provisional-after-final\",\"already-withdrawn\",\"negative-value\"]},\"status\":{\"const\":422}},\"required\":[\"refusalCode\"]}},{\"if\":{\"properties\":{\"code\":{\"not\":{\"enum\":[\"action.refused\",\"statistical-dataset.release-refused\"]}}}},\"then\":{\"not\":{\"required\":[\"refusalCode\"]}}},{\"if\":{\"properties\":{\"code\":{\"const\":\"statistical-dataset.version-withdrawn\"}}},\"then\":{\"properties\":{\"status\":{\"const\":410}},\"required\":[\"reasonCode\"]}},{\"if\":{\"properties\":{\"code\":{\"not\":{\"const\":\"statistical-dataset.version-withdrawn\"}}}},\"then\":{\"not\":{\"required\":[\"reasonCode\"]}}},{\"if\":{\"properties\":{\"code\":{\"const\":\"access-profile.ambiguous\"}}},\"then\":{\"additionalProperties\":true,\"not\":{\"required\":[\"failedCheck\"]},\"properties\":{\"status\":{\"const\":400}},\"required\":[\"accessProfiles\"]}},{\"if\":{\"properties\":{\"code\":{\"not\":{\"const\":\"access-profile.ambiguous\"}}}},\"then\":{\"not\":{\"required\":[\"accessProfiles\"]}}},{\"if\":{\"properties\":{\"code\":{\"const\":\"action.evidence-failed\"}}},\"then\":{\"properties\":{\"detail\":{\"const\":\"The declared Evidence dependency could not be accepted.\"},\"fieldPath\":{\"pattern\":\"^/evidence/[a-z][a-z0-9_-]{0,63}$\",\"type\":\"string\"},\"status\":{\"const\":503}}}},{\"if\":{\"properties\":{\"code\":{\"const\":\"action.handler-failed\"}}},\"then\":{\"properties\":{\"status\":{\"const\":500}}}},{\"if\":{\"anyOf\":[{\"required\":[\"atField\"]},{\"required\":[\"notAfterField\"]}]},\"then\":{\"properties\":{\"code\":{\"const\":\"request.invalid\"},\"status\":{\"const\":400}},\"required\":[\"atField\",\"notAfterField\"]}},{\"if\":{\"anyOf\":[{\"required\":[\"recordType\"]},{\"required\":[\"fieldId\"]},{\"required\":[\"constraintId\"]},{\"required\":[\"constraintKind\"]},{\"required\":[\"left\"]},{\"required\":[\"right\"]},{\"required\":[\"field\"]}]},\"then\":{\"oneOf\":[{\"not\":{\"anyOf\":[{\"required\":[\"constraintId\"]},{\"required\":[\"constraintKind\"]},{\"required\":[\"left\"]},{\"required\":[\"right\"]},{\"required\":[\"field\"]}]},\"required\":[\"fieldId\"]},{\"not\":{\"required\":[\"fieldId\"]},\"oneOf\":[{\"not\":{\"required\":[\"field\"]},\"properties\":{\"constraintKind\":{\"const\":\"compare\"}},\"required\":[\"left\",\"right\"]},{\"not\":{\"anyOf\":[{\"required\":[\"left\"]},{\"required\":[\"right\"]}]},\"properties\":{\"constraintKind\":{\"enum\":[\"int-range\",\"vocabulary\"]}},\"required\":[\"field\"]}],\"required\":[\"constraintId\",\"constraintKind\"]}],\"properties\":{\"code\":{\"const\":\"mutation.conflict\"},\"status\":{\"const\":409}},\"required\":[\"recordType\"]}}],\"anyOf\":[{\"properties\":{\"code\":{\"const\":\"access-profile.ambiguous\"},\"status\":{\"const\":400},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/access-profile/ambiguous\"}}},{\"properties\":{\"code\":{\"const\":\"action.evidence-failed\"},\"status\":{\"const\":503},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/action/evidence-failed\"}}},{\"properties\":{\"code\":{\"const\":\"action.guard-failed\"},\"status\":{\"const\":412},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/action/guard-failed\"}}},{\"properties\":{\"code\":{\"const\":\"action.handler-failed\"},\"status\":{\"const\":500},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/action/handler-failed\"}}},{\"properties\":{\"code\":{\"const\":\"action.refused\"},\"status\":{\"const\":422},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/action/refused\"}}},{\"properties\":{\"code\":{\"const\":\"attachment.content-type\"},\"status\":{\"const\":415},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/attachment/content-type\"}}},{\"properties\":{\"code\":{\"const\":\"attachment.digest-mismatch\"},\"status\":{\"const\":422},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/attachment/digest-mismatch\"}}},{\"properties\":{\"code\":{\"const\":\"attachment.limit-reached\"},\"status\":{\"const\":409},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/attachment/limit-reached\"}}},{\"properties\":{\"code\":{\"const\":\"attachment.required\"},\"status\":{\"const\":422},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/attachment/required\"}}},{\"properties\":{\"code\":{\"const\":\"attachment.slot-write-once\"},\"status\":{\"const\":409},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/attachment/slot-write-once\"}}},{\"properties\":{\"code\":{\"const\":\"attachment.too-large\"},\"status\":{\"const\":413},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/attachment/too-large\"}}},{\"properties\":{\"code\":{\"const\":\"attachment.verification-pending\"},\"status\":{\"const\":409},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/attachment/verification-pending\"}}},{\"properties\":{\"code\":{\"const\":\"attachment.verification-rejected\"},\"status\":{\"const\":422},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/attachment/verification-rejected\"}}},{\"properties\":{\"code\":{\"const\":\"authentication.refused\"},\"status\":{\"const\":401},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/authentication/refused\"}}},{\"properties\":{\"code\":{\"const\":\"idempotency.expired\"},\"status\":{\"const\":410},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/idempotency/expired\"}}},{\"properties\":{\"code\":{\"const\":\"idempotency.key-reused\"},\"status\":{\"const\":409},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/idempotency/key-reused\"}}},{\"properties\":{\"code\":{\"const\":\"ingestion.chunk-mismatch\"},\"status\":{\"const\":409},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/ingestion/chunk-mismatch\"}}},{\"properties\":{\"code\":{\"const\":\"ingestion.profile-mismatch\"},\"status\":{\"const\":403},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/ingestion/profile-mismatch\"}}},{\"properties\":{\"code\":{\"const\":\"ingestion.receipt-erased\"},\"status\":{\"const\":410},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/ingestion/receipt-erased\"}}},{\"properties\":{\"code\":{\"const\":\"ingestion.run-blocked\"},\"status\":{\"const\":409},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/ingestion/run-blocked\"}}},{\"properties\":{\"code\":{\"const\":\"ingestion.run-not-open\"},\"status\":{\"const\":409},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/ingestion/run-not-open\"}}},{\"properties\":{\"code\":{\"const\":\"lookup.unresolved\"},\"status\":{\"const\":404},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/lookup/unresolved\"}}},{\"properties\":{\"code\":{\"const\":\"mutation.conflict\"},\"status\":{\"const\":409},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/mutation/conflict\"}}},{\"properties\":{\"code\":{\"const\":\"precondition.failed\"},\"status\":{\"const\":412},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/precondition/failed\"}}},{\"properties\":{\"code\":{\"const\":\"precondition.required\"},\"status\":{\"const\":428},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/precondition/required\"}}},{\"properties\":{\"code\":{\"const\":\"profile.not-authorized\"},\"status\":{\"const\":403},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/profile/not-authorized\"}}},{\"properties\":{\"code\":{\"const\":\"proposal.form-limit-reached\"},\"status\":{\"const\":409},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/proposal/form-limit-reached\"}}},{\"properties\":{\"code\":{\"const\":\"proposal.form-undeclared\"},\"status\":{\"const\":404},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/proposal/form-undeclared\"}}},{\"properties\":{\"code\":{\"const\":\"proposal.message-limit-reached\"},\"status\":{\"const\":409},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/proposal/message-limit-reached\"}}},{\"properties\":{\"code\":{\"const\":\"proposal.rejected\"},\"status\":{\"const\":409},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/proposal/rejected\"}}},{\"properties\":{\"code\":{\"const\":\"proposal.review-result-mismatch\"},\"status\":{\"const\":412},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/proposal/review-result-mismatch\"}}},{\"properties\":{\"code\":{\"const\":\"proposal.subject-changed\"},\"status\":{\"const\":409},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/proposal/subject-changed\"}}},{\"properties\":{\"code\":{\"const\":\"proposal.subject-not-caller\"},\"status\":{\"const\":403},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/proposal/subject-not-caller\"}}},{\"properties\":{\"code\":{\"const\":\"proposal.submission-expired\"},\"status\":{\"const\":410},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/proposal/submission-expired\"}}},{\"properties\":{\"code\":{\"const\":\"query.cursor-invalid\"},\"status\":{\"const\":400},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/query/cursor-invalid\"}}},{\"properties\":{\"code\":{\"const\":\"query.filter-required\"},\"status\":{\"const\":400},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/query/filter-required\"}}},{\"properties\":{\"code\":{\"const\":\"query.invalid\"},\"status\":{\"const\":400},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/query/invalid\"}}},{\"properties\":{\"code\":{\"const\":\"request.access-reason-required\"},\"status\":{\"const\":400},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/request/access-reason-required\"}}},{\"properties\":{\"code\":{\"const\":\"request.invalid\"},\"status\":{\"const\":400},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/request/invalid\"}}},{\"properties\":{\"code\":{\"const\":\"request.timeout\"},\"status\":{\"const\":504},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/request/timeout\"}}},{\"properties\":{\"code\":{\"const\":\"resource.not-found\"},\"status\":{\"const\":404},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/resource/not-found\"}}},{\"properties\":{\"code\":{\"const\":\"runtime.field-encryption.unavailable\"},\"status\":{\"const\":503},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/runtime/field-encryption/unavailable\"}}},{\"properties\":{\"code\":{\"const\":\"service.unavailable\"},\"status\":{\"const\":503},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/service/unavailable\"}}},{\"properties\":{\"code\":{\"const\":\"source.unavailable\"},\"status\":{\"const\":503},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/source/unavailable\"}}},{\"properties\":{\"code\":{\"const\":\"statistical-dataset.domain-violation\"},\"status\":{\"const\":500},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/statistical-dataset/domain-violation\"}}},{\"properties\":{\"code\":{\"const\":\"statistical-dataset.release-refused\"},\"status\":{\"const\":422},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/statistical-dataset/release-refused\"}}},{\"properties\":{\"code\":{\"const\":\"statistical-dataset.version-conflict\"},\"status\":{\"const\":409},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/statistical-dataset/version-conflict\"}}},{\"properties\":{\"code\":{\"const\":\"statistical-dataset.version-withdrawn\"},\"status\":{\"const\":410},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/statistical-dataset/version-withdrawn\"}}},{\"properties\":{\"code\":{\"const\":\"unsupported.media-type\"},\"status\":{\"const\":415},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/unsupported/media-type\"}}},{\"properties\":{\"code\":{\"const\":\"write.outside-boundary\"},\"status\":{\"const\":403},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/write/outside-boundary\"}}}],\"properties\":{\"accessProfiles\":{\"items\":{\"maxLength\":128,\"minLength\":1,\"type\":\"string\"},\"minItems\":2,\"type\":\"array\",\"uniqueItems\":true},\"atField\":{\"maxLength\":128,\"minLength\":1,\"type\":\"string\"},\"code\":{\"enum\":[\"access-profile.ambiguous\",\"action.evidence-failed\",\"action.guard-failed\",\"action.handler-failed\",\"action.refused\",\"attachment.content-type\",\"attachment.digest-mismatch\",\"attachment.limit-reached\",\"attachment.required\",\"attachment.slot-write-once\",\"attachment.too-large\",\"attachment.verification-pending\",\"attachment.verification-rejected\",\"authentication.refused\",\"idempotency.expired\",\"idempotency.key-reused\",\"ingestion.chunk-mismatch\",\"ingestion.profile-mismatch\",\"ingestion.receipt-erased\",\"ingestion.run-blocked\",\"ingestion.run-not-open\",\"lookup.unresolved\",\"mutation.conflict\",\"precondition.failed\",\"precondition.required\",\"profile.not-authorized\",\"proposal.form-limit-reached\",\"proposal.form-undeclared\",\"proposal.message-limit-reached\",\"proposal.rejected\",\"proposal.review-result-mismatch\",\"proposal.subject-changed\",\"proposal.subject-not-caller\",\"proposal.submission-expired\",\"query.cursor-invalid\",\"query.filter-required\",\"query.invalid\",\"request.access-reason-required\",\"request.invalid\",\"request.timeout\",\"resource.not-found\",\"runtime.field-encryption.unavailable\",\"service.unavailable\",\"source.unavailable\",\"statistical-dataset.domain-violation\",\"statistical-dataset.release-refused\",\"statistical-dataset.version-conflict\",\"statistical-dataset.version-withdrawn\",\"unsupported.media-type\",\"write.outside-boundary\"],\"type\":\"string\"},\"constraintId\":{\"maxLength\":128,\"minLength\":1,\"type\":\"string\"},\"constraintKind\":{\"enum\":[\"compare\",\"int-range\",\"vocabulary\"],\"type\":\"string\"},\"detail\":{\"maxLength\":256,\"type\":\"string\"},\"failedCheck\":{\"type\":\"string\"},\"field\":{\"maxLength\":128,\"minLength\":1,\"type\":\"string\"},\"fieldId\":{\"maxLength\":128,\"minLength\":1,\"type\":\"string\"},\"fieldPath\":{\"maxLength\":256,\"type\":\"string\"},\"guardReason\":{\"pattern\":\"^[a-z][a-z0-9_-]{0,63}$\",\"type\":\"string\"},\"left\":{\"maxLength\":128,\"minLength\":1,\"type\":\"string\"},\"notAfterField\":{\"maxLength\":128,\"minLength\":1,\"type\":\"string\"},\"reasonCode\":{\"enum\":[\"computation-error\",\"source-data-error\",\"disclosure-risk\"],\"type\":\"string\"},\"recordType\":{\"maxLength\":128,\"minLength\":1,\"type\":\"string\"},\"refusalCode\":{\"maxLength\":128,\"minLength\":1,\"type\":\"string\"},\"requiredFilters\":{\"items\":{\"items\":{\"maxLength\":64,\"minLength\":1,\"type\":\"string\"},\"maxItems\":32,\"minItems\":1,\"type\":\"array\",\"uniqueItems\":true},\"maxItems\":8,\"minItems\":1,\"type\":\"array\"},\"right\":{\"maxLength\":128,\"minLength\":1,\"type\":\"string\"},\"status\":{\"maximum\":599,\"minimum\":400,\"type\":\"integer\"},\"title\":{\"maxLength\":128,\"type\":\"string\"},\"traceId\":{\"maxLength\":32,\"minLength\":32,\"pattern\":\"^[0-9a-f]{32}$\",\"type\":\"string\"},\"type\":{\"maxLength\":256,\"type\":\"string\"}},\"required\":[\"type\",\"title\",\"status\",\"detail\",\"code\",\"traceId\"],\"type\":\"object\"}")], ["/components/schemas/ReviewCompletion", JSON.parse("{\"additionalProperties\":false,\"properties\":{\"completedAt\":{\"type\":\"string\"},\"eventId\":{\"type\":\"string\"},\"requestId\":{\"type\":\"string\"},\"resultId\":{\"type\":\"string\"},\"type\":{\"const\":\"review.completed\"}},\"required\":[\"type\",\"eventId\",\"requestId\",\"resultId\",\"completedAt\"],\"type\":\"object\"}")], ["/components/schemas/action-correct-address-invoke-input", JSON.parse("{\"additionalProperties\":false,\"properties\":{\"input\":{\"additionalProperties\":false,\"properties\":{\"addressLine\":{\"maxLength\":240,\"minLength\":1,\"type\":\"string\"},\"city\":{\"maxLength\":120,\"minLength\":1,\"type\":\"string\"},\"facilityId\":{\"type\":\"string\"},\"postalCode\":{\"maxLength\":24,\"minLength\":1,\"type\":\"string\"}},\"required\":[],\"type\":\"object\"}},\"required\":[\"input\"],\"type\":\"object\"}")], - ["/components/schemas/action-correct-address-invoke-response", JSON.parse("{\"additionalProperties\":false,\"properties\":{\"actionId\":{\"type\":\"string\"},\"actionRevision\":{\"type\":\"string\"},\"application\":{\"additionalProperties\":false,\"properties\":{\"applicationId\":{\"type\":\"string\"},\"effectDigest\":{\"pattern\":\"^sha256:[0-9a-f]{64}$\",\"type\":\"string\"},\"resultLinks\":{\"items\":{\"additionalProperties\":false,\"properties\":{\"recordId\":{\"type\":\"string\"},\"recordType\":{\"type\":\"string\"},\"revision\":{\"minimum\":1,\"type\":\"integer\"}},\"required\":[\"recordType\",\"recordId\",\"revision\"],\"type\":\"object\"},\"maxItems\":16,\"type\":\"array\"},\"submissionVersion\":{\"minimum\":1,\"type\":\"integer\"}},\"required\":[\"applicationId\",\"submissionVersion\",\"effectDigest\",\"resultLinks\"],\"type\":\"object\"},\"applicationStatus\":{\"additionalProperties\":false,\"properties\":{\"automaticRetry\":{\"additionalProperties\":false,\"properties\":{\"attempts\":{\"maximum\":1000,\"minimum\":0,\"type\":\"integer\"},\"maximumAttempts\":{\"maximum\":1000,\"minimum\":1,\"type\":\"integer\"},\"scheduled\":{\"type\":\"boolean\"}},\"required\":[\"scheduled\",\"attempts\",\"maximumAttempts\"],\"type\":\"object\"},\"mode\":{\"enum\":[\"automatic\",\"manual\"]},\"reason\":{\"enum\":[\"package-changed\",\"dependency-outage\",\"lease-expired\",\"application-refused\",\"attempts-exhausted\"]},\"recovery\":{\"enum\":[\"retry\",\"rebase\",\"revise\",\"correct-input\"]},\"state\":{\"enum\":[\"awaiting-review\",\"pending\",\"applying\",\"blocked\",\"applied\",\"cancelled\",\"rejected\"]}},\"required\":[\"state\",\"mode\"],\"type\":\"object\"},\"asks\":{\"items\":{\"additionalProperties\":false,\"properties\":{\"answer\":{\"additionalProperties\":false,\"properties\":{\"additions\":{\"items\":{\"type\":\"string\"},\"maxItems\":32,\"type\":\"array\",\"uniqueItems\":true},\"answeredAt\":{\"type\":\"string\"},\"text\":{\"maxLength\":2000,\"minLength\":1,\"type\":\"string\"}},\"required\":[\"additions\",\"answeredAt\"],\"type\":\"object\"},\"askedAt\":{\"type\":\"string\"},\"dueAt\":{\"type\":\"string\"},\"id\":{\"type\":\"string\"},\"links\":{\"additionalProperties\":false,\"properties\":{\"answer\":{\"additionalProperties\":false,\"properties\":{\"accessProfile\":{\"type\":\"string\"},\"availability\":{\"additionalProperties\":false,\"if\":{\"properties\":{\"available\":{\"const\":false}}},\"properties\":{\"available\":{\"type\":\"boolean\"},\"observedRevision\":{\"minimum\":1,\"type\":\"integer\"},\"reason\":{\"enum\":[\"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\":{\"enum\":[\"refresh\",\"revise\",\"retry\",\"rebase\",\"correct-input\",\"receipt-only\"]}},\"required\":[\"available\",\"observedRevision\"],\"then\":{\"required\":[\"reason\",\"recovery\"]},\"type\":\"object\"},\"ifMatch\":{\"type\":\"string\"},\"method\":{\"const\":\"POST\"},\"operation\":{\"const\":\"answer\"},\"path\":{\"type\":\"string\"}},\"required\":[\"method\",\"path\",\"accessProfile\",\"operation\",\"ifMatch\",\"availability\"],\"type\":\"object\"}},\"type\":\"object\"},\"state\":{\"enum\":[\"open\",\"answered\",\"expired\",\"closed\"]},\"text\":{\"maxLength\":2000,\"minLength\":1,\"type\":\"string\"},\"wants\":{\"items\":{\"additionalProperties\":false,\"properties\":{\"kind\":{\"enum\":[\"answer\",\"document\"]}},\"required\":[\"kind\"],\"type\":\"object\"},\"maxItems\":8,\"type\":\"array\",\"uniqueItems\":true}},\"required\":[\"id\",\"text\",\"wants\",\"askedAt\",\"state\",\"links\"],\"type\":\"object\"},\"maxItems\":50,\"type\":\"array\"},\"attachments\":{\"additionalProperties\":{\"additionalProperties\":false,\"properties\":{\"classification\":{\"enum\":[\"public\",\"internal\",\"restricted\"]},\"contentTypes\":{\"items\":{\"type\":\"string\"},\"maxItems\":16,\"minItems\":1,\"type\":\"array\",\"uniqueItems\":true},\"id\":{\"type\":\"string\"},\"links\":{\"additionalProperties\":{\"additionalProperties\":false,\"properties\":{\"accessProfile\":{\"type\":\"string\"},\"availability\":{\"additionalProperties\":false,\"if\":{\"properties\":{\"available\":{\"const\":false}}},\"properties\":{\"available\":{\"type\":\"boolean\"},\"observedRevision\":{\"minimum\":1,\"type\":\"integer\"},\"reason\":{\"enum\":[\"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\":{\"enum\":[\"refresh\",\"revise\",\"retry\",\"rebase\",\"correct-input\",\"receipt-only\"]}},\"required\":[\"available\",\"observedRevision\"],\"then\":{\"required\":[\"reason\",\"recovery\"]},\"type\":\"object\"},\"ifMatch\":{\"type\":\"string\"},\"method\":{\"enum\":[\"GET\",\"PATCH\",\"DELETE\"]},\"operation\":{\"enum\":[\"download\",\"upload\",\"remove\"]},\"path\":{\"type\":\"string\"}},\"required\":[\"method\",\"path\",\"accessProfile\",\"operation\"],\"type\":\"object\"},\"type\":\"object\"},\"maximumBytes\":{\"maximum\":16777216,\"minimum\":1,\"type\":\"integer\"},\"required\":{\"type\":\"boolean\"},\"value\":{\"additionalProperties\":false,\"properties\":{\"byteSize\":{\"minimum\":1,\"type\":\"integer\"},\"contentType\":{\"type\":\"string\"},\"sha256\":{\"pattern\":\"^[a-f0-9]{64}$\",\"type\":\"string\"},\"submissionVersion\":{\"minimum\":0,\"type\":\"integer\"},\"uploadedAt\":{\"type\":\"string\"},\"verificationStatus\":{\"enum\":[\"notRequired\",\"pending\",\"approved\",\"rejected\"]}},\"required\":[\"submissionVersion\",\"sha256\",\"contentType\",\"byteSize\",\"verificationStatus\"],\"type\":\"object\"}},\"required\":[\"id\",\"required\",\"maximumBytes\",\"contentTypes\",\"classification\",\"links\"],\"type\":\"object\"},\"maxProperties\":8,\"type\":\"object\"},\"blockedReason\":{\"enum\":[\"package-changed\"]},\"createdAt\":{\"type\":\"string\"},\"decision\":{\"additionalProperties\":false,\"properties\":{\"decidedAt\":{\"type\":\"string\"},\"publicReason\":{\"minLength\":1,\"pattern\":\"^[^\\\\u0000-\\\\u001F\\\\u007F-\\\\u009F]*[^\\\\u0000-\\\\u0020\\\\u007F-\\\\u00A0\\\\u1680\\\\u2000-\\\\u200A\\\\u2028\\\\u2029\\\\u202F\\\\u205F\\\\u3000][^\\\\u0000-\\\\u001F\\\\u007F-\\\\u009F]*$\",\"type\":\"string\"},\"status\":{\"enum\":[\"approved\",\"rejected\",\"changes-requested\",\"answered\"]}},\"required\":[\"status\",\"decidedAt\"],\"type\":\"object\"},\"effectDigest\":{\"type\":\"string\"},\"handoffRefusal\":{\"additionalProperties\":false,\"properties\":{\"code\":{\"enum\":[\"review.initiator-required\",\"review.initiator-excluded\",\"review.policy-mismatch\",\"review.refused\"]}},\"required\":[\"code\"],\"type\":\"object\"},\"id\":{\"type\":\"string\"},\"input\":{\"type\":\"object\"},\"links\":{\"additionalProperties\":{\"additionalProperties\":false,\"properties\":{\"accessProfile\":{\"type\":\"string\"},\"availability\":{\"additionalProperties\":false,\"if\":{\"properties\":{\"available\":{\"const\":false}}},\"properties\":{\"available\":{\"type\":\"boolean\"},\"observedRevision\":{\"minimum\":1,\"type\":\"integer\"},\"reason\":{\"enum\":[\"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\":{\"enum\":[\"refresh\",\"revise\",\"retry\",\"rebase\",\"correct-input\",\"receipt-only\"]}},\"required\":[\"available\",\"observedRevision\"],\"then\":{\"required\":[\"reason\",\"recovery\"]},\"type\":\"object\"},\"ifMatch\":{\"type\":\"string\"},\"method\":{\"enum\":[\"GET\",\"POST\"]},\"operation\":{\"type\":\"string\"},\"path\":{\"type\":\"string\"}},\"required\":[\"method\",\"path\",\"accessProfile\",\"operation\"],\"type\":\"object\"},\"type\":\"object\"},\"revision\":{\"minimum\":1,\"type\":\"integer\"},\"state\":{\"enum\":[\"draft\",\"submitted\",\"applied\",\"cancelled\",\"rejected\"]},\"status\":{\"enum\":[\"draft\",\"awaiting-party\",\"in-review\",\"approved\",\"processing\",\"applied\",\"rejected\",\"cancelled\"]},\"submissionVersion\":{\"minimum\":0,\"type\":\"integer\"},\"title\":{\"maxLength\":1024,\"type\":\"string\"},\"turn\":{\"enum\":[\"party\",\"official\",\"nobody\"]}},\"required\":[\"id\",\"actionId\",\"actionRevision\",\"submissionVersion\",\"revision\",\"state\",\"turn\",\"links\"],\"type\":\"object\"}")], + ["/components/schemas/action-correct-address-invoke-response", JSON.parse("{\"additionalProperties\":false,\"properties\":{\"actionId\":{\"type\":\"string\"},\"actionRevision\":{\"type\":\"string\"},\"application\":{\"additionalProperties\":false,\"properties\":{\"applicationId\":{\"type\":\"string\"},\"effectDigest\":{\"pattern\":\"^sha256:[0-9a-f]{64}$\",\"type\":\"string\"},\"resultLinks\":{\"items\":{\"additionalProperties\":false,\"properties\":{\"recordId\":{\"type\":\"string\"},\"recordType\":{\"type\":\"string\"},\"revision\":{\"minimum\":1,\"type\":\"integer\"}},\"required\":[\"recordType\",\"recordId\",\"revision\"],\"type\":\"object\"},\"maxItems\":16,\"type\":\"array\"},\"submissionVersion\":{\"minimum\":1,\"type\":\"integer\"}},\"required\":[\"applicationId\",\"submissionVersion\",\"effectDigest\",\"resultLinks\"],\"type\":\"object\"},\"applicationStatus\":{\"additionalProperties\":false,\"properties\":{\"automaticRetry\":{\"additionalProperties\":false,\"properties\":{\"attempts\":{\"maximum\":1000,\"minimum\":0,\"type\":\"integer\"},\"maximumAttempts\":{\"maximum\":1000,\"minimum\":1,\"type\":\"integer\"},\"scheduled\":{\"type\":\"boolean\"}},\"required\":[\"scheduled\",\"attempts\",\"maximumAttempts\"],\"type\":\"object\"},\"mode\":{\"enum\":[\"automatic\",\"manual\"]},\"reason\":{\"enum\":[\"package-changed\",\"dependency-outage\",\"lease-expired\",\"application-refused\",\"attempts-exhausted\"]},\"recovery\":{\"enum\":[\"retry\",\"rebase\",\"revise\",\"correct-input\"]},\"state\":{\"enum\":[\"awaiting-review\",\"pending\",\"applying\",\"blocked\",\"applied\",\"cancelled\",\"rejected\"]}},\"required\":[\"state\",\"mode\"],\"type\":\"object\"},\"asks\":{\"items\":{\"additionalProperties\":false,\"properties\":{\"answer\":{\"additionalProperties\":false,\"properties\":{\"additions\":{\"items\":{\"type\":\"string\"},\"maxItems\":32,\"type\":\"array\",\"uniqueItems\":true},\"answeredAt\":{\"type\":\"string\"},\"formEntries\":{\"items\":{\"type\":\"string\"},\"maxItems\":32,\"type\":\"array\",\"uniqueItems\":true},\"text\":{\"maxLength\":2000,\"minLength\":1,\"type\":\"string\"}},\"required\":[\"additions\",\"answeredAt\"],\"type\":\"object\"},\"askedAt\":{\"type\":\"string\"},\"dueAt\":{\"type\":\"string\"},\"id\":{\"type\":\"string\"},\"links\":{\"additionalProperties\":false,\"properties\":{\"answer\":{\"additionalProperties\":false,\"properties\":{\"accessProfile\":{\"type\":\"string\"},\"availability\":{\"additionalProperties\":false,\"if\":{\"properties\":{\"available\":{\"const\":false}}},\"properties\":{\"available\":{\"type\":\"boolean\"},\"observedRevision\":{\"minimum\":1,\"type\":\"integer\"},\"reason\":{\"enum\":[\"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\":{\"enum\":[\"refresh\",\"revise\",\"retry\",\"rebase\",\"correct-input\",\"receipt-only\"]}},\"required\":[\"available\",\"observedRevision\"],\"then\":{\"required\":[\"reason\",\"recovery\"]},\"type\":\"object\"},\"ifMatch\":{\"type\":\"string\"},\"method\":{\"const\":\"POST\"},\"operation\":{\"const\":\"answer\"},\"path\":{\"type\":\"string\"}},\"required\":[\"method\",\"path\",\"accessProfile\",\"operation\",\"ifMatch\",\"availability\"],\"type\":\"object\"}},\"type\":\"object\"},\"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\",\"links\"],\"type\":\"object\"},\"maxItems\":50,\"type\":\"array\"},\"attachments\":{\"additionalProperties\":{\"additionalProperties\":false,\"properties\":{\"classification\":{\"enum\":[\"public\",\"internal\",\"restricted\"]},\"contentTypes\":{\"items\":{\"type\":\"string\"},\"maxItems\":16,\"minItems\":1,\"type\":\"array\",\"uniqueItems\":true},\"id\":{\"type\":\"string\"},\"links\":{\"additionalProperties\":{\"additionalProperties\":false,\"properties\":{\"accessProfile\":{\"type\":\"string\"},\"availability\":{\"additionalProperties\":false,\"if\":{\"properties\":{\"available\":{\"const\":false}}},\"properties\":{\"available\":{\"type\":\"boolean\"},\"observedRevision\":{\"minimum\":1,\"type\":\"integer\"},\"reason\":{\"enum\":[\"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\":{\"enum\":[\"refresh\",\"revise\",\"retry\",\"rebase\",\"correct-input\",\"receipt-only\"]}},\"required\":[\"available\",\"observedRevision\"],\"then\":{\"required\":[\"reason\",\"recovery\"]},\"type\":\"object\"},\"ifMatch\":{\"type\":\"string\"},\"method\":{\"enum\":[\"GET\",\"PATCH\",\"DELETE\"]},\"operation\":{\"enum\":[\"download\",\"upload\",\"remove\"]},\"path\":{\"type\":\"string\"}},\"required\":[\"method\",\"path\",\"accessProfile\",\"operation\"],\"type\":\"object\"},\"type\":\"object\"},\"maximumBytes\":{\"maximum\":16777216,\"minimum\":1,\"type\":\"integer\"},\"required\":{\"type\":\"boolean\"},\"value\":{\"additionalProperties\":false,\"properties\":{\"byteSize\":{\"minimum\":1,\"type\":\"integer\"},\"contentType\":{\"type\":\"string\"},\"sha256\":{\"pattern\":\"^[a-f0-9]{64}$\",\"type\":\"string\"},\"submissionVersion\":{\"minimum\":0,\"type\":\"integer\"},\"uploadedAt\":{\"type\":\"string\"},\"verificationStatus\":{\"enum\":[\"notRequired\",\"pending\",\"approved\",\"rejected\"]}},\"required\":[\"submissionVersion\",\"sha256\",\"contentType\",\"byteSize\",\"verificationStatus\"],\"type\":\"object\"}},\"required\":[\"id\",\"required\",\"maximumBytes\",\"contentTypes\",\"classification\",\"links\"],\"type\":\"object\"},\"maxProperties\":8,\"type\":\"object\"},\"blockedReason\":{\"enum\":[\"package-changed\"]},\"createdAt\":{\"type\":\"string\"},\"decision\":{\"additionalProperties\":false,\"properties\":{\"decidedAt\":{\"type\":\"string\"},\"publicReason\":{\"minLength\":1,\"pattern\":\"^[^\\\\u0000-\\\\u001F\\\\u007F-\\\\u009F]*[^\\\\u0000-\\\\u0020\\\\u007F-\\\\u00A0\\\\u1680\\\\u2000-\\\\u200A\\\\u2028\\\\u2029\\\\u202F\\\\u205F\\\\u3000][^\\\\u0000-\\\\u001F\\\\u007F-\\\\u009F]*$\",\"type\":\"string\"},\"status\":{\"enum\":[\"approved\",\"rejected\",\"changes-requested\",\"answered\"]}},\"required\":[\"status\",\"decidedAt\"],\"type\":\"object\"},\"effectDigest\":{\"type\":\"string\"},\"handoffRefusal\":{\"additionalProperties\":false,\"properties\":{\"code\":{\"enum\":[\"review.initiator-required\",\"review.initiator-excluded\",\"review.policy-mismatch\",\"review.refused\"]}},\"required\":[\"code\"],\"type\":\"object\"},\"id\":{\"type\":\"string\"},\"input\":{\"type\":\"object\"},\"links\":{\"additionalProperties\":{\"additionalProperties\":false,\"properties\":{\"accessProfile\":{\"type\":\"string\"},\"availability\":{\"additionalProperties\":false,\"if\":{\"properties\":{\"available\":{\"const\":false}}},\"properties\":{\"available\":{\"type\":\"boolean\"},\"observedRevision\":{\"minimum\":1,\"type\":\"integer\"},\"reason\":{\"enum\":[\"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\":{\"enum\":[\"refresh\",\"revise\",\"retry\",\"rebase\",\"correct-input\",\"receipt-only\"]}},\"required\":[\"available\",\"observedRevision\"],\"then\":{\"required\":[\"reason\",\"recovery\"]},\"type\":\"object\"},\"ifMatch\":{\"type\":\"string\"},\"method\":{\"enum\":[\"GET\",\"POST\"]},\"operation\":{\"type\":\"string\"},\"path\":{\"type\":\"string\"}},\"required\":[\"method\",\"path\",\"accessProfile\",\"operation\"],\"type\":\"object\"},\"type\":\"object\"},\"partyRole\":{\"enum\":[\"owner\",\"subject\"]},\"revision\":{\"minimum\":1,\"type\":\"integer\"},\"state\":{\"enum\":[\"draft\",\"submitted\",\"applied\",\"cancelled\",\"rejected\"]},\"status\":{\"enum\":[\"draft\",\"awaiting-party\",\"in-review\",\"approved\",\"processing\",\"applied\",\"rejected\",\"cancelled\"]},\"submissionVersion\":{\"minimum\":0,\"type\":\"integer\"},\"title\":{\"maxLength\":1024,\"type\":\"string\"},\"turn\":{\"enum\":[\"party\",\"official\",\"nobody\"]}},\"required\":[\"id\",\"actionId\",\"actionRevision\",\"submissionVersion\",\"revision\",\"state\",\"turn\",\"links\"],\"type\":\"object\"}")], ["/components/schemas/action-deactivate-facility-invoke-input", JSON.parse("{\"additionalProperties\":false,\"properties\":{\"input\":{\"additionalProperties\":false,\"properties\":{\"facilityId\":{\"type\":\"string\"}},\"required\":[],\"type\":\"object\"}},\"required\":[\"input\"],\"type\":\"object\"}")], - ["/components/schemas/action-deactivate-facility-invoke-response", JSON.parse("{\"additionalProperties\":false,\"properties\":{\"actionId\":{\"type\":\"string\"},\"actionRevision\":{\"type\":\"string\"},\"application\":{\"additionalProperties\":false,\"properties\":{\"applicationId\":{\"type\":\"string\"},\"effectDigest\":{\"pattern\":\"^sha256:[0-9a-f]{64}$\",\"type\":\"string\"},\"resultLinks\":{\"items\":{\"additionalProperties\":false,\"properties\":{\"recordId\":{\"type\":\"string\"},\"recordType\":{\"type\":\"string\"},\"revision\":{\"minimum\":1,\"type\":\"integer\"}},\"required\":[\"recordType\",\"recordId\",\"revision\"],\"type\":\"object\"},\"maxItems\":16,\"type\":\"array\"},\"submissionVersion\":{\"minimum\":1,\"type\":\"integer\"}},\"required\":[\"applicationId\",\"submissionVersion\",\"effectDigest\",\"resultLinks\"],\"type\":\"object\"},\"applicationStatus\":{\"additionalProperties\":false,\"properties\":{\"automaticRetry\":{\"additionalProperties\":false,\"properties\":{\"attempts\":{\"maximum\":1000,\"minimum\":0,\"type\":\"integer\"},\"maximumAttempts\":{\"maximum\":1000,\"minimum\":1,\"type\":\"integer\"},\"scheduled\":{\"type\":\"boolean\"}},\"required\":[\"scheduled\",\"attempts\",\"maximumAttempts\"],\"type\":\"object\"},\"mode\":{\"enum\":[\"automatic\",\"manual\"]},\"reason\":{\"enum\":[\"package-changed\",\"dependency-outage\",\"lease-expired\",\"application-refused\",\"attempts-exhausted\"]},\"recovery\":{\"enum\":[\"retry\",\"rebase\",\"revise\",\"correct-input\"]},\"state\":{\"enum\":[\"awaiting-review\",\"pending\",\"applying\",\"blocked\",\"applied\",\"cancelled\",\"rejected\"]}},\"required\":[\"state\",\"mode\"],\"type\":\"object\"},\"asks\":{\"items\":{\"additionalProperties\":false,\"properties\":{\"answer\":{\"additionalProperties\":false,\"properties\":{\"additions\":{\"items\":{\"type\":\"string\"},\"maxItems\":32,\"type\":\"array\",\"uniqueItems\":true},\"answeredAt\":{\"type\":\"string\"},\"text\":{\"maxLength\":2000,\"minLength\":1,\"type\":\"string\"}},\"required\":[\"additions\",\"answeredAt\"],\"type\":\"object\"},\"askedAt\":{\"type\":\"string\"},\"dueAt\":{\"type\":\"string\"},\"id\":{\"type\":\"string\"},\"links\":{\"additionalProperties\":false,\"properties\":{\"answer\":{\"additionalProperties\":false,\"properties\":{\"accessProfile\":{\"type\":\"string\"},\"availability\":{\"additionalProperties\":false,\"if\":{\"properties\":{\"available\":{\"const\":false}}},\"properties\":{\"available\":{\"type\":\"boolean\"},\"observedRevision\":{\"minimum\":1,\"type\":\"integer\"},\"reason\":{\"enum\":[\"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\":{\"enum\":[\"refresh\",\"revise\",\"retry\",\"rebase\",\"correct-input\",\"receipt-only\"]}},\"required\":[\"available\",\"observedRevision\"],\"then\":{\"required\":[\"reason\",\"recovery\"]},\"type\":\"object\"},\"ifMatch\":{\"type\":\"string\"},\"method\":{\"const\":\"POST\"},\"operation\":{\"const\":\"answer\"},\"path\":{\"type\":\"string\"}},\"required\":[\"method\",\"path\",\"accessProfile\",\"operation\",\"ifMatch\",\"availability\"],\"type\":\"object\"}},\"type\":\"object\"},\"state\":{\"enum\":[\"open\",\"answered\",\"expired\",\"closed\"]},\"text\":{\"maxLength\":2000,\"minLength\":1,\"type\":\"string\"},\"wants\":{\"items\":{\"additionalProperties\":false,\"properties\":{\"kind\":{\"enum\":[\"answer\",\"document\"]}},\"required\":[\"kind\"],\"type\":\"object\"},\"maxItems\":8,\"type\":\"array\",\"uniqueItems\":true}},\"required\":[\"id\",\"text\",\"wants\",\"askedAt\",\"state\",\"links\"],\"type\":\"object\"},\"maxItems\":50,\"type\":\"array\"},\"attachments\":{\"additionalProperties\":{\"additionalProperties\":false,\"properties\":{\"classification\":{\"enum\":[\"public\",\"internal\",\"restricted\"]},\"contentTypes\":{\"items\":{\"type\":\"string\"},\"maxItems\":16,\"minItems\":1,\"type\":\"array\",\"uniqueItems\":true},\"id\":{\"type\":\"string\"},\"links\":{\"additionalProperties\":{\"additionalProperties\":false,\"properties\":{\"accessProfile\":{\"type\":\"string\"},\"availability\":{\"additionalProperties\":false,\"if\":{\"properties\":{\"available\":{\"const\":false}}},\"properties\":{\"available\":{\"type\":\"boolean\"},\"observedRevision\":{\"minimum\":1,\"type\":\"integer\"},\"reason\":{\"enum\":[\"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\":{\"enum\":[\"refresh\",\"revise\",\"retry\",\"rebase\",\"correct-input\",\"receipt-only\"]}},\"required\":[\"available\",\"observedRevision\"],\"then\":{\"required\":[\"reason\",\"recovery\"]},\"type\":\"object\"},\"ifMatch\":{\"type\":\"string\"},\"method\":{\"enum\":[\"GET\",\"PATCH\",\"DELETE\"]},\"operation\":{\"enum\":[\"download\",\"upload\",\"remove\"]},\"path\":{\"type\":\"string\"}},\"required\":[\"method\",\"path\",\"accessProfile\",\"operation\"],\"type\":\"object\"},\"type\":\"object\"},\"maximumBytes\":{\"maximum\":16777216,\"minimum\":1,\"type\":\"integer\"},\"required\":{\"type\":\"boolean\"},\"value\":{\"additionalProperties\":false,\"properties\":{\"byteSize\":{\"minimum\":1,\"type\":\"integer\"},\"contentType\":{\"type\":\"string\"},\"sha256\":{\"pattern\":\"^[a-f0-9]{64}$\",\"type\":\"string\"},\"submissionVersion\":{\"minimum\":0,\"type\":\"integer\"},\"uploadedAt\":{\"type\":\"string\"},\"verificationStatus\":{\"enum\":[\"notRequired\",\"pending\",\"approved\",\"rejected\"]}},\"required\":[\"submissionVersion\",\"sha256\",\"contentType\",\"byteSize\",\"verificationStatus\"],\"type\":\"object\"}},\"required\":[\"id\",\"required\",\"maximumBytes\",\"contentTypes\",\"classification\",\"links\"],\"type\":\"object\"},\"maxProperties\":8,\"type\":\"object\"},\"blockedReason\":{\"enum\":[\"package-changed\"]},\"createdAt\":{\"type\":\"string\"},\"decision\":{\"additionalProperties\":false,\"properties\":{\"decidedAt\":{\"type\":\"string\"},\"publicReason\":{\"minLength\":1,\"pattern\":\"^[^\\\\u0000-\\\\u001F\\\\u007F-\\\\u009F]*[^\\\\u0000-\\\\u0020\\\\u007F-\\\\u00A0\\\\u1680\\\\u2000-\\\\u200A\\\\u2028\\\\u2029\\\\u202F\\\\u205F\\\\u3000][^\\\\u0000-\\\\u001F\\\\u007F-\\\\u009F]*$\",\"type\":\"string\"},\"status\":{\"enum\":[\"approved\",\"rejected\",\"changes-requested\",\"answered\"]}},\"required\":[\"status\",\"decidedAt\"],\"type\":\"object\"},\"effectDigest\":{\"type\":\"string\"},\"handoffRefusal\":{\"additionalProperties\":false,\"properties\":{\"code\":{\"enum\":[\"review.initiator-required\",\"review.initiator-excluded\",\"review.policy-mismatch\",\"review.refused\"]}},\"required\":[\"code\"],\"type\":\"object\"},\"id\":{\"type\":\"string\"},\"input\":{\"type\":\"object\"},\"links\":{\"additionalProperties\":{\"additionalProperties\":false,\"properties\":{\"accessProfile\":{\"type\":\"string\"},\"availability\":{\"additionalProperties\":false,\"if\":{\"properties\":{\"available\":{\"const\":false}}},\"properties\":{\"available\":{\"type\":\"boolean\"},\"observedRevision\":{\"minimum\":1,\"type\":\"integer\"},\"reason\":{\"enum\":[\"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\":{\"enum\":[\"refresh\",\"revise\",\"retry\",\"rebase\",\"correct-input\",\"receipt-only\"]}},\"required\":[\"available\",\"observedRevision\"],\"then\":{\"required\":[\"reason\",\"recovery\"]},\"type\":\"object\"},\"ifMatch\":{\"type\":\"string\"},\"method\":{\"enum\":[\"GET\",\"POST\"]},\"operation\":{\"type\":\"string\"},\"path\":{\"type\":\"string\"}},\"required\":[\"method\",\"path\",\"accessProfile\",\"operation\"],\"type\":\"object\"},\"type\":\"object\"},\"revision\":{\"minimum\":1,\"type\":\"integer\"},\"state\":{\"enum\":[\"draft\",\"submitted\",\"applied\",\"cancelled\",\"rejected\"]},\"status\":{\"enum\":[\"draft\",\"awaiting-party\",\"in-review\",\"approved\",\"processing\",\"applied\",\"rejected\",\"cancelled\"]},\"submissionVersion\":{\"minimum\":0,\"type\":\"integer\"},\"title\":{\"maxLength\":1024,\"type\":\"string\"},\"turn\":{\"enum\":[\"party\",\"official\",\"nobody\"]}},\"required\":[\"id\",\"actionId\",\"actionRevision\",\"submissionVersion\",\"revision\",\"state\",\"turn\",\"links\"],\"type\":\"object\"}")], + ["/components/schemas/action-deactivate-facility-invoke-response", JSON.parse("{\"additionalProperties\":false,\"properties\":{\"actionId\":{\"type\":\"string\"},\"actionRevision\":{\"type\":\"string\"},\"application\":{\"additionalProperties\":false,\"properties\":{\"applicationId\":{\"type\":\"string\"},\"effectDigest\":{\"pattern\":\"^sha256:[0-9a-f]{64}$\",\"type\":\"string\"},\"resultLinks\":{\"items\":{\"additionalProperties\":false,\"properties\":{\"recordId\":{\"type\":\"string\"},\"recordType\":{\"type\":\"string\"},\"revision\":{\"minimum\":1,\"type\":\"integer\"}},\"required\":[\"recordType\",\"recordId\",\"revision\"],\"type\":\"object\"},\"maxItems\":16,\"type\":\"array\"},\"submissionVersion\":{\"minimum\":1,\"type\":\"integer\"}},\"required\":[\"applicationId\",\"submissionVersion\",\"effectDigest\",\"resultLinks\"],\"type\":\"object\"},\"applicationStatus\":{\"additionalProperties\":false,\"properties\":{\"automaticRetry\":{\"additionalProperties\":false,\"properties\":{\"attempts\":{\"maximum\":1000,\"minimum\":0,\"type\":\"integer\"},\"maximumAttempts\":{\"maximum\":1000,\"minimum\":1,\"type\":\"integer\"},\"scheduled\":{\"type\":\"boolean\"}},\"required\":[\"scheduled\",\"attempts\",\"maximumAttempts\"],\"type\":\"object\"},\"mode\":{\"enum\":[\"automatic\",\"manual\"]},\"reason\":{\"enum\":[\"package-changed\",\"dependency-outage\",\"lease-expired\",\"application-refused\",\"attempts-exhausted\"]},\"recovery\":{\"enum\":[\"retry\",\"rebase\",\"revise\",\"correct-input\"]},\"state\":{\"enum\":[\"awaiting-review\",\"pending\",\"applying\",\"blocked\",\"applied\",\"cancelled\",\"rejected\"]}},\"required\":[\"state\",\"mode\"],\"type\":\"object\"},\"asks\":{\"items\":{\"additionalProperties\":false,\"properties\":{\"answer\":{\"additionalProperties\":false,\"properties\":{\"additions\":{\"items\":{\"type\":\"string\"},\"maxItems\":32,\"type\":\"array\",\"uniqueItems\":true},\"answeredAt\":{\"type\":\"string\"},\"formEntries\":{\"items\":{\"type\":\"string\"},\"maxItems\":32,\"type\":\"array\",\"uniqueItems\":true},\"text\":{\"maxLength\":2000,\"minLength\":1,\"type\":\"string\"}},\"required\":[\"additions\",\"answeredAt\"],\"type\":\"object\"},\"askedAt\":{\"type\":\"string\"},\"dueAt\":{\"type\":\"string\"},\"id\":{\"type\":\"string\"},\"links\":{\"additionalProperties\":false,\"properties\":{\"answer\":{\"additionalProperties\":false,\"properties\":{\"accessProfile\":{\"type\":\"string\"},\"availability\":{\"additionalProperties\":false,\"if\":{\"properties\":{\"available\":{\"const\":false}}},\"properties\":{\"available\":{\"type\":\"boolean\"},\"observedRevision\":{\"minimum\":1,\"type\":\"integer\"},\"reason\":{\"enum\":[\"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\":{\"enum\":[\"refresh\",\"revise\",\"retry\",\"rebase\",\"correct-input\",\"receipt-only\"]}},\"required\":[\"available\",\"observedRevision\"],\"then\":{\"required\":[\"reason\",\"recovery\"]},\"type\":\"object\"},\"ifMatch\":{\"type\":\"string\"},\"method\":{\"const\":\"POST\"},\"operation\":{\"const\":\"answer\"},\"path\":{\"type\":\"string\"}},\"required\":[\"method\",\"path\",\"accessProfile\",\"operation\",\"ifMatch\",\"availability\"],\"type\":\"object\"}},\"type\":\"object\"},\"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\",\"links\"],\"type\":\"object\"},\"maxItems\":50,\"type\":\"array\"},\"attachments\":{\"additionalProperties\":{\"additionalProperties\":false,\"properties\":{\"classification\":{\"enum\":[\"public\",\"internal\",\"restricted\"]},\"contentTypes\":{\"items\":{\"type\":\"string\"},\"maxItems\":16,\"minItems\":1,\"type\":\"array\",\"uniqueItems\":true},\"id\":{\"type\":\"string\"},\"links\":{\"additionalProperties\":{\"additionalProperties\":false,\"properties\":{\"accessProfile\":{\"type\":\"string\"},\"availability\":{\"additionalProperties\":false,\"if\":{\"properties\":{\"available\":{\"const\":false}}},\"properties\":{\"available\":{\"type\":\"boolean\"},\"observedRevision\":{\"minimum\":1,\"type\":\"integer\"},\"reason\":{\"enum\":[\"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\":{\"enum\":[\"refresh\",\"revise\",\"retry\",\"rebase\",\"correct-input\",\"receipt-only\"]}},\"required\":[\"available\",\"observedRevision\"],\"then\":{\"required\":[\"reason\",\"recovery\"]},\"type\":\"object\"},\"ifMatch\":{\"type\":\"string\"},\"method\":{\"enum\":[\"GET\",\"PATCH\",\"DELETE\"]},\"operation\":{\"enum\":[\"download\",\"upload\",\"remove\"]},\"path\":{\"type\":\"string\"}},\"required\":[\"method\",\"path\",\"accessProfile\",\"operation\"],\"type\":\"object\"},\"type\":\"object\"},\"maximumBytes\":{\"maximum\":16777216,\"minimum\":1,\"type\":\"integer\"},\"required\":{\"type\":\"boolean\"},\"value\":{\"additionalProperties\":false,\"properties\":{\"byteSize\":{\"minimum\":1,\"type\":\"integer\"},\"contentType\":{\"type\":\"string\"},\"sha256\":{\"pattern\":\"^[a-f0-9]{64}$\",\"type\":\"string\"},\"submissionVersion\":{\"minimum\":0,\"type\":\"integer\"},\"uploadedAt\":{\"type\":\"string\"},\"verificationStatus\":{\"enum\":[\"notRequired\",\"pending\",\"approved\",\"rejected\"]}},\"required\":[\"submissionVersion\",\"sha256\",\"contentType\",\"byteSize\",\"verificationStatus\"],\"type\":\"object\"}},\"required\":[\"id\",\"required\",\"maximumBytes\",\"contentTypes\",\"classification\",\"links\"],\"type\":\"object\"},\"maxProperties\":8,\"type\":\"object\"},\"blockedReason\":{\"enum\":[\"package-changed\"]},\"createdAt\":{\"type\":\"string\"},\"decision\":{\"additionalProperties\":false,\"properties\":{\"decidedAt\":{\"type\":\"string\"},\"publicReason\":{\"minLength\":1,\"pattern\":\"^[^\\\\u0000-\\\\u001F\\\\u007F-\\\\u009F]*[^\\\\u0000-\\\\u0020\\\\u007F-\\\\u00A0\\\\u1680\\\\u2000-\\\\u200A\\\\u2028\\\\u2029\\\\u202F\\\\u205F\\\\u3000][^\\\\u0000-\\\\u001F\\\\u007F-\\\\u009F]*$\",\"type\":\"string\"},\"status\":{\"enum\":[\"approved\",\"rejected\",\"changes-requested\",\"answered\"]}},\"required\":[\"status\",\"decidedAt\"],\"type\":\"object\"},\"effectDigest\":{\"type\":\"string\"},\"handoffRefusal\":{\"additionalProperties\":false,\"properties\":{\"code\":{\"enum\":[\"review.initiator-required\",\"review.initiator-excluded\",\"review.policy-mismatch\",\"review.refused\"]}},\"required\":[\"code\"],\"type\":\"object\"},\"id\":{\"type\":\"string\"},\"input\":{\"type\":\"object\"},\"links\":{\"additionalProperties\":{\"additionalProperties\":false,\"properties\":{\"accessProfile\":{\"type\":\"string\"},\"availability\":{\"additionalProperties\":false,\"if\":{\"properties\":{\"available\":{\"const\":false}}},\"properties\":{\"available\":{\"type\":\"boolean\"},\"observedRevision\":{\"minimum\":1,\"type\":\"integer\"},\"reason\":{\"enum\":[\"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\":{\"enum\":[\"refresh\",\"revise\",\"retry\",\"rebase\",\"correct-input\",\"receipt-only\"]}},\"required\":[\"available\",\"observedRevision\"],\"then\":{\"required\":[\"reason\",\"recovery\"]},\"type\":\"object\"},\"ifMatch\":{\"type\":\"string\"},\"method\":{\"enum\":[\"GET\",\"POST\"]},\"operation\":{\"type\":\"string\"},\"path\":{\"type\":\"string\"}},\"required\":[\"method\",\"path\",\"accessProfile\",\"operation\"],\"type\":\"object\"},\"type\":\"object\"},\"partyRole\":{\"enum\":[\"owner\",\"subject\"]},\"revision\":{\"minimum\":1,\"type\":\"integer\"},\"state\":{\"enum\":[\"draft\",\"submitted\",\"applied\",\"cancelled\",\"rejected\"]},\"status\":{\"enum\":[\"draft\",\"awaiting-party\",\"in-review\",\"approved\",\"processing\",\"applied\",\"rejected\",\"cancelled\"]},\"submissionVersion\":{\"minimum\":0,\"type\":\"integer\"},\"title\":{\"maxLength\":1024,\"type\":\"string\"},\"turn\":{\"enum\":[\"party\",\"official\",\"nobody\"]}},\"required\":[\"id\",\"actionId\",\"actionRevision\",\"submissionVersion\",\"revision\",\"state\",\"turn\",\"links\"],\"type\":\"object\"}")], ["/components/schemas/action-register-facility-availability-input", JSON.parse("{\"additionalProperties\":false,\"oneOf\":[{\"properties\":{\"input\":{\"properties\":{\"operatorId\":{\"type\":\"string\"}},\"required\":[\"operatorId\"]},\"targetInput\":{\"const\":\"operatorId\"}}}],\"properties\":{\"input\":{\"additionalProperties\":false,\"properties\":{\"addressLine\":{\"maxLength\":240,\"minLength\":1,\"type\":\"string\"},\"city\":{\"maxLength\":120,\"minLength\":1,\"type\":\"string\"},\"facilityCode\":{\"maxLength\":64,\"minLength\":1,\"type\":\"string\"},\"jurisdiction\":{\"maxLength\":40,\"minLength\":1,\"type\":\"string\"},\"name\":{\"maxLength\":200,\"minLength\":1,\"type\":\"string\"},\"operatorId\":{\"type\":\"string\"},\"postalCode\":{\"maxLength\":24,\"minLength\":1,\"type\":\"string\"}},\"required\":[],\"type\":\"object\"},\"targetInput\":{\"enum\":[\"operatorId\"],\"type\":\"string\"}},\"required\":[\"targetInput\",\"input\"],\"type\":\"object\"}")], ["/components/schemas/action-register-facility-availability-response", JSON.parse("{\"additionalProperties\":false,\"properties\":{\"availability\":{\"oneOf\":[{\"additionalProperties\":false,\"properties\":{\"available\":{\"const\":true},\"observedRevision\":{\"minimum\":1,\"type\":\"integer\"}},\"required\":[\"available\",\"observedRevision\"],\"type\":\"object\"},{\"additionalProperties\":false,\"properties\":{\"available\":{\"const\":false},\"guardLabel\":{\"maxLength\":256,\"minLength\":1,\"type\":\"string\"},\"guardReason\":{\"pattern\":\"^[a-z][a-z0-9_-]{0,63}$\",\"type\":\"string\"},\"observedRevision\":{\"minimum\":1,\"type\":\"integer\"},\"reason\":{\"const\":\"guard-not-satisfied\"},\"recovery\":{\"const\":\"none\"}},\"required\":[\"available\",\"observedRevision\",\"reason\",\"recovery\"],\"type\":\"object\"},{\"additionalProperties\":false,\"properties\":{\"available\":{\"type\":\"null\"},\"missingInputs\":{\"items\":{\"enum\":[\"facilityCode\",\"name\",\"addressLine\",\"city\",\"postalCode\",\"operatorId\",\"jurisdiction\"],\"type\":\"string\"},\"minItems\":1,\"type\":\"array\",\"uniqueItems\":true},\"observedRevision\":{\"minimum\":1,\"type\":\"integer\"},\"reason\":{\"const\":\"input-required\"},\"recovery\":{\"const\":\"correct-input\"}},\"required\":[\"available\",\"observedRevision\",\"reason\",\"recovery\",\"missingInputs\"],\"type\":\"object\"},{\"additionalProperties\":false,\"properties\":{\"available\":{\"type\":\"null\"},\"observedRevision\":{\"type\":\"null\"},\"reason\":{\"const\":\"not-disclosed\"},\"recovery\":{\"const\":\"none\"}},\"required\":[\"available\",\"observedRevision\",\"reason\",\"recovery\"],\"type\":\"object\"}]}},\"required\":[\"availability\"],\"type\":\"object\"}")], ["/components/schemas/action-register-facility-invoke-input", JSON.parse("{\"additionalProperties\":false,\"properties\":{\"input\":{\"additionalProperties\":false,\"properties\":{\"addressLine\":{\"maxLength\":240,\"minLength\":1,\"type\":\"string\"},\"city\":{\"maxLength\":120,\"minLength\":1,\"type\":\"string\"},\"facilityCode\":{\"maxLength\":64,\"minLength\":1,\"type\":\"string\"},\"jurisdiction\":{\"maxLength\":40,\"minLength\":1,\"type\":\"string\"},\"name\":{\"maxLength\":200,\"minLength\":1,\"type\":\"string\"},\"operatorId\":{\"type\":\"string\"},\"postalCode\":{\"maxLength\":24,\"minLength\":1,\"type\":\"string\"}},\"required\":[\"facilityCode\",\"name\",\"addressLine\",\"city\",\"postalCode\",\"operatorId\",\"jurisdiction\"],\"type\":\"object\"},\"preconditions\":{\"additionalProperties\":false,\"properties\":{},\"required\":[],\"type\":\"object\"}},\"required\":[\"input\"],\"type\":\"object\"}")], @@ -160,28 +164,28 @@ const rules: Record = Object.fromEntries([ ["/paths/~1v1~1actions~1register-facility~1availability/post/responses/415/content/application~1problem+json/schema", JSON.parse("{\"$ref\":\"/components/schemas/Problem\"}")], ["/paths/~1v1~1actions~1register-facility~1availability/post/responses/503/content/application~1problem+json/schema", JSON.parse("{\"$ref\":\"/components/schemas/Problem\"}")], ["/paths/~1v1~1actions~1register-facility~1availability/post/responses/504/content/application~1problem+json/schema", JSON.parse("{\"$ref\":\"/components/schemas/Problem\"}")], - ["/paths/~1v1~1proposals/get/responses/200/content/application~1json/schema", JSON.parse("{\"additionalProperties\":false,\"properties\":{\"items\":{\"items\":{\"additionalProperties\":false,\"properties\":{\"actionId\":{\"type\":\"string\"},\"actionRevision\":{\"type\":\"string\"},\"application\":{\"additionalProperties\":false,\"properties\":{\"applicationId\":{\"type\":\"string\"},\"effectDigest\":{\"pattern\":\"^sha256:[0-9a-f]{64}$\",\"type\":\"string\"},\"resultLinks\":{\"items\":{\"additionalProperties\":false,\"properties\":{\"recordId\":{\"type\":\"string\"},\"recordType\":{\"type\":\"string\"},\"revision\":{\"minimum\":1,\"type\":\"integer\"}},\"required\":[\"recordType\",\"recordId\",\"revision\"],\"type\":\"object\"},\"maxItems\":16,\"type\":\"array\"},\"submissionVersion\":{\"minimum\":1,\"type\":\"integer\"}},\"required\":[\"applicationId\",\"submissionVersion\",\"effectDigest\",\"resultLinks\"],\"type\":\"object\"},\"applicationStatus\":{\"additionalProperties\":false,\"properties\":{\"automaticRetry\":{\"additionalProperties\":false,\"properties\":{\"attempts\":{\"maximum\":1000,\"minimum\":0,\"type\":\"integer\"},\"maximumAttempts\":{\"maximum\":1000,\"minimum\":1,\"type\":\"integer\"},\"scheduled\":{\"type\":\"boolean\"}},\"required\":[\"scheduled\",\"attempts\",\"maximumAttempts\"],\"type\":\"object\"},\"mode\":{\"enum\":[\"automatic\",\"manual\"]},\"reason\":{\"enum\":[\"package-changed\",\"dependency-outage\",\"lease-expired\",\"application-refused\",\"attempts-exhausted\"]},\"recovery\":{\"enum\":[\"retry\",\"rebase\",\"revise\",\"correct-input\"]},\"state\":{\"enum\":[\"awaiting-review\",\"pending\",\"applying\",\"blocked\",\"applied\",\"cancelled\",\"rejected\"]}},\"required\":[\"state\",\"mode\"],\"type\":\"object\"},\"asks\":{\"items\":{\"additionalProperties\":false,\"properties\":{\"answer\":{\"additionalProperties\":false,\"properties\":{\"additions\":{\"items\":{\"type\":\"string\"},\"maxItems\":32,\"type\":\"array\",\"uniqueItems\":true},\"answeredAt\":{\"type\":\"string\"},\"text\":{\"maxLength\":2000,\"minLength\":1,\"type\":\"string\"}},\"required\":[\"additions\",\"answeredAt\"],\"type\":\"object\"},\"askedAt\":{\"type\":\"string\"},\"dueAt\":{\"type\":\"string\"},\"id\":{\"type\":\"string\"},\"links\":{\"additionalProperties\":false,\"properties\":{\"answer\":{\"additionalProperties\":false,\"properties\":{\"accessProfile\":{\"type\":\"string\"},\"availability\":{\"additionalProperties\":false,\"if\":{\"properties\":{\"available\":{\"const\":false}}},\"properties\":{\"available\":{\"type\":\"boolean\"},\"observedRevision\":{\"minimum\":1,\"type\":\"integer\"},\"reason\":{\"enum\":[\"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\":{\"enum\":[\"refresh\",\"revise\",\"retry\",\"rebase\",\"correct-input\",\"receipt-only\"]}},\"required\":[\"available\",\"observedRevision\"],\"then\":{\"required\":[\"reason\",\"recovery\"]},\"type\":\"object\"},\"ifMatch\":{\"type\":\"string\"},\"method\":{\"const\":\"POST\"},\"operation\":{\"const\":\"answer\"},\"path\":{\"type\":\"string\"}},\"required\":[\"method\",\"path\",\"accessProfile\",\"operation\",\"ifMatch\",\"availability\"],\"type\":\"object\"}},\"type\":\"object\"},\"state\":{\"enum\":[\"open\",\"answered\",\"expired\",\"closed\"]},\"text\":{\"maxLength\":2000,\"minLength\":1,\"type\":\"string\"},\"wants\":{\"items\":{\"additionalProperties\":false,\"properties\":{\"kind\":{\"enum\":[\"answer\",\"document\"]}},\"required\":[\"kind\"],\"type\":\"object\"},\"maxItems\":8,\"type\":\"array\",\"uniqueItems\":true}},\"required\":[\"id\",\"text\",\"wants\",\"askedAt\",\"state\",\"links\"],\"type\":\"object\"},\"maxItems\":50,\"type\":\"array\"},\"attachments\":{\"additionalProperties\":{\"additionalProperties\":false,\"properties\":{\"classification\":{\"enum\":[\"public\",\"internal\",\"restricted\"]},\"contentTypes\":{\"items\":{\"type\":\"string\"},\"maxItems\":16,\"minItems\":1,\"type\":\"array\",\"uniqueItems\":true},\"id\":{\"type\":\"string\"},\"links\":{\"additionalProperties\":{\"additionalProperties\":false,\"properties\":{\"accessProfile\":{\"type\":\"string\"},\"availability\":{\"additionalProperties\":false,\"if\":{\"properties\":{\"available\":{\"const\":false}}},\"properties\":{\"available\":{\"type\":\"boolean\"},\"observedRevision\":{\"minimum\":1,\"type\":\"integer\"},\"reason\":{\"enum\":[\"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\":{\"enum\":[\"refresh\",\"revise\",\"retry\",\"rebase\",\"correct-input\",\"receipt-only\"]}},\"required\":[\"available\",\"observedRevision\"],\"then\":{\"required\":[\"reason\",\"recovery\"]},\"type\":\"object\"},\"ifMatch\":{\"type\":\"string\"},\"method\":{\"enum\":[\"GET\",\"PATCH\",\"DELETE\"]},\"operation\":{\"enum\":[\"download\",\"upload\",\"remove\"]},\"path\":{\"type\":\"string\"}},\"required\":[\"method\",\"path\",\"accessProfile\",\"operation\"],\"type\":\"object\"},\"type\":\"object\"},\"maximumBytes\":{\"maximum\":16777216,\"minimum\":1,\"type\":\"integer\"},\"required\":{\"type\":\"boolean\"},\"value\":{\"additionalProperties\":false,\"properties\":{\"byteSize\":{\"minimum\":1,\"type\":\"integer\"},\"contentType\":{\"type\":\"string\"},\"sha256\":{\"pattern\":\"^[a-f0-9]{64}$\",\"type\":\"string\"},\"submissionVersion\":{\"minimum\":0,\"type\":\"integer\"},\"uploadedAt\":{\"type\":\"string\"},\"verificationStatus\":{\"enum\":[\"notRequired\",\"pending\",\"approved\",\"rejected\"]}},\"required\":[\"submissionVersion\",\"sha256\",\"contentType\",\"byteSize\",\"verificationStatus\"],\"type\":\"object\"}},\"required\":[\"id\",\"required\",\"maximumBytes\",\"contentTypes\",\"classification\",\"links\"],\"type\":\"object\"},\"maxProperties\":8,\"type\":\"object\"},\"blockedReason\":{\"enum\":[\"package-changed\"]},\"createdAt\":{\"type\":\"string\"},\"decision\":{\"additionalProperties\":false,\"properties\":{\"decidedAt\":{\"type\":\"string\"},\"publicReason\":{\"minLength\":1,\"pattern\":\"^[^\\\\u0000-\\\\u001F\\\\u007F-\\\\u009F]*[^\\\\u0000-\\\\u0020\\\\u007F-\\\\u00A0\\\\u1680\\\\u2000-\\\\u200A\\\\u2028\\\\u2029\\\\u202F\\\\u205F\\\\u3000][^\\\\u0000-\\\\u001F\\\\u007F-\\\\u009F]*$\",\"type\":\"string\"},\"status\":{\"enum\":[\"approved\",\"rejected\",\"changes-requested\",\"answered\"]}},\"required\":[\"status\",\"decidedAt\"],\"type\":\"object\"},\"effectDigest\":{\"type\":\"string\"},\"handoffRefusal\":{\"additionalProperties\":false,\"properties\":{\"code\":{\"enum\":[\"review.initiator-required\",\"review.initiator-excluded\",\"review.policy-mismatch\",\"review.refused\"]}},\"required\":[\"code\"],\"type\":\"object\"},\"id\":{\"type\":\"string\"},\"input\":{\"type\":\"object\"},\"links\":{\"additionalProperties\":{\"additionalProperties\":false,\"properties\":{\"accessProfile\":{\"type\":\"string\"},\"availability\":{\"additionalProperties\":false,\"if\":{\"properties\":{\"available\":{\"const\":false}}},\"properties\":{\"available\":{\"type\":\"boolean\"},\"observedRevision\":{\"minimum\":1,\"type\":\"integer\"},\"reason\":{\"enum\":[\"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\":{\"enum\":[\"refresh\",\"revise\",\"retry\",\"rebase\",\"correct-input\",\"receipt-only\"]}},\"required\":[\"available\",\"observedRevision\"],\"then\":{\"required\":[\"reason\",\"recovery\"]},\"type\":\"object\"},\"ifMatch\":{\"type\":\"string\"},\"method\":{\"enum\":[\"GET\",\"POST\"]},\"operation\":{\"type\":\"string\"},\"path\":{\"type\":\"string\"}},\"required\":[\"method\",\"path\",\"accessProfile\",\"operation\"],\"type\":\"object\"},\"type\":\"object\"},\"revision\":{\"minimum\":1,\"type\":\"integer\"},\"state\":{\"enum\":[\"draft\",\"submitted\",\"applied\",\"cancelled\",\"rejected\"]},\"status\":{\"enum\":[\"draft\",\"awaiting-party\",\"in-review\",\"approved\",\"processing\",\"applied\",\"rejected\",\"cancelled\"]},\"submissionVersion\":{\"minimum\":0,\"type\":\"integer\"},\"title\":{\"maxLength\":1024,\"type\":\"string\"},\"turn\":{\"enum\":[\"party\",\"official\",\"nobody\"]}},\"required\":[\"id\",\"actionId\",\"actionRevision\",\"submissionVersion\",\"revision\",\"state\",\"turn\",\"links\"],\"type\":\"object\"},\"maxItems\":100,\"type\":\"array\"},\"nextCursor\":{\"type\":\"string\"}},\"required\":[\"items\"],\"type\":\"object\"}")], + ["/paths/~1v1~1proposals/get/responses/200/content/application~1json/schema", JSON.parse("{\"additionalProperties\":false,\"properties\":{\"items\":{\"items\":{\"additionalProperties\":false,\"properties\":{\"actionId\":{\"type\":\"string\"},\"actionRevision\":{\"type\":\"string\"},\"application\":{\"additionalProperties\":false,\"properties\":{\"applicationId\":{\"type\":\"string\"},\"effectDigest\":{\"pattern\":\"^sha256:[0-9a-f]{64}$\",\"type\":\"string\"},\"resultLinks\":{\"items\":{\"additionalProperties\":false,\"properties\":{\"recordId\":{\"type\":\"string\"},\"recordType\":{\"type\":\"string\"},\"revision\":{\"minimum\":1,\"type\":\"integer\"}},\"required\":[\"recordType\",\"recordId\",\"revision\"],\"type\":\"object\"},\"maxItems\":16,\"type\":\"array\"},\"submissionVersion\":{\"minimum\":1,\"type\":\"integer\"}},\"required\":[\"applicationId\",\"submissionVersion\",\"effectDigest\",\"resultLinks\"],\"type\":\"object\"},\"applicationStatus\":{\"additionalProperties\":false,\"properties\":{\"automaticRetry\":{\"additionalProperties\":false,\"properties\":{\"attempts\":{\"maximum\":1000,\"minimum\":0,\"type\":\"integer\"},\"maximumAttempts\":{\"maximum\":1000,\"minimum\":1,\"type\":\"integer\"},\"scheduled\":{\"type\":\"boolean\"}},\"required\":[\"scheduled\",\"attempts\",\"maximumAttempts\"],\"type\":\"object\"},\"mode\":{\"enum\":[\"automatic\",\"manual\"]},\"reason\":{\"enum\":[\"package-changed\",\"dependency-outage\",\"lease-expired\",\"application-refused\",\"attempts-exhausted\"]},\"recovery\":{\"enum\":[\"retry\",\"rebase\",\"revise\",\"correct-input\"]},\"state\":{\"enum\":[\"awaiting-review\",\"pending\",\"applying\",\"blocked\",\"applied\",\"cancelled\",\"rejected\"]}},\"required\":[\"state\",\"mode\"],\"type\":\"object\"},\"asks\":{\"items\":{\"additionalProperties\":false,\"properties\":{\"answer\":{\"additionalProperties\":false,\"properties\":{\"additions\":{\"items\":{\"type\":\"string\"},\"maxItems\":32,\"type\":\"array\",\"uniqueItems\":true},\"answeredAt\":{\"type\":\"string\"},\"formEntries\":{\"items\":{\"type\":\"string\"},\"maxItems\":32,\"type\":\"array\",\"uniqueItems\":true},\"text\":{\"maxLength\":2000,\"minLength\":1,\"type\":\"string\"}},\"required\":[\"additions\",\"answeredAt\"],\"type\":\"object\"},\"askedAt\":{\"type\":\"string\"},\"dueAt\":{\"type\":\"string\"},\"id\":{\"type\":\"string\"},\"links\":{\"additionalProperties\":false,\"properties\":{\"answer\":{\"additionalProperties\":false,\"properties\":{\"accessProfile\":{\"type\":\"string\"},\"availability\":{\"additionalProperties\":false,\"if\":{\"properties\":{\"available\":{\"const\":false}}},\"properties\":{\"available\":{\"type\":\"boolean\"},\"observedRevision\":{\"minimum\":1,\"type\":\"integer\"},\"reason\":{\"enum\":[\"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\":{\"enum\":[\"refresh\",\"revise\",\"retry\",\"rebase\",\"correct-input\",\"receipt-only\"]}},\"required\":[\"available\",\"observedRevision\"],\"then\":{\"required\":[\"reason\",\"recovery\"]},\"type\":\"object\"},\"ifMatch\":{\"type\":\"string\"},\"method\":{\"const\":\"POST\"},\"operation\":{\"const\":\"answer\"},\"path\":{\"type\":\"string\"}},\"required\":[\"method\",\"path\",\"accessProfile\",\"operation\",\"ifMatch\",\"availability\"],\"type\":\"object\"}},\"type\":\"object\"},\"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\",\"links\"],\"type\":\"object\"},\"maxItems\":50,\"type\":\"array\"},\"attachments\":{\"additionalProperties\":{\"additionalProperties\":false,\"properties\":{\"classification\":{\"enum\":[\"public\",\"internal\",\"restricted\"]},\"contentTypes\":{\"items\":{\"type\":\"string\"},\"maxItems\":16,\"minItems\":1,\"type\":\"array\",\"uniqueItems\":true},\"id\":{\"type\":\"string\"},\"links\":{\"additionalProperties\":{\"additionalProperties\":false,\"properties\":{\"accessProfile\":{\"type\":\"string\"},\"availability\":{\"additionalProperties\":false,\"if\":{\"properties\":{\"available\":{\"const\":false}}},\"properties\":{\"available\":{\"type\":\"boolean\"},\"observedRevision\":{\"minimum\":1,\"type\":\"integer\"},\"reason\":{\"enum\":[\"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\":{\"enum\":[\"refresh\",\"revise\",\"retry\",\"rebase\",\"correct-input\",\"receipt-only\"]}},\"required\":[\"available\",\"observedRevision\"],\"then\":{\"required\":[\"reason\",\"recovery\"]},\"type\":\"object\"},\"ifMatch\":{\"type\":\"string\"},\"method\":{\"enum\":[\"GET\",\"PATCH\",\"DELETE\"]},\"operation\":{\"enum\":[\"download\",\"upload\",\"remove\"]},\"path\":{\"type\":\"string\"}},\"required\":[\"method\",\"path\",\"accessProfile\",\"operation\"],\"type\":\"object\"},\"type\":\"object\"},\"maximumBytes\":{\"maximum\":16777216,\"minimum\":1,\"type\":\"integer\"},\"required\":{\"type\":\"boolean\"},\"value\":{\"additionalProperties\":false,\"properties\":{\"byteSize\":{\"minimum\":1,\"type\":\"integer\"},\"contentType\":{\"type\":\"string\"},\"sha256\":{\"pattern\":\"^[a-f0-9]{64}$\",\"type\":\"string\"},\"submissionVersion\":{\"minimum\":0,\"type\":\"integer\"},\"uploadedAt\":{\"type\":\"string\"},\"verificationStatus\":{\"enum\":[\"notRequired\",\"pending\",\"approved\",\"rejected\"]}},\"required\":[\"submissionVersion\",\"sha256\",\"contentType\",\"byteSize\",\"verificationStatus\"],\"type\":\"object\"}},\"required\":[\"id\",\"required\",\"maximumBytes\",\"contentTypes\",\"classification\",\"links\"],\"type\":\"object\"},\"maxProperties\":8,\"type\":\"object\"},\"blockedReason\":{\"enum\":[\"package-changed\"]},\"createdAt\":{\"type\":\"string\"},\"decision\":{\"additionalProperties\":false,\"properties\":{\"decidedAt\":{\"type\":\"string\"},\"publicReason\":{\"minLength\":1,\"pattern\":\"^[^\\\\u0000-\\\\u001F\\\\u007F-\\\\u009F]*[^\\\\u0000-\\\\u0020\\\\u007F-\\\\u00A0\\\\u1680\\\\u2000-\\\\u200A\\\\u2028\\\\u2029\\\\u202F\\\\u205F\\\\u3000][^\\\\u0000-\\\\u001F\\\\u007F-\\\\u009F]*$\",\"type\":\"string\"},\"status\":{\"enum\":[\"approved\",\"rejected\",\"changes-requested\",\"answered\"]}},\"required\":[\"status\",\"decidedAt\"],\"type\":\"object\"},\"effectDigest\":{\"type\":\"string\"},\"handoffRefusal\":{\"additionalProperties\":false,\"properties\":{\"code\":{\"enum\":[\"review.initiator-required\",\"review.initiator-excluded\",\"review.policy-mismatch\",\"review.refused\"]}},\"required\":[\"code\"],\"type\":\"object\"},\"id\":{\"type\":\"string\"},\"input\":{\"type\":\"object\"},\"links\":{\"additionalProperties\":{\"additionalProperties\":false,\"properties\":{\"accessProfile\":{\"type\":\"string\"},\"availability\":{\"additionalProperties\":false,\"if\":{\"properties\":{\"available\":{\"const\":false}}},\"properties\":{\"available\":{\"type\":\"boolean\"},\"observedRevision\":{\"minimum\":1,\"type\":\"integer\"},\"reason\":{\"enum\":[\"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\":{\"enum\":[\"refresh\",\"revise\",\"retry\",\"rebase\",\"correct-input\",\"receipt-only\"]}},\"required\":[\"available\",\"observedRevision\"],\"then\":{\"required\":[\"reason\",\"recovery\"]},\"type\":\"object\"},\"ifMatch\":{\"type\":\"string\"},\"method\":{\"enum\":[\"GET\",\"POST\"]},\"operation\":{\"type\":\"string\"},\"path\":{\"type\":\"string\"}},\"required\":[\"method\",\"path\",\"accessProfile\",\"operation\"],\"type\":\"object\"},\"type\":\"object\"},\"partyRole\":{\"enum\":[\"owner\",\"subject\"]},\"revision\":{\"minimum\":1,\"type\":\"integer\"},\"state\":{\"enum\":[\"draft\",\"submitted\",\"applied\",\"cancelled\",\"rejected\"]},\"status\":{\"enum\":[\"draft\",\"awaiting-party\",\"in-review\",\"approved\",\"processing\",\"applied\",\"rejected\",\"cancelled\"]},\"submissionVersion\":{\"minimum\":0,\"type\":\"integer\"},\"title\":{\"maxLength\":1024,\"type\":\"string\"},\"turn\":{\"enum\":[\"party\",\"official\",\"nobody\"]}},\"required\":[\"id\",\"actionId\",\"actionRevision\",\"submissionVersion\",\"revision\",\"state\",\"turn\",\"links\"],\"type\":\"object\"},\"maxItems\":100,\"type\":\"array\"},\"nextCursor\":{\"type\":\"string\"}},\"required\":[\"items\"],\"type\":\"object\"}")], ["/paths/~1v1~1proposals/get/responses/400/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"access-profile.ambiguous\",\"query.invalid\"]}},\"type\":\"object\"}]}")], ["/paths/~1v1~1proposals/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/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/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\"}]}")], ["/paths/~1v1~1proposals~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~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~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}/get/responses/200/content/application~1json/schema", JSON.parse("{\"additionalProperties\":false,\"properties\":{\"actionId\":{\"type\":\"string\"},\"actionRevision\":{\"type\":\"string\"},\"application\":{\"additionalProperties\":false,\"dependentRequired\":{\"appliedAt\":[\"appliedBy\"],\"appliedBy\":[\"appliedAt\"]},\"properties\":{\"applicationId\":{\"type\":\"string\"},\"appliedAt\":{\"type\":\"string\"},\"appliedBy\":{\"pattern\":\"^hmac-sha256:[0-9a-f]{64}$\",\"type\":\"string\"},\"effectDigest\":{\"pattern\":\"^sha256:[0-9a-f]{64}$\",\"type\":\"string\"},\"resultLinks\":{\"items\":{\"additionalProperties\":false,\"properties\":{\"recordId\":{\"type\":\"string\"},\"recordType\":{\"type\":\"string\"},\"revision\":{\"minimum\":1,\"type\":\"integer\"}},\"required\":[\"recordType\",\"recordId\",\"revision\"],\"type\":\"object\"},\"maxItems\":16,\"type\":\"array\"},\"submissionVersion\":{\"minimum\":1,\"type\":\"integer\"}},\"required\":[\"applicationId\",\"submissionVersion\",\"effectDigest\",\"resultLinks\"],\"type\":\"object\"},\"applicationStatus\":{\"additionalProperties\":false,\"properties\":{\"automaticRetry\":{\"additionalProperties\":false,\"properties\":{\"attempts\":{\"maximum\":1000,\"minimum\":0,\"type\":\"integer\"},\"maximumAttempts\":{\"maximum\":1000,\"minimum\":1,\"type\":\"integer\"},\"scheduled\":{\"type\":\"boolean\"}},\"required\":[\"scheduled\",\"attempts\",\"maximumAttempts\"],\"type\":\"object\"},\"mode\":{\"enum\":[\"automatic\",\"manual\"]},\"reason\":{\"enum\":[\"package-changed\",\"dependency-outage\",\"lease-expired\",\"application-refused\",\"attempts-exhausted\"]},\"recovery\":{\"enum\":[\"retry\",\"rebase\",\"revise\",\"correct-input\"]},\"state\":{\"enum\":[\"awaiting-review\",\"pending\",\"applying\",\"blocked\",\"applied\",\"cancelled\",\"rejected\"]}},\"required\":[\"state\",\"mode\"],\"type\":\"object\"},\"asks\":{\"items\":{\"additionalProperties\":false,\"properties\":{\"answer\":{\"additionalProperties\":false,\"properties\":{\"additions\":{\"items\":{\"type\":\"string\"},\"maxItems\":32,\"type\":\"array\",\"uniqueItems\":true},\"answeredAt\":{\"type\":\"string\"},\"text\":{\"maxLength\":2000,\"minLength\":1,\"type\":\"string\"}},\"required\":[\"additions\",\"answeredAt\"],\"type\":\"object\"},\"askedAt\":{\"type\":\"string\"},\"dueAt\":{\"type\":\"string\"},\"id\":{\"type\":\"string\"},\"links\":{\"additionalProperties\":false,\"properties\":{\"answer\":{\"additionalProperties\":false,\"properties\":{\"accessProfile\":{\"type\":\"string\"},\"availability\":{\"additionalProperties\":false,\"if\":{\"properties\":{\"available\":{\"const\":false}}},\"properties\":{\"available\":{\"type\":\"boolean\"},\"observedRevision\":{\"minimum\":1,\"type\":\"integer\"},\"reason\":{\"enum\":[\"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\":{\"enum\":[\"refresh\",\"revise\",\"retry\",\"rebase\",\"correct-input\",\"receipt-only\"]}},\"required\":[\"available\",\"observedRevision\"],\"then\":{\"required\":[\"reason\",\"recovery\"]},\"type\":\"object\"},\"ifMatch\":{\"type\":\"string\"},\"method\":{\"const\":\"POST\"},\"operation\":{\"const\":\"answer\"},\"path\":{\"type\":\"string\"}},\"required\":[\"method\",\"path\",\"accessProfile\",\"operation\",\"ifMatch\",\"availability\"],\"type\":\"object\"}},\"type\":\"object\"},\"state\":{\"enum\":[\"open\",\"answered\",\"expired\",\"closed\"]},\"text\":{\"maxLength\":2000,\"minLength\":1,\"type\":\"string\"},\"wants\":{\"items\":{\"additionalProperties\":false,\"properties\":{\"kind\":{\"enum\":[\"answer\",\"document\"]}},\"required\":[\"kind\"],\"type\":\"object\"},\"maxItems\":8,\"type\":\"array\",\"uniqueItems\":true}},\"required\":[\"id\",\"text\",\"wants\",\"askedAt\",\"state\",\"links\"],\"type\":\"object\"},\"maxItems\":50,\"type\":\"array\"},\"attachments\":{\"additionalProperties\":{\"additionalProperties\":false,\"properties\":{\"classification\":{\"enum\":[\"public\",\"internal\",\"restricted\"]},\"contentTypes\":{\"items\":{\"type\":\"string\"},\"maxItems\":16,\"minItems\":1,\"type\":\"array\",\"uniqueItems\":true},\"id\":{\"type\":\"string\"},\"links\":{\"additionalProperties\":{\"additionalProperties\":false,\"properties\":{\"accessProfile\":{\"type\":\"string\"},\"availability\":{\"additionalProperties\":false,\"if\":{\"properties\":{\"available\":{\"const\":false}}},\"properties\":{\"available\":{\"type\":\"boolean\"},\"observedRevision\":{\"minimum\":1,\"type\":\"integer\"},\"reason\":{\"enum\":[\"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\":{\"enum\":[\"refresh\",\"revise\",\"retry\",\"rebase\",\"correct-input\",\"receipt-only\"]}},\"required\":[\"available\",\"observedRevision\"],\"then\":{\"required\":[\"reason\",\"recovery\"]},\"type\":\"object\"},\"ifMatch\":{\"type\":\"string\"},\"method\":{\"enum\":[\"GET\",\"PATCH\",\"DELETE\"]},\"operation\":{\"enum\":[\"download\",\"upload\",\"remove\"]},\"path\":{\"type\":\"string\"}},\"required\":[\"method\",\"path\",\"accessProfile\",\"operation\"],\"type\":\"object\"},\"type\":\"object\"},\"maximumBytes\":{\"maximum\":16777216,\"minimum\":1,\"type\":\"integer\"},\"required\":{\"type\":\"boolean\"},\"value\":{\"additionalProperties\":false,\"properties\":{\"byteSize\":{\"minimum\":1,\"type\":\"integer\"},\"contentType\":{\"type\":\"string\"},\"sha256\":{\"pattern\":\"^[a-f0-9]{64}$\",\"type\":\"string\"},\"submissionVersion\":{\"minimum\":0,\"type\":\"integer\"},\"uploadedAt\":{\"type\":\"string\"},\"verificationStatus\":{\"enum\":[\"notRequired\",\"pending\",\"approved\",\"rejected\"]}},\"required\":[\"submissionVersion\",\"sha256\",\"contentType\",\"byteSize\",\"verificationStatus\"],\"type\":\"object\"}},\"required\":[\"id\",\"required\",\"maximumBytes\",\"contentTypes\",\"classification\",\"links\"],\"type\":\"object\"},\"maxProperties\":8,\"type\":\"object\"},\"blockedReason\":{\"enum\":[\"package-changed\"]},\"createdAt\":{\"type\":\"string\"},\"decision\":{\"additionalProperties\":false,\"properties\":{\"decidedAt\":{\"type\":\"string\"},\"publicReason\":{\"minLength\":1,\"pattern\":\"^[^\\\\u0000-\\\\u001F\\\\u007F-\\\\u009F]*[^\\\\u0000-\\\\u0020\\\\u007F-\\\\u00A0\\\\u1680\\\\u2000-\\\\u200A\\\\u2028\\\\u2029\\\\u202F\\\\u205F\\\\u3000][^\\\\u0000-\\\\u001F\\\\u007F-\\\\u009F]*$\",\"type\":\"string\"},\"status\":{\"enum\":[\"approved\",\"rejected\",\"changes-requested\",\"answered\"]}},\"required\":[\"status\",\"decidedAt\"],\"type\":\"object\"},\"effectDigest\":{\"type\":\"string\"},\"handoffRefusal\":{\"additionalProperties\":false,\"properties\":{\"code\":{\"enum\":[\"review.initiator-required\",\"review.initiator-excluded\",\"review.policy-mismatch\",\"review.refused\"]}},\"required\":[\"code\"],\"type\":\"object\"},\"id\":{\"type\":\"string\"},\"input\":{\"type\":\"object\"},\"links\":{\"additionalProperties\":{\"additionalProperties\":false,\"properties\":{\"accessProfile\":{\"type\":\"string\"},\"availability\":{\"additionalProperties\":false,\"if\":{\"properties\":{\"available\":{\"const\":false}}},\"properties\":{\"available\":{\"type\":\"boolean\"},\"observedRevision\":{\"minimum\":1,\"type\":\"integer\"},\"reason\":{\"enum\":[\"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\":{\"enum\":[\"refresh\",\"revise\",\"retry\",\"rebase\",\"correct-input\",\"receipt-only\"]}},\"required\":[\"available\",\"observedRevision\"],\"then\":{\"required\":[\"reason\",\"recovery\"]},\"type\":\"object\"},\"ifMatch\":{\"type\":\"string\"},\"method\":{\"enum\":[\"GET\",\"POST\"]},\"operation\":{\"type\":\"string\"},\"path\":{\"type\":\"string\"}},\"required\":[\"method\",\"path\",\"accessProfile\",\"operation\"],\"type\":\"object\"},\"type\":\"object\"},\"revision\":{\"minimum\":1,\"type\":\"integer\"},\"state\":{\"enum\":[\"draft\",\"submitted\",\"applied\",\"cancelled\",\"rejected\"]},\"status\":{\"enum\":[\"draft\",\"awaiting-party\",\"in-review\",\"approved\",\"processing\",\"applied\",\"rejected\",\"cancelled\"]},\"submissionVersion\":{\"minimum\":0,\"type\":\"integer\"},\"title\":{\"maxLength\":1024,\"type\":\"string\"},\"turn\":{\"enum\":[\"party\",\"official\",\"nobody\"]}},\"required\":[\"id\",\"actionId\",\"actionRevision\",\"submissionVersion\",\"revision\",\"state\",\"turn\",\"links\"],\"type\":\"object\"}")], + ["/paths/~1v1~1proposals~1{proposal_id}/get/responses/200/content/application~1json/schema", JSON.parse("{\"additionalProperties\":false,\"properties\":{\"actionId\":{\"type\":\"string\"},\"actionRevision\":{\"type\":\"string\"},\"application\":{\"additionalProperties\":false,\"dependentRequired\":{\"appliedAt\":[\"appliedBy\"],\"appliedBy\":[\"appliedAt\"]},\"properties\":{\"applicationId\":{\"type\":\"string\"},\"appliedAt\":{\"type\":\"string\"},\"appliedBy\":{\"pattern\":\"^hmac-sha256:[0-9a-f]{64}$\",\"type\":\"string\"},\"effectDigest\":{\"pattern\":\"^sha256:[0-9a-f]{64}$\",\"type\":\"string\"},\"resultLinks\":{\"items\":{\"additionalProperties\":false,\"properties\":{\"recordId\":{\"type\":\"string\"},\"recordType\":{\"type\":\"string\"},\"revision\":{\"minimum\":1,\"type\":\"integer\"}},\"required\":[\"recordType\",\"recordId\",\"revision\"],\"type\":\"object\"},\"maxItems\":16,\"type\":\"array\"},\"submissionVersion\":{\"minimum\":1,\"type\":\"integer\"}},\"required\":[\"applicationId\",\"submissionVersion\",\"effectDigest\",\"resultLinks\"],\"type\":\"object\"},\"applicationStatus\":{\"additionalProperties\":false,\"properties\":{\"automaticRetry\":{\"additionalProperties\":false,\"properties\":{\"attempts\":{\"maximum\":1000,\"minimum\":0,\"type\":\"integer\"},\"maximumAttempts\":{\"maximum\":1000,\"minimum\":1,\"type\":\"integer\"},\"scheduled\":{\"type\":\"boolean\"}},\"required\":[\"scheduled\",\"attempts\",\"maximumAttempts\"],\"type\":\"object\"},\"mode\":{\"enum\":[\"automatic\",\"manual\"]},\"reason\":{\"enum\":[\"package-changed\",\"dependency-outage\",\"lease-expired\",\"application-refused\",\"attempts-exhausted\"]},\"recovery\":{\"enum\":[\"retry\",\"rebase\",\"revise\",\"correct-input\"]},\"state\":{\"enum\":[\"awaiting-review\",\"pending\",\"applying\",\"blocked\",\"applied\",\"cancelled\",\"rejected\"]}},\"required\":[\"state\",\"mode\"],\"type\":\"object\"},\"asks\":{\"items\":{\"additionalProperties\":false,\"properties\":{\"answer\":{\"additionalProperties\":false,\"properties\":{\"additions\":{\"items\":{\"type\":\"string\"},\"maxItems\":32,\"type\":\"array\",\"uniqueItems\":true},\"answeredAt\":{\"type\":\"string\"},\"formEntries\":{\"items\":{\"type\":\"string\"},\"maxItems\":32,\"type\":\"array\",\"uniqueItems\":true},\"text\":{\"maxLength\":2000,\"minLength\":1,\"type\":\"string\"}},\"required\":[\"additions\",\"answeredAt\"],\"type\":\"object\"},\"askedAt\":{\"type\":\"string\"},\"dueAt\":{\"type\":\"string\"},\"id\":{\"type\":\"string\"},\"links\":{\"additionalProperties\":false,\"properties\":{\"answer\":{\"additionalProperties\":false,\"properties\":{\"accessProfile\":{\"type\":\"string\"},\"availability\":{\"additionalProperties\":false,\"if\":{\"properties\":{\"available\":{\"const\":false}}},\"properties\":{\"available\":{\"type\":\"boolean\"},\"observedRevision\":{\"minimum\":1,\"type\":\"integer\"},\"reason\":{\"enum\":[\"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\":{\"enum\":[\"refresh\",\"revise\",\"retry\",\"rebase\",\"correct-input\",\"receipt-only\"]}},\"required\":[\"available\",\"observedRevision\"],\"then\":{\"required\":[\"reason\",\"recovery\"]},\"type\":\"object\"},\"ifMatch\":{\"type\":\"string\"},\"method\":{\"const\":\"POST\"},\"operation\":{\"const\":\"answer\"},\"path\":{\"type\":\"string\"}},\"required\":[\"method\",\"path\",\"accessProfile\",\"operation\",\"ifMatch\",\"availability\"],\"type\":\"object\"}},\"type\":\"object\"},\"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\",\"links\"],\"type\":\"object\"},\"maxItems\":50,\"type\":\"array\"},\"attachments\":{\"additionalProperties\":{\"additionalProperties\":false,\"properties\":{\"classification\":{\"enum\":[\"public\",\"internal\",\"restricted\"]},\"contentTypes\":{\"items\":{\"type\":\"string\"},\"maxItems\":16,\"minItems\":1,\"type\":\"array\",\"uniqueItems\":true},\"id\":{\"type\":\"string\"},\"links\":{\"additionalProperties\":{\"additionalProperties\":false,\"properties\":{\"accessProfile\":{\"type\":\"string\"},\"availability\":{\"additionalProperties\":false,\"if\":{\"properties\":{\"available\":{\"const\":false}}},\"properties\":{\"available\":{\"type\":\"boolean\"},\"observedRevision\":{\"minimum\":1,\"type\":\"integer\"},\"reason\":{\"enum\":[\"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\":{\"enum\":[\"refresh\",\"revise\",\"retry\",\"rebase\",\"correct-input\",\"receipt-only\"]}},\"required\":[\"available\",\"observedRevision\"],\"then\":{\"required\":[\"reason\",\"recovery\"]},\"type\":\"object\"},\"ifMatch\":{\"type\":\"string\"},\"method\":{\"enum\":[\"GET\",\"PATCH\",\"DELETE\"]},\"operation\":{\"enum\":[\"download\",\"upload\",\"remove\"]},\"path\":{\"type\":\"string\"}},\"required\":[\"method\",\"path\",\"accessProfile\",\"operation\"],\"type\":\"object\"},\"type\":\"object\"},\"maximumBytes\":{\"maximum\":16777216,\"minimum\":1,\"type\":\"integer\"},\"required\":{\"type\":\"boolean\"},\"value\":{\"additionalProperties\":false,\"properties\":{\"byteSize\":{\"minimum\":1,\"type\":\"integer\"},\"contentType\":{\"type\":\"string\"},\"sha256\":{\"pattern\":\"^[a-f0-9]{64}$\",\"type\":\"string\"},\"submissionVersion\":{\"minimum\":0,\"type\":\"integer\"},\"uploadedAt\":{\"type\":\"string\"},\"verificationStatus\":{\"enum\":[\"notRequired\",\"pending\",\"approved\",\"rejected\"]}},\"required\":[\"submissionVersion\",\"sha256\",\"contentType\",\"byteSize\",\"verificationStatus\"],\"type\":\"object\"}},\"required\":[\"id\",\"required\",\"maximumBytes\",\"contentTypes\",\"classification\",\"links\"],\"type\":\"object\"},\"maxProperties\":8,\"type\":\"object\"},\"blockedReason\":{\"enum\":[\"package-changed\"]},\"createdAt\":{\"type\":\"string\"},\"decision\":{\"additionalProperties\":false,\"properties\":{\"decidedAt\":{\"type\":\"string\"},\"publicReason\":{\"minLength\":1,\"pattern\":\"^[^\\\\u0000-\\\\u001F\\\\u007F-\\\\u009F]*[^\\\\u0000-\\\\u0020\\\\u007F-\\\\u00A0\\\\u1680\\\\u2000-\\\\u200A\\\\u2028\\\\u2029\\\\u202F\\\\u205F\\\\u3000][^\\\\u0000-\\\\u001F\\\\u007F-\\\\u009F]*$\",\"type\":\"string\"},\"status\":{\"enum\":[\"approved\",\"rejected\",\"changes-requested\",\"answered\"]}},\"required\":[\"status\",\"decidedAt\"],\"type\":\"object\"},\"effectDigest\":{\"type\":\"string\"},\"handoffRefusal\":{\"additionalProperties\":false,\"properties\":{\"code\":{\"enum\":[\"review.initiator-required\",\"review.initiator-excluded\",\"review.policy-mismatch\",\"review.refused\"]}},\"required\":[\"code\"],\"type\":\"object\"},\"id\":{\"type\":\"string\"},\"input\":{\"type\":\"object\"},\"links\":{\"additionalProperties\":{\"additionalProperties\":false,\"properties\":{\"accessProfile\":{\"type\":\"string\"},\"availability\":{\"additionalProperties\":false,\"if\":{\"properties\":{\"available\":{\"const\":false}}},\"properties\":{\"available\":{\"type\":\"boolean\"},\"observedRevision\":{\"minimum\":1,\"type\":\"integer\"},\"reason\":{\"enum\":[\"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\":{\"enum\":[\"refresh\",\"revise\",\"retry\",\"rebase\",\"correct-input\",\"receipt-only\"]}},\"required\":[\"available\",\"observedRevision\"],\"then\":{\"required\":[\"reason\",\"recovery\"]},\"type\":\"object\"},\"ifMatch\":{\"type\":\"string\"},\"method\":{\"enum\":[\"GET\",\"POST\"]},\"operation\":{\"type\":\"string\"},\"path\":{\"type\":\"string\"}},\"required\":[\"method\",\"path\",\"accessProfile\",\"operation\"],\"type\":\"object\"},\"type\":\"object\"},\"partyRole\":{\"enum\":[\"owner\",\"subject\"]},\"revision\":{\"minimum\":1,\"type\":\"integer\"},\"state\":{\"enum\":[\"draft\",\"submitted\",\"applied\",\"cancelled\",\"rejected\"]},\"status\":{\"enum\":[\"draft\",\"awaiting-party\",\"in-review\",\"approved\",\"processing\",\"applied\",\"rejected\",\"cancelled\"]},\"submissionVersion\":{\"minimum\":0,\"type\":\"integer\"},\"title\":{\"maxLength\":1024,\"type\":\"string\"},\"turn\":{\"enum\":[\"party\",\"official\",\"nobody\"]}},\"required\":[\"id\",\"actionId\",\"actionRevision\",\"submissionVersion\",\"revision\",\"state\",\"turn\",\"links\"],\"type\":\"object\"}")], ["/paths/~1v1~1proposals~1{proposal_id}/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}/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}/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}/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}/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}/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}~1apply/post/responses/200/content/application~1json/schema", JSON.parse("{\"additionalProperties\":false,\"properties\":{\"actionId\":{\"type\":\"string\"},\"actionRevision\":{\"type\":\"string\"},\"application\":{\"additionalProperties\":false,\"properties\":{\"applicationId\":{\"type\":\"string\"},\"effectDigest\":{\"pattern\":\"^sha256:[0-9a-f]{64}$\",\"type\":\"string\"},\"resultLinks\":{\"items\":{\"additionalProperties\":false,\"properties\":{\"recordId\":{\"type\":\"string\"},\"recordType\":{\"type\":\"string\"},\"revision\":{\"minimum\":1,\"type\":\"integer\"}},\"required\":[\"recordType\",\"recordId\",\"revision\"],\"type\":\"object\"},\"maxItems\":16,\"type\":\"array\"},\"submissionVersion\":{\"minimum\":1,\"type\":\"integer\"}},\"required\":[\"applicationId\",\"submissionVersion\",\"effectDigest\",\"resultLinks\"],\"type\":\"object\"},\"applicationStatus\":{\"additionalProperties\":false,\"properties\":{\"automaticRetry\":{\"additionalProperties\":false,\"properties\":{\"attempts\":{\"maximum\":1000,\"minimum\":0,\"type\":\"integer\"},\"maximumAttempts\":{\"maximum\":1000,\"minimum\":1,\"type\":\"integer\"},\"scheduled\":{\"type\":\"boolean\"}},\"required\":[\"scheduled\",\"attempts\",\"maximumAttempts\"],\"type\":\"object\"},\"mode\":{\"enum\":[\"automatic\",\"manual\"]},\"reason\":{\"enum\":[\"package-changed\",\"dependency-outage\",\"lease-expired\",\"application-refused\",\"attempts-exhausted\"]},\"recovery\":{\"enum\":[\"retry\",\"rebase\",\"revise\",\"correct-input\"]},\"state\":{\"enum\":[\"awaiting-review\",\"pending\",\"applying\",\"blocked\",\"applied\",\"cancelled\",\"rejected\"]}},\"required\":[\"state\",\"mode\"],\"type\":\"object\"},\"asks\":{\"items\":{\"additionalProperties\":false,\"properties\":{\"answer\":{\"additionalProperties\":false,\"properties\":{\"additions\":{\"items\":{\"type\":\"string\"},\"maxItems\":32,\"type\":\"array\",\"uniqueItems\":true},\"answeredAt\":{\"type\":\"string\"},\"text\":{\"maxLength\":2000,\"minLength\":1,\"type\":\"string\"}},\"required\":[\"additions\",\"answeredAt\"],\"type\":\"object\"},\"askedAt\":{\"type\":\"string\"},\"dueAt\":{\"type\":\"string\"},\"id\":{\"type\":\"string\"},\"links\":{\"additionalProperties\":false,\"properties\":{\"answer\":{\"additionalProperties\":false,\"properties\":{\"accessProfile\":{\"type\":\"string\"},\"availability\":{\"additionalProperties\":false,\"if\":{\"properties\":{\"available\":{\"const\":false}}},\"properties\":{\"available\":{\"type\":\"boolean\"},\"observedRevision\":{\"minimum\":1,\"type\":\"integer\"},\"reason\":{\"enum\":[\"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\":{\"enum\":[\"refresh\",\"revise\",\"retry\",\"rebase\",\"correct-input\",\"receipt-only\"]}},\"required\":[\"available\",\"observedRevision\"],\"then\":{\"required\":[\"reason\",\"recovery\"]},\"type\":\"object\"},\"ifMatch\":{\"type\":\"string\"},\"method\":{\"const\":\"POST\"},\"operation\":{\"const\":\"answer\"},\"path\":{\"type\":\"string\"}},\"required\":[\"method\",\"path\",\"accessProfile\",\"operation\",\"ifMatch\",\"availability\"],\"type\":\"object\"}},\"type\":\"object\"},\"state\":{\"enum\":[\"open\",\"answered\",\"expired\",\"closed\"]},\"text\":{\"maxLength\":2000,\"minLength\":1,\"type\":\"string\"},\"wants\":{\"items\":{\"additionalProperties\":false,\"properties\":{\"kind\":{\"enum\":[\"answer\",\"document\"]}},\"required\":[\"kind\"],\"type\":\"object\"},\"maxItems\":8,\"type\":\"array\",\"uniqueItems\":true}},\"required\":[\"id\",\"text\",\"wants\",\"askedAt\",\"state\",\"links\"],\"type\":\"object\"},\"maxItems\":50,\"type\":\"array\"},\"attachments\":{\"additionalProperties\":{\"additionalProperties\":false,\"properties\":{\"classification\":{\"enum\":[\"public\",\"internal\",\"restricted\"]},\"contentTypes\":{\"items\":{\"type\":\"string\"},\"maxItems\":16,\"minItems\":1,\"type\":\"array\",\"uniqueItems\":true},\"id\":{\"type\":\"string\"},\"links\":{\"additionalProperties\":{\"additionalProperties\":false,\"properties\":{\"accessProfile\":{\"type\":\"string\"},\"availability\":{\"additionalProperties\":false,\"if\":{\"properties\":{\"available\":{\"const\":false}}},\"properties\":{\"available\":{\"type\":\"boolean\"},\"observedRevision\":{\"minimum\":1,\"type\":\"integer\"},\"reason\":{\"enum\":[\"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\":{\"enum\":[\"refresh\",\"revise\",\"retry\",\"rebase\",\"correct-input\",\"receipt-only\"]}},\"required\":[\"available\",\"observedRevision\"],\"then\":{\"required\":[\"reason\",\"recovery\"]},\"type\":\"object\"},\"ifMatch\":{\"type\":\"string\"},\"method\":{\"enum\":[\"GET\",\"PATCH\",\"DELETE\"]},\"operation\":{\"enum\":[\"download\",\"upload\",\"remove\"]},\"path\":{\"type\":\"string\"}},\"required\":[\"method\",\"path\",\"accessProfile\",\"operation\"],\"type\":\"object\"},\"type\":\"object\"},\"maximumBytes\":{\"maximum\":16777216,\"minimum\":1,\"type\":\"integer\"},\"required\":{\"type\":\"boolean\"},\"value\":{\"additionalProperties\":false,\"properties\":{\"byteSize\":{\"minimum\":1,\"type\":\"integer\"},\"contentType\":{\"type\":\"string\"},\"sha256\":{\"pattern\":\"^[a-f0-9]{64}$\",\"type\":\"string\"},\"submissionVersion\":{\"minimum\":0,\"type\":\"integer\"},\"uploadedAt\":{\"type\":\"string\"},\"verificationStatus\":{\"enum\":[\"notRequired\",\"pending\",\"approved\",\"rejected\"]}},\"required\":[\"submissionVersion\",\"sha256\",\"contentType\",\"byteSize\",\"verificationStatus\"],\"type\":\"object\"}},\"required\":[\"id\",\"required\",\"maximumBytes\",\"contentTypes\",\"classification\",\"links\"],\"type\":\"object\"},\"maxProperties\":8,\"type\":\"object\"},\"blockedReason\":{\"enum\":[\"package-changed\"]},\"createdAt\":{\"type\":\"string\"},\"decision\":{\"additionalProperties\":false,\"properties\":{\"decidedAt\":{\"type\":\"string\"},\"publicReason\":{\"minLength\":1,\"pattern\":\"^[^\\\\u0000-\\\\u001F\\\\u007F-\\\\u009F]*[^\\\\u0000-\\\\u0020\\\\u007F-\\\\u00A0\\\\u1680\\\\u2000-\\\\u200A\\\\u2028\\\\u2029\\\\u202F\\\\u205F\\\\u3000][^\\\\u0000-\\\\u001F\\\\u007F-\\\\u009F]*$\",\"type\":\"string\"},\"status\":{\"enum\":[\"approved\",\"rejected\",\"changes-requested\",\"answered\"]}},\"required\":[\"status\",\"decidedAt\"],\"type\":\"object\"},\"effectDigest\":{\"type\":\"string\"},\"handoffRefusal\":{\"additionalProperties\":false,\"properties\":{\"code\":{\"enum\":[\"review.initiator-required\",\"review.initiator-excluded\",\"review.policy-mismatch\",\"review.refused\"]}},\"required\":[\"code\"],\"type\":\"object\"},\"id\":{\"type\":\"string\"},\"input\":{\"type\":\"object\"},\"links\":{\"additionalProperties\":{\"additionalProperties\":false,\"properties\":{\"accessProfile\":{\"type\":\"string\"},\"availability\":{\"additionalProperties\":false,\"if\":{\"properties\":{\"available\":{\"const\":false}}},\"properties\":{\"available\":{\"type\":\"boolean\"},\"observedRevision\":{\"minimum\":1,\"type\":\"integer\"},\"reason\":{\"enum\":[\"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\":{\"enum\":[\"refresh\",\"revise\",\"retry\",\"rebase\",\"correct-input\",\"receipt-only\"]}},\"required\":[\"available\",\"observedRevision\"],\"then\":{\"required\":[\"reason\",\"recovery\"]},\"type\":\"object\"},\"ifMatch\":{\"type\":\"string\"},\"method\":{\"enum\":[\"GET\",\"POST\"]},\"operation\":{\"type\":\"string\"},\"path\":{\"type\":\"string\"}},\"required\":[\"method\",\"path\",\"accessProfile\",\"operation\"],\"type\":\"object\"},\"type\":\"object\"},\"revision\":{\"minimum\":1,\"type\":\"integer\"},\"state\":{\"enum\":[\"draft\",\"submitted\",\"applied\",\"cancelled\",\"rejected\"]},\"status\":{\"enum\":[\"draft\",\"awaiting-party\",\"in-review\",\"approved\",\"processing\",\"applied\",\"rejected\",\"cancelled\"]},\"submissionVersion\":{\"minimum\":0,\"type\":\"integer\"},\"title\":{\"maxLength\":1024,\"type\":\"string\"},\"turn\":{\"enum\":[\"party\",\"official\",\"nobody\"]}},\"required\":[\"id\",\"actionId\",\"actionRevision\",\"submissionVersion\",\"revision\",\"state\",\"turn\",\"links\"],\"type\":\"object\"}")], + ["/paths/~1v1~1proposals~1{proposal_id}~1apply/post/responses/200/content/application~1json/schema", JSON.parse("{\"additionalProperties\":false,\"properties\":{\"actionId\":{\"type\":\"string\"},\"actionRevision\":{\"type\":\"string\"},\"application\":{\"additionalProperties\":false,\"properties\":{\"applicationId\":{\"type\":\"string\"},\"effectDigest\":{\"pattern\":\"^sha256:[0-9a-f]{64}$\",\"type\":\"string\"},\"resultLinks\":{\"items\":{\"additionalProperties\":false,\"properties\":{\"recordId\":{\"type\":\"string\"},\"recordType\":{\"type\":\"string\"},\"revision\":{\"minimum\":1,\"type\":\"integer\"}},\"required\":[\"recordType\",\"recordId\",\"revision\"],\"type\":\"object\"},\"maxItems\":16,\"type\":\"array\"},\"submissionVersion\":{\"minimum\":1,\"type\":\"integer\"}},\"required\":[\"applicationId\",\"submissionVersion\",\"effectDigest\",\"resultLinks\"],\"type\":\"object\"},\"applicationStatus\":{\"additionalProperties\":false,\"properties\":{\"automaticRetry\":{\"additionalProperties\":false,\"properties\":{\"attempts\":{\"maximum\":1000,\"minimum\":0,\"type\":\"integer\"},\"maximumAttempts\":{\"maximum\":1000,\"minimum\":1,\"type\":\"integer\"},\"scheduled\":{\"type\":\"boolean\"}},\"required\":[\"scheduled\",\"attempts\",\"maximumAttempts\"],\"type\":\"object\"},\"mode\":{\"enum\":[\"automatic\",\"manual\"]},\"reason\":{\"enum\":[\"package-changed\",\"dependency-outage\",\"lease-expired\",\"application-refused\",\"attempts-exhausted\"]},\"recovery\":{\"enum\":[\"retry\",\"rebase\",\"revise\",\"correct-input\"]},\"state\":{\"enum\":[\"awaiting-review\",\"pending\",\"applying\",\"blocked\",\"applied\",\"cancelled\",\"rejected\"]}},\"required\":[\"state\",\"mode\"],\"type\":\"object\"},\"asks\":{\"items\":{\"additionalProperties\":false,\"properties\":{\"answer\":{\"additionalProperties\":false,\"properties\":{\"additions\":{\"items\":{\"type\":\"string\"},\"maxItems\":32,\"type\":\"array\",\"uniqueItems\":true},\"answeredAt\":{\"type\":\"string\"},\"formEntries\":{\"items\":{\"type\":\"string\"},\"maxItems\":32,\"type\":\"array\",\"uniqueItems\":true},\"text\":{\"maxLength\":2000,\"minLength\":1,\"type\":\"string\"}},\"required\":[\"additions\",\"answeredAt\"],\"type\":\"object\"},\"askedAt\":{\"type\":\"string\"},\"dueAt\":{\"type\":\"string\"},\"id\":{\"type\":\"string\"},\"links\":{\"additionalProperties\":false,\"properties\":{\"answer\":{\"additionalProperties\":false,\"properties\":{\"accessProfile\":{\"type\":\"string\"},\"availability\":{\"additionalProperties\":false,\"if\":{\"properties\":{\"available\":{\"const\":false}}},\"properties\":{\"available\":{\"type\":\"boolean\"},\"observedRevision\":{\"minimum\":1,\"type\":\"integer\"},\"reason\":{\"enum\":[\"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\":{\"enum\":[\"refresh\",\"revise\",\"retry\",\"rebase\",\"correct-input\",\"receipt-only\"]}},\"required\":[\"available\",\"observedRevision\"],\"then\":{\"required\":[\"reason\",\"recovery\"]},\"type\":\"object\"},\"ifMatch\":{\"type\":\"string\"},\"method\":{\"const\":\"POST\"},\"operation\":{\"const\":\"answer\"},\"path\":{\"type\":\"string\"}},\"required\":[\"method\",\"path\",\"accessProfile\",\"operation\",\"ifMatch\",\"availability\"],\"type\":\"object\"}},\"type\":\"object\"},\"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\",\"links\"],\"type\":\"object\"},\"maxItems\":50,\"type\":\"array\"},\"attachments\":{\"additionalProperties\":{\"additionalProperties\":false,\"properties\":{\"classification\":{\"enum\":[\"public\",\"internal\",\"restricted\"]},\"contentTypes\":{\"items\":{\"type\":\"string\"},\"maxItems\":16,\"minItems\":1,\"type\":\"array\",\"uniqueItems\":true},\"id\":{\"type\":\"string\"},\"links\":{\"additionalProperties\":{\"additionalProperties\":false,\"properties\":{\"accessProfile\":{\"type\":\"string\"},\"availability\":{\"additionalProperties\":false,\"if\":{\"properties\":{\"available\":{\"const\":false}}},\"properties\":{\"available\":{\"type\":\"boolean\"},\"observedRevision\":{\"minimum\":1,\"type\":\"integer\"},\"reason\":{\"enum\":[\"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\":{\"enum\":[\"refresh\",\"revise\",\"retry\",\"rebase\",\"correct-input\",\"receipt-only\"]}},\"required\":[\"available\",\"observedRevision\"],\"then\":{\"required\":[\"reason\",\"recovery\"]},\"type\":\"object\"},\"ifMatch\":{\"type\":\"string\"},\"method\":{\"enum\":[\"GET\",\"PATCH\",\"DELETE\"]},\"operation\":{\"enum\":[\"download\",\"upload\",\"remove\"]},\"path\":{\"type\":\"string\"}},\"required\":[\"method\",\"path\",\"accessProfile\",\"operation\"],\"type\":\"object\"},\"type\":\"object\"},\"maximumBytes\":{\"maximum\":16777216,\"minimum\":1,\"type\":\"integer\"},\"required\":{\"type\":\"boolean\"},\"value\":{\"additionalProperties\":false,\"properties\":{\"byteSize\":{\"minimum\":1,\"type\":\"integer\"},\"contentType\":{\"type\":\"string\"},\"sha256\":{\"pattern\":\"^[a-f0-9]{64}$\",\"type\":\"string\"},\"submissionVersion\":{\"minimum\":0,\"type\":\"integer\"},\"uploadedAt\":{\"type\":\"string\"},\"verificationStatus\":{\"enum\":[\"notRequired\",\"pending\",\"approved\",\"rejected\"]}},\"required\":[\"submissionVersion\",\"sha256\",\"contentType\",\"byteSize\",\"verificationStatus\"],\"type\":\"object\"}},\"required\":[\"id\",\"required\",\"maximumBytes\",\"contentTypes\",\"classification\",\"links\"],\"type\":\"object\"},\"maxProperties\":8,\"type\":\"object\"},\"blockedReason\":{\"enum\":[\"package-changed\"]},\"createdAt\":{\"type\":\"string\"},\"decision\":{\"additionalProperties\":false,\"properties\":{\"decidedAt\":{\"type\":\"string\"},\"publicReason\":{\"minLength\":1,\"pattern\":\"^[^\\\\u0000-\\\\u001F\\\\u007F-\\\\u009F]*[^\\\\u0000-\\\\u0020\\\\u007F-\\\\u00A0\\\\u1680\\\\u2000-\\\\u200A\\\\u2028\\\\u2029\\\\u202F\\\\u205F\\\\u3000][^\\\\u0000-\\\\u001F\\\\u007F-\\\\u009F]*$\",\"type\":\"string\"},\"status\":{\"enum\":[\"approved\",\"rejected\",\"changes-requested\",\"answered\"]}},\"required\":[\"status\",\"decidedAt\"],\"type\":\"object\"},\"effectDigest\":{\"type\":\"string\"},\"handoffRefusal\":{\"additionalProperties\":false,\"properties\":{\"code\":{\"enum\":[\"review.initiator-required\",\"review.initiator-excluded\",\"review.policy-mismatch\",\"review.refused\"]}},\"required\":[\"code\"],\"type\":\"object\"},\"id\":{\"type\":\"string\"},\"input\":{\"type\":\"object\"},\"links\":{\"additionalProperties\":{\"additionalProperties\":false,\"properties\":{\"accessProfile\":{\"type\":\"string\"},\"availability\":{\"additionalProperties\":false,\"if\":{\"properties\":{\"available\":{\"const\":false}}},\"properties\":{\"available\":{\"type\":\"boolean\"},\"observedRevision\":{\"minimum\":1,\"type\":\"integer\"},\"reason\":{\"enum\":[\"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\":{\"enum\":[\"refresh\",\"revise\",\"retry\",\"rebase\",\"correct-input\",\"receipt-only\"]}},\"required\":[\"available\",\"observedRevision\"],\"then\":{\"required\":[\"reason\",\"recovery\"]},\"type\":\"object\"},\"ifMatch\":{\"type\":\"string\"},\"method\":{\"enum\":[\"GET\",\"POST\"]},\"operation\":{\"type\":\"string\"},\"path\":{\"type\":\"string\"}},\"required\":[\"method\",\"path\",\"accessProfile\",\"operation\"],\"type\":\"object\"},\"type\":\"object\"},\"partyRole\":{\"enum\":[\"owner\",\"subject\"]},\"revision\":{\"minimum\":1,\"type\":\"integer\"},\"state\":{\"enum\":[\"draft\",\"submitted\",\"applied\",\"cancelled\",\"rejected\"]},\"status\":{\"enum\":[\"draft\",\"awaiting-party\",\"in-review\",\"approved\",\"processing\",\"applied\",\"rejected\",\"cancelled\"]},\"submissionVersion\":{\"minimum\":0,\"type\":\"integer\"},\"title\":{\"maxLength\":1024,\"type\":\"string\"},\"turn\":{\"enum\":[\"party\",\"official\",\"nobody\"]}},\"required\":[\"id\",\"actionId\",\"actionRevision\",\"submissionVersion\",\"revision\",\"state\",\"turn\",\"links\"],\"type\":\"object\"}")], ["/paths/~1v1~1proposals~1{proposal_id}~1apply/post/responses/400/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"access-profile.ambiguous\",\"request.invalid\"]}},\"type\":\"object\"}]}")], ["/paths/~1v1~1proposals~1{proposal_id}~1apply/post/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}~1apply/post/responses/403/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"profile.not-authorized\"]}},\"type\":\"object\"}]}")], @@ -193,7 +197,7 @@ const rules: Record = Object.fromEntries([ ["/paths/~1v1~1proposals~1{proposal_id}~1apply/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}~1apply/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}~1apply/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}~1attachments~1supporting-document/delete/responses/200/content/application~1json/schema", JSON.parse("{\"additionalProperties\":false,\"properties\":{\"actionId\":{\"type\":\"string\"},\"actionRevision\":{\"type\":\"string\"},\"application\":{\"additionalProperties\":false,\"properties\":{\"applicationId\":{\"type\":\"string\"},\"effectDigest\":{\"pattern\":\"^sha256:[0-9a-f]{64}$\",\"type\":\"string\"},\"resultLinks\":{\"items\":{\"additionalProperties\":false,\"properties\":{\"recordId\":{\"type\":\"string\"},\"recordType\":{\"type\":\"string\"},\"revision\":{\"minimum\":1,\"type\":\"integer\"}},\"required\":[\"recordType\",\"recordId\",\"revision\"],\"type\":\"object\"},\"maxItems\":16,\"type\":\"array\"},\"submissionVersion\":{\"minimum\":1,\"type\":\"integer\"}},\"required\":[\"applicationId\",\"submissionVersion\",\"effectDigest\",\"resultLinks\"],\"type\":\"object\"},\"applicationStatus\":{\"additionalProperties\":false,\"properties\":{\"automaticRetry\":{\"additionalProperties\":false,\"properties\":{\"attempts\":{\"maximum\":1000,\"minimum\":0,\"type\":\"integer\"},\"maximumAttempts\":{\"maximum\":1000,\"minimum\":1,\"type\":\"integer\"},\"scheduled\":{\"type\":\"boolean\"}},\"required\":[\"scheduled\",\"attempts\",\"maximumAttempts\"],\"type\":\"object\"},\"mode\":{\"enum\":[\"automatic\",\"manual\"]},\"reason\":{\"enum\":[\"package-changed\",\"dependency-outage\",\"lease-expired\",\"application-refused\",\"attempts-exhausted\"]},\"recovery\":{\"enum\":[\"retry\",\"rebase\",\"revise\",\"correct-input\"]},\"state\":{\"enum\":[\"awaiting-review\",\"pending\",\"applying\",\"blocked\",\"applied\",\"cancelled\",\"rejected\"]}},\"required\":[\"state\",\"mode\"],\"type\":\"object\"},\"asks\":{\"items\":{\"additionalProperties\":false,\"properties\":{\"answer\":{\"additionalProperties\":false,\"properties\":{\"additions\":{\"items\":{\"type\":\"string\"},\"maxItems\":32,\"type\":\"array\",\"uniqueItems\":true},\"answeredAt\":{\"type\":\"string\"},\"text\":{\"maxLength\":2000,\"minLength\":1,\"type\":\"string\"}},\"required\":[\"additions\",\"answeredAt\"],\"type\":\"object\"},\"askedAt\":{\"type\":\"string\"},\"dueAt\":{\"type\":\"string\"},\"id\":{\"type\":\"string\"},\"links\":{\"additionalProperties\":false,\"properties\":{\"answer\":{\"additionalProperties\":false,\"properties\":{\"accessProfile\":{\"type\":\"string\"},\"availability\":{\"additionalProperties\":false,\"if\":{\"properties\":{\"available\":{\"const\":false}}},\"properties\":{\"available\":{\"type\":\"boolean\"},\"observedRevision\":{\"minimum\":1,\"type\":\"integer\"},\"reason\":{\"enum\":[\"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\":{\"enum\":[\"refresh\",\"revise\",\"retry\",\"rebase\",\"correct-input\",\"receipt-only\"]}},\"required\":[\"available\",\"observedRevision\"],\"then\":{\"required\":[\"reason\",\"recovery\"]},\"type\":\"object\"},\"ifMatch\":{\"type\":\"string\"},\"method\":{\"const\":\"POST\"},\"operation\":{\"const\":\"answer\"},\"path\":{\"type\":\"string\"}},\"required\":[\"method\",\"path\",\"accessProfile\",\"operation\",\"ifMatch\",\"availability\"],\"type\":\"object\"}},\"type\":\"object\"},\"state\":{\"enum\":[\"open\",\"answered\",\"expired\",\"closed\"]},\"text\":{\"maxLength\":2000,\"minLength\":1,\"type\":\"string\"},\"wants\":{\"items\":{\"additionalProperties\":false,\"properties\":{\"kind\":{\"enum\":[\"answer\",\"document\"]}},\"required\":[\"kind\"],\"type\":\"object\"},\"maxItems\":8,\"type\":\"array\",\"uniqueItems\":true}},\"required\":[\"id\",\"text\",\"wants\",\"askedAt\",\"state\",\"links\"],\"type\":\"object\"},\"maxItems\":50,\"type\":\"array\"},\"attachments\":{\"additionalProperties\":{\"additionalProperties\":false,\"properties\":{\"classification\":{\"enum\":[\"public\",\"internal\",\"restricted\"]},\"contentTypes\":{\"items\":{\"type\":\"string\"},\"maxItems\":16,\"minItems\":1,\"type\":\"array\",\"uniqueItems\":true},\"id\":{\"type\":\"string\"},\"links\":{\"additionalProperties\":{\"additionalProperties\":false,\"properties\":{\"accessProfile\":{\"type\":\"string\"},\"availability\":{\"additionalProperties\":false,\"if\":{\"properties\":{\"available\":{\"const\":false}}},\"properties\":{\"available\":{\"type\":\"boolean\"},\"observedRevision\":{\"minimum\":1,\"type\":\"integer\"},\"reason\":{\"enum\":[\"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\":{\"enum\":[\"refresh\",\"revise\",\"retry\",\"rebase\",\"correct-input\",\"receipt-only\"]}},\"required\":[\"available\",\"observedRevision\"],\"then\":{\"required\":[\"reason\",\"recovery\"]},\"type\":\"object\"},\"ifMatch\":{\"type\":\"string\"},\"method\":{\"enum\":[\"GET\",\"PATCH\",\"DELETE\"]},\"operation\":{\"enum\":[\"download\",\"upload\",\"remove\"]},\"path\":{\"type\":\"string\"}},\"required\":[\"method\",\"path\",\"accessProfile\",\"operation\"],\"type\":\"object\"},\"type\":\"object\"},\"maximumBytes\":{\"maximum\":16777216,\"minimum\":1,\"type\":\"integer\"},\"required\":{\"type\":\"boolean\"},\"value\":{\"additionalProperties\":false,\"properties\":{\"byteSize\":{\"minimum\":1,\"type\":\"integer\"},\"contentType\":{\"type\":\"string\"},\"sha256\":{\"pattern\":\"^[a-f0-9]{64}$\",\"type\":\"string\"},\"submissionVersion\":{\"minimum\":0,\"type\":\"integer\"},\"uploadedAt\":{\"type\":\"string\"},\"verificationStatus\":{\"enum\":[\"notRequired\",\"pending\",\"approved\",\"rejected\"]}},\"required\":[\"submissionVersion\",\"sha256\",\"contentType\",\"byteSize\",\"verificationStatus\"],\"type\":\"object\"}},\"required\":[\"id\",\"required\",\"maximumBytes\",\"contentTypes\",\"classification\",\"links\"],\"type\":\"object\"},\"maxProperties\":8,\"type\":\"object\"},\"blockedReason\":{\"enum\":[\"package-changed\"]},\"createdAt\":{\"type\":\"string\"},\"decision\":{\"additionalProperties\":false,\"properties\":{\"decidedAt\":{\"type\":\"string\"},\"publicReason\":{\"minLength\":1,\"pattern\":\"^[^\\\\u0000-\\\\u001F\\\\u007F-\\\\u009F]*[^\\\\u0000-\\\\u0020\\\\u007F-\\\\u00A0\\\\u1680\\\\u2000-\\\\u200A\\\\u2028\\\\u2029\\\\u202F\\\\u205F\\\\u3000][^\\\\u0000-\\\\u001F\\\\u007F-\\\\u009F]*$\",\"type\":\"string\"},\"status\":{\"enum\":[\"approved\",\"rejected\",\"changes-requested\",\"answered\"]}},\"required\":[\"status\",\"decidedAt\"],\"type\":\"object\"},\"effectDigest\":{\"type\":\"string\"},\"handoffRefusal\":{\"additionalProperties\":false,\"properties\":{\"code\":{\"enum\":[\"review.initiator-required\",\"review.initiator-excluded\",\"review.policy-mismatch\",\"review.refused\"]}},\"required\":[\"code\"],\"type\":\"object\"},\"id\":{\"type\":\"string\"},\"input\":{\"type\":\"object\"},\"links\":{\"additionalProperties\":{\"additionalProperties\":false,\"properties\":{\"accessProfile\":{\"type\":\"string\"},\"availability\":{\"additionalProperties\":false,\"if\":{\"properties\":{\"available\":{\"const\":false}}},\"properties\":{\"available\":{\"type\":\"boolean\"},\"observedRevision\":{\"minimum\":1,\"type\":\"integer\"},\"reason\":{\"enum\":[\"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\":{\"enum\":[\"refresh\",\"revise\",\"retry\",\"rebase\",\"correct-input\",\"receipt-only\"]}},\"required\":[\"available\",\"observedRevision\"],\"then\":{\"required\":[\"reason\",\"recovery\"]},\"type\":\"object\"},\"ifMatch\":{\"type\":\"string\"},\"method\":{\"enum\":[\"GET\",\"POST\"]},\"operation\":{\"type\":\"string\"},\"path\":{\"type\":\"string\"}},\"required\":[\"method\",\"path\",\"accessProfile\",\"operation\"],\"type\":\"object\"},\"type\":\"object\"},\"revision\":{\"minimum\":1,\"type\":\"integer\"},\"state\":{\"enum\":[\"draft\",\"submitted\",\"applied\",\"cancelled\",\"rejected\"]},\"status\":{\"enum\":[\"draft\",\"awaiting-party\",\"in-review\",\"approved\",\"processing\",\"applied\",\"rejected\",\"cancelled\"]},\"submissionVersion\":{\"minimum\":0,\"type\":\"integer\"},\"title\":{\"maxLength\":1024,\"type\":\"string\"},\"turn\":{\"enum\":[\"party\",\"official\",\"nobody\"]}},\"required\":[\"id\",\"actionId\",\"actionRevision\",\"submissionVersion\",\"revision\",\"state\",\"turn\",\"links\"],\"type\":\"object\"}")], + ["/paths/~1v1~1proposals~1{proposal_id}~1attachments~1supporting-document/delete/responses/200/content/application~1json/schema", JSON.parse("{\"additionalProperties\":false,\"properties\":{\"actionId\":{\"type\":\"string\"},\"actionRevision\":{\"type\":\"string\"},\"application\":{\"additionalProperties\":false,\"properties\":{\"applicationId\":{\"type\":\"string\"},\"effectDigest\":{\"pattern\":\"^sha256:[0-9a-f]{64}$\",\"type\":\"string\"},\"resultLinks\":{\"items\":{\"additionalProperties\":false,\"properties\":{\"recordId\":{\"type\":\"string\"},\"recordType\":{\"type\":\"string\"},\"revision\":{\"minimum\":1,\"type\":\"integer\"}},\"required\":[\"recordType\",\"recordId\",\"revision\"],\"type\":\"object\"},\"maxItems\":16,\"type\":\"array\"},\"submissionVersion\":{\"minimum\":1,\"type\":\"integer\"}},\"required\":[\"applicationId\",\"submissionVersion\",\"effectDigest\",\"resultLinks\"],\"type\":\"object\"},\"applicationStatus\":{\"additionalProperties\":false,\"properties\":{\"automaticRetry\":{\"additionalProperties\":false,\"properties\":{\"attempts\":{\"maximum\":1000,\"minimum\":0,\"type\":\"integer\"},\"maximumAttempts\":{\"maximum\":1000,\"minimum\":1,\"type\":\"integer\"},\"scheduled\":{\"type\":\"boolean\"}},\"required\":[\"scheduled\",\"attempts\",\"maximumAttempts\"],\"type\":\"object\"},\"mode\":{\"enum\":[\"automatic\",\"manual\"]},\"reason\":{\"enum\":[\"package-changed\",\"dependency-outage\",\"lease-expired\",\"application-refused\",\"attempts-exhausted\"]},\"recovery\":{\"enum\":[\"retry\",\"rebase\",\"revise\",\"correct-input\"]},\"state\":{\"enum\":[\"awaiting-review\",\"pending\",\"applying\",\"blocked\",\"applied\",\"cancelled\",\"rejected\"]}},\"required\":[\"state\",\"mode\"],\"type\":\"object\"},\"asks\":{\"items\":{\"additionalProperties\":false,\"properties\":{\"answer\":{\"additionalProperties\":false,\"properties\":{\"additions\":{\"items\":{\"type\":\"string\"},\"maxItems\":32,\"type\":\"array\",\"uniqueItems\":true},\"answeredAt\":{\"type\":\"string\"},\"formEntries\":{\"items\":{\"type\":\"string\"},\"maxItems\":32,\"type\":\"array\",\"uniqueItems\":true},\"text\":{\"maxLength\":2000,\"minLength\":1,\"type\":\"string\"}},\"required\":[\"additions\",\"answeredAt\"],\"type\":\"object\"},\"askedAt\":{\"type\":\"string\"},\"dueAt\":{\"type\":\"string\"},\"id\":{\"type\":\"string\"},\"links\":{\"additionalProperties\":false,\"properties\":{\"answer\":{\"additionalProperties\":false,\"properties\":{\"accessProfile\":{\"type\":\"string\"},\"availability\":{\"additionalProperties\":false,\"if\":{\"properties\":{\"available\":{\"const\":false}}},\"properties\":{\"available\":{\"type\":\"boolean\"},\"observedRevision\":{\"minimum\":1,\"type\":\"integer\"},\"reason\":{\"enum\":[\"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\":{\"enum\":[\"refresh\",\"revise\",\"retry\",\"rebase\",\"correct-input\",\"receipt-only\"]}},\"required\":[\"available\",\"observedRevision\"],\"then\":{\"required\":[\"reason\",\"recovery\"]},\"type\":\"object\"},\"ifMatch\":{\"type\":\"string\"},\"method\":{\"const\":\"POST\"},\"operation\":{\"const\":\"answer\"},\"path\":{\"type\":\"string\"}},\"required\":[\"method\",\"path\",\"accessProfile\",\"operation\",\"ifMatch\",\"availability\"],\"type\":\"object\"}},\"type\":\"object\"},\"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\",\"links\"],\"type\":\"object\"},\"maxItems\":50,\"type\":\"array\"},\"attachments\":{\"additionalProperties\":{\"additionalProperties\":false,\"properties\":{\"classification\":{\"enum\":[\"public\",\"internal\",\"restricted\"]},\"contentTypes\":{\"items\":{\"type\":\"string\"},\"maxItems\":16,\"minItems\":1,\"type\":\"array\",\"uniqueItems\":true},\"id\":{\"type\":\"string\"},\"links\":{\"additionalProperties\":{\"additionalProperties\":false,\"properties\":{\"accessProfile\":{\"type\":\"string\"},\"availability\":{\"additionalProperties\":false,\"if\":{\"properties\":{\"available\":{\"const\":false}}},\"properties\":{\"available\":{\"type\":\"boolean\"},\"observedRevision\":{\"minimum\":1,\"type\":\"integer\"},\"reason\":{\"enum\":[\"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\":{\"enum\":[\"refresh\",\"revise\",\"retry\",\"rebase\",\"correct-input\",\"receipt-only\"]}},\"required\":[\"available\",\"observedRevision\"],\"then\":{\"required\":[\"reason\",\"recovery\"]},\"type\":\"object\"},\"ifMatch\":{\"type\":\"string\"},\"method\":{\"enum\":[\"GET\",\"PATCH\",\"DELETE\"]},\"operation\":{\"enum\":[\"download\",\"upload\",\"remove\"]},\"path\":{\"type\":\"string\"}},\"required\":[\"method\",\"path\",\"accessProfile\",\"operation\"],\"type\":\"object\"},\"type\":\"object\"},\"maximumBytes\":{\"maximum\":16777216,\"minimum\":1,\"type\":\"integer\"},\"required\":{\"type\":\"boolean\"},\"value\":{\"additionalProperties\":false,\"properties\":{\"byteSize\":{\"minimum\":1,\"type\":\"integer\"},\"contentType\":{\"type\":\"string\"},\"sha256\":{\"pattern\":\"^[a-f0-9]{64}$\",\"type\":\"string\"},\"submissionVersion\":{\"minimum\":0,\"type\":\"integer\"},\"uploadedAt\":{\"type\":\"string\"},\"verificationStatus\":{\"enum\":[\"notRequired\",\"pending\",\"approved\",\"rejected\"]}},\"required\":[\"submissionVersion\",\"sha256\",\"contentType\",\"byteSize\",\"verificationStatus\"],\"type\":\"object\"}},\"required\":[\"id\",\"required\",\"maximumBytes\",\"contentTypes\",\"classification\",\"links\"],\"type\":\"object\"},\"maxProperties\":8,\"type\":\"object\"},\"blockedReason\":{\"enum\":[\"package-changed\"]},\"createdAt\":{\"type\":\"string\"},\"decision\":{\"additionalProperties\":false,\"properties\":{\"decidedAt\":{\"type\":\"string\"},\"publicReason\":{\"minLength\":1,\"pattern\":\"^[^\\\\u0000-\\\\u001F\\\\u007F-\\\\u009F]*[^\\\\u0000-\\\\u0020\\\\u007F-\\\\u00A0\\\\u1680\\\\u2000-\\\\u200A\\\\u2028\\\\u2029\\\\u202F\\\\u205F\\\\u3000][^\\\\u0000-\\\\u001F\\\\u007F-\\\\u009F]*$\",\"type\":\"string\"},\"status\":{\"enum\":[\"approved\",\"rejected\",\"changes-requested\",\"answered\"]}},\"required\":[\"status\",\"decidedAt\"],\"type\":\"object\"},\"effectDigest\":{\"type\":\"string\"},\"handoffRefusal\":{\"additionalProperties\":false,\"properties\":{\"code\":{\"enum\":[\"review.initiator-required\",\"review.initiator-excluded\",\"review.policy-mismatch\",\"review.refused\"]}},\"required\":[\"code\"],\"type\":\"object\"},\"id\":{\"type\":\"string\"},\"input\":{\"type\":\"object\"},\"links\":{\"additionalProperties\":{\"additionalProperties\":false,\"properties\":{\"accessProfile\":{\"type\":\"string\"},\"availability\":{\"additionalProperties\":false,\"if\":{\"properties\":{\"available\":{\"const\":false}}},\"properties\":{\"available\":{\"type\":\"boolean\"},\"observedRevision\":{\"minimum\":1,\"type\":\"integer\"},\"reason\":{\"enum\":[\"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\":{\"enum\":[\"refresh\",\"revise\",\"retry\",\"rebase\",\"correct-input\",\"receipt-only\"]}},\"required\":[\"available\",\"observedRevision\"],\"then\":{\"required\":[\"reason\",\"recovery\"]},\"type\":\"object\"},\"ifMatch\":{\"type\":\"string\"},\"method\":{\"enum\":[\"GET\",\"POST\"]},\"operation\":{\"type\":\"string\"},\"path\":{\"type\":\"string\"}},\"required\":[\"method\",\"path\",\"accessProfile\",\"operation\"],\"type\":\"object\"},\"type\":\"object\"},\"partyRole\":{\"enum\":[\"owner\",\"subject\"]},\"revision\":{\"minimum\":1,\"type\":\"integer\"},\"state\":{\"enum\":[\"draft\",\"submitted\",\"applied\",\"cancelled\",\"rejected\"]},\"status\":{\"enum\":[\"draft\",\"awaiting-party\",\"in-review\",\"approved\",\"processing\",\"applied\",\"rejected\",\"cancelled\"]},\"submissionVersion\":{\"minimum\":0,\"type\":\"integer\"},\"title\":{\"maxLength\":1024,\"type\":\"string\"},\"turn\":{\"enum\":[\"party\",\"official\",\"nobody\"]}},\"required\":[\"id\",\"actionId\",\"actionRevision\",\"submissionVersion\",\"revision\",\"state\",\"turn\",\"links\"],\"type\":\"object\"}")], ["/paths/~1v1~1proposals~1{proposal_id}~1attachments~1supporting-document/delete/responses/400/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"access-profile.ambiguous\",\"request.invalid\"]}},\"type\":\"object\"}]}")], ["/paths/~1v1~1proposals~1{proposal_id}~1attachments~1supporting-document/delete/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}~1attachments~1supporting-document/delete/responses/403/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"profile.not-authorized\"]}},\"type\":\"object\"}]}")], @@ -210,7 +214,7 @@ const rules: Record = Object.fromEntries([ ["/paths/~1v1~1proposals~1{proposal_id}~1attachments~1supporting-document/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}~1attachments~1supporting-document/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}~1attachments~1supporting-document/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}~1attachments~1supporting-document/patch/responses/200/content/application~1json/schema", JSON.parse("{\"additionalProperties\":false,\"properties\":{\"actionId\":{\"type\":\"string\"},\"actionRevision\":{\"type\":\"string\"},\"application\":{\"additionalProperties\":false,\"properties\":{\"applicationId\":{\"type\":\"string\"},\"effectDigest\":{\"pattern\":\"^sha256:[0-9a-f]{64}$\",\"type\":\"string\"},\"resultLinks\":{\"items\":{\"additionalProperties\":false,\"properties\":{\"recordId\":{\"type\":\"string\"},\"recordType\":{\"type\":\"string\"},\"revision\":{\"minimum\":1,\"type\":\"integer\"}},\"required\":[\"recordType\",\"recordId\",\"revision\"],\"type\":\"object\"},\"maxItems\":16,\"type\":\"array\"},\"submissionVersion\":{\"minimum\":1,\"type\":\"integer\"}},\"required\":[\"applicationId\",\"submissionVersion\",\"effectDigest\",\"resultLinks\"],\"type\":\"object\"},\"applicationStatus\":{\"additionalProperties\":false,\"properties\":{\"automaticRetry\":{\"additionalProperties\":false,\"properties\":{\"attempts\":{\"maximum\":1000,\"minimum\":0,\"type\":\"integer\"},\"maximumAttempts\":{\"maximum\":1000,\"minimum\":1,\"type\":\"integer\"},\"scheduled\":{\"type\":\"boolean\"}},\"required\":[\"scheduled\",\"attempts\",\"maximumAttempts\"],\"type\":\"object\"},\"mode\":{\"enum\":[\"automatic\",\"manual\"]},\"reason\":{\"enum\":[\"package-changed\",\"dependency-outage\",\"lease-expired\",\"application-refused\",\"attempts-exhausted\"]},\"recovery\":{\"enum\":[\"retry\",\"rebase\",\"revise\",\"correct-input\"]},\"state\":{\"enum\":[\"awaiting-review\",\"pending\",\"applying\",\"blocked\",\"applied\",\"cancelled\",\"rejected\"]}},\"required\":[\"state\",\"mode\"],\"type\":\"object\"},\"asks\":{\"items\":{\"additionalProperties\":false,\"properties\":{\"answer\":{\"additionalProperties\":false,\"properties\":{\"additions\":{\"items\":{\"type\":\"string\"},\"maxItems\":32,\"type\":\"array\",\"uniqueItems\":true},\"answeredAt\":{\"type\":\"string\"},\"text\":{\"maxLength\":2000,\"minLength\":1,\"type\":\"string\"}},\"required\":[\"additions\",\"answeredAt\"],\"type\":\"object\"},\"askedAt\":{\"type\":\"string\"},\"dueAt\":{\"type\":\"string\"},\"id\":{\"type\":\"string\"},\"links\":{\"additionalProperties\":false,\"properties\":{\"answer\":{\"additionalProperties\":false,\"properties\":{\"accessProfile\":{\"type\":\"string\"},\"availability\":{\"additionalProperties\":false,\"if\":{\"properties\":{\"available\":{\"const\":false}}},\"properties\":{\"available\":{\"type\":\"boolean\"},\"observedRevision\":{\"minimum\":1,\"type\":\"integer\"},\"reason\":{\"enum\":[\"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\":{\"enum\":[\"refresh\",\"revise\",\"retry\",\"rebase\",\"correct-input\",\"receipt-only\"]}},\"required\":[\"available\",\"observedRevision\"],\"then\":{\"required\":[\"reason\",\"recovery\"]},\"type\":\"object\"},\"ifMatch\":{\"type\":\"string\"},\"method\":{\"const\":\"POST\"},\"operation\":{\"const\":\"answer\"},\"path\":{\"type\":\"string\"}},\"required\":[\"method\",\"path\",\"accessProfile\",\"operation\",\"ifMatch\",\"availability\"],\"type\":\"object\"}},\"type\":\"object\"},\"state\":{\"enum\":[\"open\",\"answered\",\"expired\",\"closed\"]},\"text\":{\"maxLength\":2000,\"minLength\":1,\"type\":\"string\"},\"wants\":{\"items\":{\"additionalProperties\":false,\"properties\":{\"kind\":{\"enum\":[\"answer\",\"document\"]}},\"required\":[\"kind\"],\"type\":\"object\"},\"maxItems\":8,\"type\":\"array\",\"uniqueItems\":true}},\"required\":[\"id\",\"text\",\"wants\",\"askedAt\",\"state\",\"links\"],\"type\":\"object\"},\"maxItems\":50,\"type\":\"array\"},\"attachments\":{\"additionalProperties\":{\"additionalProperties\":false,\"properties\":{\"classification\":{\"enum\":[\"public\",\"internal\",\"restricted\"]},\"contentTypes\":{\"items\":{\"type\":\"string\"},\"maxItems\":16,\"minItems\":1,\"type\":\"array\",\"uniqueItems\":true},\"id\":{\"type\":\"string\"},\"links\":{\"additionalProperties\":{\"additionalProperties\":false,\"properties\":{\"accessProfile\":{\"type\":\"string\"},\"availability\":{\"additionalProperties\":false,\"if\":{\"properties\":{\"available\":{\"const\":false}}},\"properties\":{\"available\":{\"type\":\"boolean\"},\"observedRevision\":{\"minimum\":1,\"type\":\"integer\"},\"reason\":{\"enum\":[\"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\":{\"enum\":[\"refresh\",\"revise\",\"retry\",\"rebase\",\"correct-input\",\"receipt-only\"]}},\"required\":[\"available\",\"observedRevision\"],\"then\":{\"required\":[\"reason\",\"recovery\"]},\"type\":\"object\"},\"ifMatch\":{\"type\":\"string\"},\"method\":{\"enum\":[\"GET\",\"PATCH\",\"DELETE\"]},\"operation\":{\"enum\":[\"download\",\"upload\",\"remove\"]},\"path\":{\"type\":\"string\"}},\"required\":[\"method\",\"path\",\"accessProfile\",\"operation\"],\"type\":\"object\"},\"type\":\"object\"},\"maximumBytes\":{\"maximum\":16777216,\"minimum\":1,\"type\":\"integer\"},\"required\":{\"type\":\"boolean\"},\"value\":{\"additionalProperties\":false,\"properties\":{\"byteSize\":{\"minimum\":1,\"type\":\"integer\"},\"contentType\":{\"type\":\"string\"},\"sha256\":{\"pattern\":\"^[a-f0-9]{64}$\",\"type\":\"string\"},\"submissionVersion\":{\"minimum\":0,\"type\":\"integer\"},\"uploadedAt\":{\"type\":\"string\"},\"verificationStatus\":{\"enum\":[\"notRequired\",\"pending\",\"approved\",\"rejected\"]}},\"required\":[\"submissionVersion\",\"sha256\",\"contentType\",\"byteSize\",\"verificationStatus\"],\"type\":\"object\"}},\"required\":[\"id\",\"required\",\"maximumBytes\",\"contentTypes\",\"classification\",\"links\"],\"type\":\"object\"},\"maxProperties\":8,\"type\":\"object\"},\"blockedReason\":{\"enum\":[\"package-changed\"]},\"createdAt\":{\"type\":\"string\"},\"decision\":{\"additionalProperties\":false,\"properties\":{\"decidedAt\":{\"type\":\"string\"},\"publicReason\":{\"minLength\":1,\"pattern\":\"^[^\\\\u0000-\\\\u001F\\\\u007F-\\\\u009F]*[^\\\\u0000-\\\\u0020\\\\u007F-\\\\u00A0\\\\u1680\\\\u2000-\\\\u200A\\\\u2028\\\\u2029\\\\u202F\\\\u205F\\\\u3000][^\\\\u0000-\\\\u001F\\\\u007F-\\\\u009F]*$\",\"type\":\"string\"},\"status\":{\"enum\":[\"approved\",\"rejected\",\"changes-requested\",\"answered\"]}},\"required\":[\"status\",\"decidedAt\"],\"type\":\"object\"},\"effectDigest\":{\"type\":\"string\"},\"handoffRefusal\":{\"additionalProperties\":false,\"properties\":{\"code\":{\"enum\":[\"review.initiator-required\",\"review.initiator-excluded\",\"review.policy-mismatch\",\"review.refused\"]}},\"required\":[\"code\"],\"type\":\"object\"},\"id\":{\"type\":\"string\"},\"input\":{\"type\":\"object\"},\"links\":{\"additionalProperties\":{\"additionalProperties\":false,\"properties\":{\"accessProfile\":{\"type\":\"string\"},\"availability\":{\"additionalProperties\":false,\"if\":{\"properties\":{\"available\":{\"const\":false}}},\"properties\":{\"available\":{\"type\":\"boolean\"},\"observedRevision\":{\"minimum\":1,\"type\":\"integer\"},\"reason\":{\"enum\":[\"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\":{\"enum\":[\"refresh\",\"revise\",\"retry\",\"rebase\",\"correct-input\",\"receipt-only\"]}},\"required\":[\"available\",\"observedRevision\"],\"then\":{\"required\":[\"reason\",\"recovery\"]},\"type\":\"object\"},\"ifMatch\":{\"type\":\"string\"},\"method\":{\"enum\":[\"GET\",\"POST\"]},\"operation\":{\"type\":\"string\"},\"path\":{\"type\":\"string\"}},\"required\":[\"method\",\"path\",\"accessProfile\",\"operation\"],\"type\":\"object\"},\"type\":\"object\"},\"revision\":{\"minimum\":1,\"type\":\"integer\"},\"state\":{\"enum\":[\"draft\",\"submitted\",\"applied\",\"cancelled\",\"rejected\"]},\"status\":{\"enum\":[\"draft\",\"awaiting-party\",\"in-review\",\"approved\",\"processing\",\"applied\",\"rejected\",\"cancelled\"]},\"submissionVersion\":{\"minimum\":0,\"type\":\"integer\"},\"title\":{\"maxLength\":1024,\"type\":\"string\"},\"turn\":{\"enum\":[\"party\",\"official\",\"nobody\"]}},\"required\":[\"id\",\"actionId\",\"actionRevision\",\"submissionVersion\",\"revision\",\"state\",\"turn\",\"links\"],\"type\":\"object\"}")], + ["/paths/~1v1~1proposals~1{proposal_id}~1attachments~1supporting-document/patch/responses/200/content/application~1json/schema", JSON.parse("{\"additionalProperties\":false,\"properties\":{\"actionId\":{\"type\":\"string\"},\"actionRevision\":{\"type\":\"string\"},\"application\":{\"additionalProperties\":false,\"properties\":{\"applicationId\":{\"type\":\"string\"},\"effectDigest\":{\"pattern\":\"^sha256:[0-9a-f]{64}$\",\"type\":\"string\"},\"resultLinks\":{\"items\":{\"additionalProperties\":false,\"properties\":{\"recordId\":{\"type\":\"string\"},\"recordType\":{\"type\":\"string\"},\"revision\":{\"minimum\":1,\"type\":\"integer\"}},\"required\":[\"recordType\",\"recordId\",\"revision\"],\"type\":\"object\"},\"maxItems\":16,\"type\":\"array\"},\"submissionVersion\":{\"minimum\":1,\"type\":\"integer\"}},\"required\":[\"applicationId\",\"submissionVersion\",\"effectDigest\",\"resultLinks\"],\"type\":\"object\"},\"applicationStatus\":{\"additionalProperties\":false,\"properties\":{\"automaticRetry\":{\"additionalProperties\":false,\"properties\":{\"attempts\":{\"maximum\":1000,\"minimum\":0,\"type\":\"integer\"},\"maximumAttempts\":{\"maximum\":1000,\"minimum\":1,\"type\":\"integer\"},\"scheduled\":{\"type\":\"boolean\"}},\"required\":[\"scheduled\",\"attempts\",\"maximumAttempts\"],\"type\":\"object\"},\"mode\":{\"enum\":[\"automatic\",\"manual\"]},\"reason\":{\"enum\":[\"package-changed\",\"dependency-outage\",\"lease-expired\",\"application-refused\",\"attempts-exhausted\"]},\"recovery\":{\"enum\":[\"retry\",\"rebase\",\"revise\",\"correct-input\"]},\"state\":{\"enum\":[\"awaiting-review\",\"pending\",\"applying\",\"blocked\",\"applied\",\"cancelled\",\"rejected\"]}},\"required\":[\"state\",\"mode\"],\"type\":\"object\"},\"asks\":{\"items\":{\"additionalProperties\":false,\"properties\":{\"answer\":{\"additionalProperties\":false,\"properties\":{\"additions\":{\"items\":{\"type\":\"string\"},\"maxItems\":32,\"type\":\"array\",\"uniqueItems\":true},\"answeredAt\":{\"type\":\"string\"},\"formEntries\":{\"items\":{\"type\":\"string\"},\"maxItems\":32,\"type\":\"array\",\"uniqueItems\":true},\"text\":{\"maxLength\":2000,\"minLength\":1,\"type\":\"string\"}},\"required\":[\"additions\",\"answeredAt\"],\"type\":\"object\"},\"askedAt\":{\"type\":\"string\"},\"dueAt\":{\"type\":\"string\"},\"id\":{\"type\":\"string\"},\"links\":{\"additionalProperties\":false,\"properties\":{\"answer\":{\"additionalProperties\":false,\"properties\":{\"accessProfile\":{\"type\":\"string\"},\"availability\":{\"additionalProperties\":false,\"if\":{\"properties\":{\"available\":{\"const\":false}}},\"properties\":{\"available\":{\"type\":\"boolean\"},\"observedRevision\":{\"minimum\":1,\"type\":\"integer\"},\"reason\":{\"enum\":[\"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\":{\"enum\":[\"refresh\",\"revise\",\"retry\",\"rebase\",\"correct-input\",\"receipt-only\"]}},\"required\":[\"available\",\"observedRevision\"],\"then\":{\"required\":[\"reason\",\"recovery\"]},\"type\":\"object\"},\"ifMatch\":{\"type\":\"string\"},\"method\":{\"const\":\"POST\"},\"operation\":{\"const\":\"answer\"},\"path\":{\"type\":\"string\"}},\"required\":[\"method\",\"path\",\"accessProfile\",\"operation\",\"ifMatch\",\"availability\"],\"type\":\"object\"}},\"type\":\"object\"},\"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\",\"links\"],\"type\":\"object\"},\"maxItems\":50,\"type\":\"array\"},\"attachments\":{\"additionalProperties\":{\"additionalProperties\":false,\"properties\":{\"classification\":{\"enum\":[\"public\",\"internal\",\"restricted\"]},\"contentTypes\":{\"items\":{\"type\":\"string\"},\"maxItems\":16,\"minItems\":1,\"type\":\"array\",\"uniqueItems\":true},\"id\":{\"type\":\"string\"},\"links\":{\"additionalProperties\":{\"additionalProperties\":false,\"properties\":{\"accessProfile\":{\"type\":\"string\"},\"availability\":{\"additionalProperties\":false,\"if\":{\"properties\":{\"available\":{\"const\":false}}},\"properties\":{\"available\":{\"type\":\"boolean\"},\"observedRevision\":{\"minimum\":1,\"type\":\"integer\"},\"reason\":{\"enum\":[\"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\":{\"enum\":[\"refresh\",\"revise\",\"retry\",\"rebase\",\"correct-input\",\"receipt-only\"]}},\"required\":[\"available\",\"observedRevision\"],\"then\":{\"required\":[\"reason\",\"recovery\"]},\"type\":\"object\"},\"ifMatch\":{\"type\":\"string\"},\"method\":{\"enum\":[\"GET\",\"PATCH\",\"DELETE\"]},\"operation\":{\"enum\":[\"download\",\"upload\",\"remove\"]},\"path\":{\"type\":\"string\"}},\"required\":[\"method\",\"path\",\"accessProfile\",\"operation\"],\"type\":\"object\"},\"type\":\"object\"},\"maximumBytes\":{\"maximum\":16777216,\"minimum\":1,\"type\":\"integer\"},\"required\":{\"type\":\"boolean\"},\"value\":{\"additionalProperties\":false,\"properties\":{\"byteSize\":{\"minimum\":1,\"type\":\"integer\"},\"contentType\":{\"type\":\"string\"},\"sha256\":{\"pattern\":\"^[a-f0-9]{64}$\",\"type\":\"string\"},\"submissionVersion\":{\"minimum\":0,\"type\":\"integer\"},\"uploadedAt\":{\"type\":\"string\"},\"verificationStatus\":{\"enum\":[\"notRequired\",\"pending\",\"approved\",\"rejected\"]}},\"required\":[\"submissionVersion\",\"sha256\",\"contentType\",\"byteSize\",\"verificationStatus\"],\"type\":\"object\"}},\"required\":[\"id\",\"required\",\"maximumBytes\",\"contentTypes\",\"classification\",\"links\"],\"type\":\"object\"},\"maxProperties\":8,\"type\":\"object\"},\"blockedReason\":{\"enum\":[\"package-changed\"]},\"createdAt\":{\"type\":\"string\"},\"decision\":{\"additionalProperties\":false,\"properties\":{\"decidedAt\":{\"type\":\"string\"},\"publicReason\":{\"minLength\":1,\"pattern\":\"^[^\\\\u0000-\\\\u001F\\\\u007F-\\\\u009F]*[^\\\\u0000-\\\\u0020\\\\u007F-\\\\u00A0\\\\u1680\\\\u2000-\\\\u200A\\\\u2028\\\\u2029\\\\u202F\\\\u205F\\\\u3000][^\\\\u0000-\\\\u001F\\\\u007F-\\\\u009F]*$\",\"type\":\"string\"},\"status\":{\"enum\":[\"approved\",\"rejected\",\"changes-requested\",\"answered\"]}},\"required\":[\"status\",\"decidedAt\"],\"type\":\"object\"},\"effectDigest\":{\"type\":\"string\"},\"handoffRefusal\":{\"additionalProperties\":false,\"properties\":{\"code\":{\"enum\":[\"review.initiator-required\",\"review.initiator-excluded\",\"review.policy-mismatch\",\"review.refused\"]}},\"required\":[\"code\"],\"type\":\"object\"},\"id\":{\"type\":\"string\"},\"input\":{\"type\":\"object\"},\"links\":{\"additionalProperties\":{\"additionalProperties\":false,\"properties\":{\"accessProfile\":{\"type\":\"string\"},\"availability\":{\"additionalProperties\":false,\"if\":{\"properties\":{\"available\":{\"const\":false}}},\"properties\":{\"available\":{\"type\":\"boolean\"},\"observedRevision\":{\"minimum\":1,\"type\":\"integer\"},\"reason\":{\"enum\":[\"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\":{\"enum\":[\"refresh\",\"revise\",\"retry\",\"rebase\",\"correct-input\",\"receipt-only\"]}},\"required\":[\"available\",\"observedRevision\"],\"then\":{\"required\":[\"reason\",\"recovery\"]},\"type\":\"object\"},\"ifMatch\":{\"type\":\"string\"},\"method\":{\"enum\":[\"GET\",\"POST\"]},\"operation\":{\"type\":\"string\"},\"path\":{\"type\":\"string\"}},\"required\":[\"method\",\"path\",\"accessProfile\",\"operation\"],\"type\":\"object\"},\"type\":\"object\"},\"partyRole\":{\"enum\":[\"owner\",\"subject\"]},\"revision\":{\"minimum\":1,\"type\":\"integer\"},\"state\":{\"enum\":[\"draft\",\"submitted\",\"applied\",\"cancelled\",\"rejected\"]},\"status\":{\"enum\":[\"draft\",\"awaiting-party\",\"in-review\",\"approved\",\"processing\",\"applied\",\"rejected\",\"cancelled\"]},\"submissionVersion\":{\"minimum\":0,\"type\":\"integer\"},\"title\":{\"maxLength\":1024,\"type\":\"string\"},\"turn\":{\"enum\":[\"party\",\"official\",\"nobody\"]}},\"required\":[\"id\",\"actionId\",\"actionRevision\",\"submissionVersion\",\"revision\",\"state\",\"turn\",\"links\"],\"type\":\"object\"}")], ["/paths/~1v1~1proposals~1{proposal_id}~1attachments~1supporting-document/patch/responses/400/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"access-profile.ambiguous\",\"request.invalid\"]}},\"type\":\"object\"}]}")], ["/paths/~1v1~1proposals~1{proposal_id}~1attachments~1supporting-document/patch/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}~1attachments~1supporting-document/patch/responses/403/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"profile.not-authorized\"]}},\"type\":\"object\"}]}")], @@ -223,7 +227,7 @@ const rules: Record = Object.fromEntries([ ["/paths/~1v1~1proposals~1{proposal_id}~1attachments~1supporting-document/patch/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}~1attachments~1supporting-document/patch/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}~1attachments~1supporting-document/patch/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}~1cancel/post/responses/200/content/application~1json/schema", JSON.parse("{\"additionalProperties\":false,\"properties\":{\"actionId\":{\"type\":\"string\"},\"actionRevision\":{\"type\":\"string\"},\"application\":{\"additionalProperties\":false,\"properties\":{\"applicationId\":{\"type\":\"string\"},\"effectDigest\":{\"pattern\":\"^sha256:[0-9a-f]{64}$\",\"type\":\"string\"},\"resultLinks\":{\"items\":{\"additionalProperties\":false,\"properties\":{\"recordId\":{\"type\":\"string\"},\"recordType\":{\"type\":\"string\"},\"revision\":{\"minimum\":1,\"type\":\"integer\"}},\"required\":[\"recordType\",\"recordId\",\"revision\"],\"type\":\"object\"},\"maxItems\":16,\"type\":\"array\"},\"submissionVersion\":{\"minimum\":1,\"type\":\"integer\"}},\"required\":[\"applicationId\",\"submissionVersion\",\"effectDigest\",\"resultLinks\"],\"type\":\"object\"},\"applicationStatus\":{\"additionalProperties\":false,\"properties\":{\"automaticRetry\":{\"additionalProperties\":false,\"properties\":{\"attempts\":{\"maximum\":1000,\"minimum\":0,\"type\":\"integer\"},\"maximumAttempts\":{\"maximum\":1000,\"minimum\":1,\"type\":\"integer\"},\"scheduled\":{\"type\":\"boolean\"}},\"required\":[\"scheduled\",\"attempts\",\"maximumAttempts\"],\"type\":\"object\"},\"mode\":{\"enum\":[\"automatic\",\"manual\"]},\"reason\":{\"enum\":[\"package-changed\",\"dependency-outage\",\"lease-expired\",\"application-refused\",\"attempts-exhausted\"]},\"recovery\":{\"enum\":[\"retry\",\"rebase\",\"revise\",\"correct-input\"]},\"state\":{\"enum\":[\"awaiting-review\",\"pending\",\"applying\",\"blocked\",\"applied\",\"cancelled\",\"rejected\"]}},\"required\":[\"state\",\"mode\"],\"type\":\"object\"},\"asks\":{\"items\":{\"additionalProperties\":false,\"properties\":{\"answer\":{\"additionalProperties\":false,\"properties\":{\"additions\":{\"items\":{\"type\":\"string\"},\"maxItems\":32,\"type\":\"array\",\"uniqueItems\":true},\"answeredAt\":{\"type\":\"string\"},\"text\":{\"maxLength\":2000,\"minLength\":1,\"type\":\"string\"}},\"required\":[\"additions\",\"answeredAt\"],\"type\":\"object\"},\"askedAt\":{\"type\":\"string\"},\"dueAt\":{\"type\":\"string\"},\"id\":{\"type\":\"string\"},\"links\":{\"additionalProperties\":false,\"properties\":{\"answer\":{\"additionalProperties\":false,\"properties\":{\"accessProfile\":{\"type\":\"string\"},\"availability\":{\"additionalProperties\":false,\"if\":{\"properties\":{\"available\":{\"const\":false}}},\"properties\":{\"available\":{\"type\":\"boolean\"},\"observedRevision\":{\"minimum\":1,\"type\":\"integer\"},\"reason\":{\"enum\":[\"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\":{\"enum\":[\"refresh\",\"revise\",\"retry\",\"rebase\",\"correct-input\",\"receipt-only\"]}},\"required\":[\"available\",\"observedRevision\"],\"then\":{\"required\":[\"reason\",\"recovery\"]},\"type\":\"object\"},\"ifMatch\":{\"type\":\"string\"},\"method\":{\"const\":\"POST\"},\"operation\":{\"const\":\"answer\"},\"path\":{\"type\":\"string\"}},\"required\":[\"method\",\"path\",\"accessProfile\",\"operation\",\"ifMatch\",\"availability\"],\"type\":\"object\"}},\"type\":\"object\"},\"state\":{\"enum\":[\"open\",\"answered\",\"expired\",\"closed\"]},\"text\":{\"maxLength\":2000,\"minLength\":1,\"type\":\"string\"},\"wants\":{\"items\":{\"additionalProperties\":false,\"properties\":{\"kind\":{\"enum\":[\"answer\",\"document\"]}},\"required\":[\"kind\"],\"type\":\"object\"},\"maxItems\":8,\"type\":\"array\",\"uniqueItems\":true}},\"required\":[\"id\",\"text\",\"wants\",\"askedAt\",\"state\",\"links\"],\"type\":\"object\"},\"maxItems\":50,\"type\":\"array\"},\"attachments\":{\"additionalProperties\":{\"additionalProperties\":false,\"properties\":{\"classification\":{\"enum\":[\"public\",\"internal\",\"restricted\"]},\"contentTypes\":{\"items\":{\"type\":\"string\"},\"maxItems\":16,\"minItems\":1,\"type\":\"array\",\"uniqueItems\":true},\"id\":{\"type\":\"string\"},\"links\":{\"additionalProperties\":{\"additionalProperties\":false,\"properties\":{\"accessProfile\":{\"type\":\"string\"},\"availability\":{\"additionalProperties\":false,\"if\":{\"properties\":{\"available\":{\"const\":false}}},\"properties\":{\"available\":{\"type\":\"boolean\"},\"observedRevision\":{\"minimum\":1,\"type\":\"integer\"},\"reason\":{\"enum\":[\"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\":{\"enum\":[\"refresh\",\"revise\",\"retry\",\"rebase\",\"correct-input\",\"receipt-only\"]}},\"required\":[\"available\",\"observedRevision\"],\"then\":{\"required\":[\"reason\",\"recovery\"]},\"type\":\"object\"},\"ifMatch\":{\"type\":\"string\"},\"method\":{\"enum\":[\"GET\",\"PATCH\",\"DELETE\"]},\"operation\":{\"enum\":[\"download\",\"upload\",\"remove\"]},\"path\":{\"type\":\"string\"}},\"required\":[\"method\",\"path\",\"accessProfile\",\"operation\"],\"type\":\"object\"},\"type\":\"object\"},\"maximumBytes\":{\"maximum\":16777216,\"minimum\":1,\"type\":\"integer\"},\"required\":{\"type\":\"boolean\"},\"value\":{\"additionalProperties\":false,\"properties\":{\"byteSize\":{\"minimum\":1,\"type\":\"integer\"},\"contentType\":{\"type\":\"string\"},\"sha256\":{\"pattern\":\"^[a-f0-9]{64}$\",\"type\":\"string\"},\"submissionVersion\":{\"minimum\":0,\"type\":\"integer\"},\"uploadedAt\":{\"type\":\"string\"},\"verificationStatus\":{\"enum\":[\"notRequired\",\"pending\",\"approved\",\"rejected\"]}},\"required\":[\"submissionVersion\",\"sha256\",\"contentType\",\"byteSize\",\"verificationStatus\"],\"type\":\"object\"}},\"required\":[\"id\",\"required\",\"maximumBytes\",\"contentTypes\",\"classification\",\"links\"],\"type\":\"object\"},\"maxProperties\":8,\"type\":\"object\"},\"blockedReason\":{\"enum\":[\"package-changed\"]},\"createdAt\":{\"type\":\"string\"},\"decision\":{\"additionalProperties\":false,\"properties\":{\"decidedAt\":{\"type\":\"string\"},\"publicReason\":{\"minLength\":1,\"pattern\":\"^[^\\\\u0000-\\\\u001F\\\\u007F-\\\\u009F]*[^\\\\u0000-\\\\u0020\\\\u007F-\\\\u00A0\\\\u1680\\\\u2000-\\\\u200A\\\\u2028\\\\u2029\\\\u202F\\\\u205F\\\\u3000][^\\\\u0000-\\\\u001F\\\\u007F-\\\\u009F]*$\",\"type\":\"string\"},\"status\":{\"enum\":[\"approved\",\"rejected\",\"changes-requested\",\"answered\"]}},\"required\":[\"status\",\"decidedAt\"],\"type\":\"object\"},\"effectDigest\":{\"type\":\"string\"},\"handoffRefusal\":{\"additionalProperties\":false,\"properties\":{\"code\":{\"enum\":[\"review.initiator-required\",\"review.initiator-excluded\",\"review.policy-mismatch\",\"review.refused\"]}},\"required\":[\"code\"],\"type\":\"object\"},\"id\":{\"type\":\"string\"},\"input\":{\"type\":\"object\"},\"links\":{\"additionalProperties\":{\"additionalProperties\":false,\"properties\":{\"accessProfile\":{\"type\":\"string\"},\"availability\":{\"additionalProperties\":false,\"if\":{\"properties\":{\"available\":{\"const\":false}}},\"properties\":{\"available\":{\"type\":\"boolean\"},\"observedRevision\":{\"minimum\":1,\"type\":\"integer\"},\"reason\":{\"enum\":[\"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\":{\"enum\":[\"refresh\",\"revise\",\"retry\",\"rebase\",\"correct-input\",\"receipt-only\"]}},\"required\":[\"available\",\"observedRevision\"],\"then\":{\"required\":[\"reason\",\"recovery\"]},\"type\":\"object\"},\"ifMatch\":{\"type\":\"string\"},\"method\":{\"enum\":[\"GET\",\"POST\"]},\"operation\":{\"type\":\"string\"},\"path\":{\"type\":\"string\"}},\"required\":[\"method\",\"path\",\"accessProfile\",\"operation\"],\"type\":\"object\"},\"type\":\"object\"},\"revision\":{\"minimum\":1,\"type\":\"integer\"},\"state\":{\"enum\":[\"draft\",\"submitted\",\"applied\",\"cancelled\",\"rejected\"]},\"status\":{\"enum\":[\"draft\",\"awaiting-party\",\"in-review\",\"approved\",\"processing\",\"applied\",\"rejected\",\"cancelled\"]},\"submissionVersion\":{\"minimum\":0,\"type\":\"integer\"},\"title\":{\"maxLength\":1024,\"type\":\"string\"},\"turn\":{\"enum\":[\"party\",\"official\",\"nobody\"]}},\"required\":[\"id\",\"actionId\",\"actionRevision\",\"submissionVersion\",\"revision\",\"state\",\"turn\",\"links\"],\"type\":\"object\"}")], + ["/paths/~1v1~1proposals~1{proposal_id}~1cancel/post/responses/200/content/application~1json/schema", JSON.parse("{\"additionalProperties\":false,\"properties\":{\"actionId\":{\"type\":\"string\"},\"actionRevision\":{\"type\":\"string\"},\"application\":{\"additionalProperties\":false,\"properties\":{\"applicationId\":{\"type\":\"string\"},\"effectDigest\":{\"pattern\":\"^sha256:[0-9a-f]{64}$\",\"type\":\"string\"},\"resultLinks\":{\"items\":{\"additionalProperties\":false,\"properties\":{\"recordId\":{\"type\":\"string\"},\"recordType\":{\"type\":\"string\"},\"revision\":{\"minimum\":1,\"type\":\"integer\"}},\"required\":[\"recordType\",\"recordId\",\"revision\"],\"type\":\"object\"},\"maxItems\":16,\"type\":\"array\"},\"submissionVersion\":{\"minimum\":1,\"type\":\"integer\"}},\"required\":[\"applicationId\",\"submissionVersion\",\"effectDigest\",\"resultLinks\"],\"type\":\"object\"},\"applicationStatus\":{\"additionalProperties\":false,\"properties\":{\"automaticRetry\":{\"additionalProperties\":false,\"properties\":{\"attempts\":{\"maximum\":1000,\"minimum\":0,\"type\":\"integer\"},\"maximumAttempts\":{\"maximum\":1000,\"minimum\":1,\"type\":\"integer\"},\"scheduled\":{\"type\":\"boolean\"}},\"required\":[\"scheduled\",\"attempts\",\"maximumAttempts\"],\"type\":\"object\"},\"mode\":{\"enum\":[\"automatic\",\"manual\"]},\"reason\":{\"enum\":[\"package-changed\",\"dependency-outage\",\"lease-expired\",\"application-refused\",\"attempts-exhausted\"]},\"recovery\":{\"enum\":[\"retry\",\"rebase\",\"revise\",\"correct-input\"]},\"state\":{\"enum\":[\"awaiting-review\",\"pending\",\"applying\",\"blocked\",\"applied\",\"cancelled\",\"rejected\"]}},\"required\":[\"state\",\"mode\"],\"type\":\"object\"},\"asks\":{\"items\":{\"additionalProperties\":false,\"properties\":{\"answer\":{\"additionalProperties\":false,\"properties\":{\"additions\":{\"items\":{\"type\":\"string\"},\"maxItems\":32,\"type\":\"array\",\"uniqueItems\":true},\"answeredAt\":{\"type\":\"string\"},\"formEntries\":{\"items\":{\"type\":\"string\"},\"maxItems\":32,\"type\":\"array\",\"uniqueItems\":true},\"text\":{\"maxLength\":2000,\"minLength\":1,\"type\":\"string\"}},\"required\":[\"additions\",\"answeredAt\"],\"type\":\"object\"},\"askedAt\":{\"type\":\"string\"},\"dueAt\":{\"type\":\"string\"},\"id\":{\"type\":\"string\"},\"links\":{\"additionalProperties\":false,\"properties\":{\"answer\":{\"additionalProperties\":false,\"properties\":{\"accessProfile\":{\"type\":\"string\"},\"availability\":{\"additionalProperties\":false,\"if\":{\"properties\":{\"available\":{\"const\":false}}},\"properties\":{\"available\":{\"type\":\"boolean\"},\"observedRevision\":{\"minimum\":1,\"type\":\"integer\"},\"reason\":{\"enum\":[\"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\":{\"enum\":[\"refresh\",\"revise\",\"retry\",\"rebase\",\"correct-input\",\"receipt-only\"]}},\"required\":[\"available\",\"observedRevision\"],\"then\":{\"required\":[\"reason\",\"recovery\"]},\"type\":\"object\"},\"ifMatch\":{\"type\":\"string\"},\"method\":{\"const\":\"POST\"},\"operation\":{\"const\":\"answer\"},\"path\":{\"type\":\"string\"}},\"required\":[\"method\",\"path\",\"accessProfile\",\"operation\",\"ifMatch\",\"availability\"],\"type\":\"object\"}},\"type\":\"object\"},\"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\",\"links\"],\"type\":\"object\"},\"maxItems\":50,\"type\":\"array\"},\"attachments\":{\"additionalProperties\":{\"additionalProperties\":false,\"properties\":{\"classification\":{\"enum\":[\"public\",\"internal\",\"restricted\"]},\"contentTypes\":{\"items\":{\"type\":\"string\"},\"maxItems\":16,\"minItems\":1,\"type\":\"array\",\"uniqueItems\":true},\"id\":{\"type\":\"string\"},\"links\":{\"additionalProperties\":{\"additionalProperties\":false,\"properties\":{\"accessProfile\":{\"type\":\"string\"},\"availability\":{\"additionalProperties\":false,\"if\":{\"properties\":{\"available\":{\"const\":false}}},\"properties\":{\"available\":{\"type\":\"boolean\"},\"observedRevision\":{\"minimum\":1,\"type\":\"integer\"},\"reason\":{\"enum\":[\"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\":{\"enum\":[\"refresh\",\"revise\",\"retry\",\"rebase\",\"correct-input\",\"receipt-only\"]}},\"required\":[\"available\",\"observedRevision\"],\"then\":{\"required\":[\"reason\",\"recovery\"]},\"type\":\"object\"},\"ifMatch\":{\"type\":\"string\"},\"method\":{\"enum\":[\"GET\",\"PATCH\",\"DELETE\"]},\"operation\":{\"enum\":[\"download\",\"upload\",\"remove\"]},\"path\":{\"type\":\"string\"}},\"required\":[\"method\",\"path\",\"accessProfile\",\"operation\"],\"type\":\"object\"},\"type\":\"object\"},\"maximumBytes\":{\"maximum\":16777216,\"minimum\":1,\"type\":\"integer\"},\"required\":{\"type\":\"boolean\"},\"value\":{\"additionalProperties\":false,\"properties\":{\"byteSize\":{\"minimum\":1,\"type\":\"integer\"},\"contentType\":{\"type\":\"string\"},\"sha256\":{\"pattern\":\"^[a-f0-9]{64}$\",\"type\":\"string\"},\"submissionVersion\":{\"minimum\":0,\"type\":\"integer\"},\"uploadedAt\":{\"type\":\"string\"},\"verificationStatus\":{\"enum\":[\"notRequired\",\"pending\",\"approved\",\"rejected\"]}},\"required\":[\"submissionVersion\",\"sha256\",\"contentType\",\"byteSize\",\"verificationStatus\"],\"type\":\"object\"}},\"required\":[\"id\",\"required\",\"maximumBytes\",\"contentTypes\",\"classification\",\"links\"],\"type\":\"object\"},\"maxProperties\":8,\"type\":\"object\"},\"blockedReason\":{\"enum\":[\"package-changed\"]},\"createdAt\":{\"type\":\"string\"},\"decision\":{\"additionalProperties\":false,\"properties\":{\"decidedAt\":{\"type\":\"string\"},\"publicReason\":{\"minLength\":1,\"pattern\":\"^[^\\\\u0000-\\\\u001F\\\\u007F-\\\\u009F]*[^\\\\u0000-\\\\u0020\\\\u007F-\\\\u00A0\\\\u1680\\\\u2000-\\\\u200A\\\\u2028\\\\u2029\\\\u202F\\\\u205F\\\\u3000][^\\\\u0000-\\\\u001F\\\\u007F-\\\\u009F]*$\",\"type\":\"string\"},\"status\":{\"enum\":[\"approved\",\"rejected\",\"changes-requested\",\"answered\"]}},\"required\":[\"status\",\"decidedAt\"],\"type\":\"object\"},\"effectDigest\":{\"type\":\"string\"},\"handoffRefusal\":{\"additionalProperties\":false,\"properties\":{\"code\":{\"enum\":[\"review.initiator-required\",\"review.initiator-excluded\",\"review.policy-mismatch\",\"review.refused\"]}},\"required\":[\"code\"],\"type\":\"object\"},\"id\":{\"type\":\"string\"},\"input\":{\"type\":\"object\"},\"links\":{\"additionalProperties\":{\"additionalProperties\":false,\"properties\":{\"accessProfile\":{\"type\":\"string\"},\"availability\":{\"additionalProperties\":false,\"if\":{\"properties\":{\"available\":{\"const\":false}}},\"properties\":{\"available\":{\"type\":\"boolean\"},\"observedRevision\":{\"minimum\":1,\"type\":\"integer\"},\"reason\":{\"enum\":[\"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\":{\"enum\":[\"refresh\",\"revise\",\"retry\",\"rebase\",\"correct-input\",\"receipt-only\"]}},\"required\":[\"available\",\"observedRevision\"],\"then\":{\"required\":[\"reason\",\"recovery\"]},\"type\":\"object\"},\"ifMatch\":{\"type\":\"string\"},\"method\":{\"enum\":[\"GET\",\"POST\"]},\"operation\":{\"type\":\"string\"},\"path\":{\"type\":\"string\"}},\"required\":[\"method\",\"path\",\"accessProfile\",\"operation\"],\"type\":\"object\"},\"type\":\"object\"},\"partyRole\":{\"enum\":[\"owner\",\"subject\"]},\"revision\":{\"minimum\":1,\"type\":\"integer\"},\"state\":{\"enum\":[\"draft\",\"submitted\",\"applied\",\"cancelled\",\"rejected\"]},\"status\":{\"enum\":[\"draft\",\"awaiting-party\",\"in-review\",\"approved\",\"processing\",\"applied\",\"rejected\",\"cancelled\"]},\"submissionVersion\":{\"minimum\":0,\"type\":\"integer\"},\"title\":{\"maxLength\":1024,\"type\":\"string\"},\"turn\":{\"enum\":[\"party\",\"official\",\"nobody\"]}},\"required\":[\"id\",\"actionId\",\"actionRevision\",\"submissionVersion\",\"revision\",\"state\",\"turn\",\"links\"],\"type\":\"object\"}")], ["/paths/~1v1~1proposals~1{proposal_id}~1cancel/post/responses/400/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"access-profile.ambiguous\",\"request.invalid\"]}},\"type\":\"object\"}]}")], ["/paths/~1v1~1proposals~1{proposal_id}~1cancel/post/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}~1cancel/post/responses/403/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"profile.not-authorized\"]}},\"type\":\"object\"}]}")], @@ -235,7 +239,7 @@ const rules: Record = Object.fromEntries([ ["/paths/~1v1~1proposals~1{proposal_id}~1cancel/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}~1cancel/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}~1cancel/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}~1edit/post/responses/200/content/application~1json/schema", JSON.parse("{\"additionalProperties\":false,\"properties\":{\"actionId\":{\"type\":\"string\"},\"actionRevision\":{\"type\":\"string\"},\"application\":{\"additionalProperties\":false,\"properties\":{\"applicationId\":{\"type\":\"string\"},\"effectDigest\":{\"pattern\":\"^sha256:[0-9a-f]{64}$\",\"type\":\"string\"},\"resultLinks\":{\"items\":{\"additionalProperties\":false,\"properties\":{\"recordId\":{\"type\":\"string\"},\"recordType\":{\"type\":\"string\"},\"revision\":{\"minimum\":1,\"type\":\"integer\"}},\"required\":[\"recordType\",\"recordId\",\"revision\"],\"type\":\"object\"},\"maxItems\":16,\"type\":\"array\"},\"submissionVersion\":{\"minimum\":1,\"type\":\"integer\"}},\"required\":[\"applicationId\",\"submissionVersion\",\"effectDigest\",\"resultLinks\"],\"type\":\"object\"},\"applicationStatus\":{\"additionalProperties\":false,\"properties\":{\"automaticRetry\":{\"additionalProperties\":false,\"properties\":{\"attempts\":{\"maximum\":1000,\"minimum\":0,\"type\":\"integer\"},\"maximumAttempts\":{\"maximum\":1000,\"minimum\":1,\"type\":\"integer\"},\"scheduled\":{\"type\":\"boolean\"}},\"required\":[\"scheduled\",\"attempts\",\"maximumAttempts\"],\"type\":\"object\"},\"mode\":{\"enum\":[\"automatic\",\"manual\"]},\"reason\":{\"enum\":[\"package-changed\",\"dependency-outage\",\"lease-expired\",\"application-refused\",\"attempts-exhausted\"]},\"recovery\":{\"enum\":[\"retry\",\"rebase\",\"revise\",\"correct-input\"]},\"state\":{\"enum\":[\"awaiting-review\",\"pending\",\"applying\",\"blocked\",\"applied\",\"cancelled\",\"rejected\"]}},\"required\":[\"state\",\"mode\"],\"type\":\"object\"},\"asks\":{\"items\":{\"additionalProperties\":false,\"properties\":{\"answer\":{\"additionalProperties\":false,\"properties\":{\"additions\":{\"items\":{\"type\":\"string\"},\"maxItems\":32,\"type\":\"array\",\"uniqueItems\":true},\"answeredAt\":{\"type\":\"string\"},\"text\":{\"maxLength\":2000,\"minLength\":1,\"type\":\"string\"}},\"required\":[\"additions\",\"answeredAt\"],\"type\":\"object\"},\"askedAt\":{\"type\":\"string\"},\"dueAt\":{\"type\":\"string\"},\"id\":{\"type\":\"string\"},\"links\":{\"additionalProperties\":false,\"properties\":{\"answer\":{\"additionalProperties\":false,\"properties\":{\"accessProfile\":{\"type\":\"string\"},\"availability\":{\"additionalProperties\":false,\"if\":{\"properties\":{\"available\":{\"const\":false}}},\"properties\":{\"available\":{\"type\":\"boolean\"},\"observedRevision\":{\"minimum\":1,\"type\":\"integer\"},\"reason\":{\"enum\":[\"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\":{\"enum\":[\"refresh\",\"revise\",\"retry\",\"rebase\",\"correct-input\",\"receipt-only\"]}},\"required\":[\"available\",\"observedRevision\"],\"then\":{\"required\":[\"reason\",\"recovery\"]},\"type\":\"object\"},\"ifMatch\":{\"type\":\"string\"},\"method\":{\"const\":\"POST\"},\"operation\":{\"const\":\"answer\"},\"path\":{\"type\":\"string\"}},\"required\":[\"method\",\"path\",\"accessProfile\",\"operation\",\"ifMatch\",\"availability\"],\"type\":\"object\"}},\"type\":\"object\"},\"state\":{\"enum\":[\"open\",\"answered\",\"expired\",\"closed\"]},\"text\":{\"maxLength\":2000,\"minLength\":1,\"type\":\"string\"},\"wants\":{\"items\":{\"additionalProperties\":false,\"properties\":{\"kind\":{\"enum\":[\"answer\",\"document\"]}},\"required\":[\"kind\"],\"type\":\"object\"},\"maxItems\":8,\"type\":\"array\",\"uniqueItems\":true}},\"required\":[\"id\",\"text\",\"wants\",\"askedAt\",\"state\",\"links\"],\"type\":\"object\"},\"maxItems\":50,\"type\":\"array\"},\"attachments\":{\"additionalProperties\":{\"additionalProperties\":false,\"properties\":{\"classification\":{\"enum\":[\"public\",\"internal\",\"restricted\"]},\"contentTypes\":{\"items\":{\"type\":\"string\"},\"maxItems\":16,\"minItems\":1,\"type\":\"array\",\"uniqueItems\":true},\"id\":{\"type\":\"string\"},\"links\":{\"additionalProperties\":{\"additionalProperties\":false,\"properties\":{\"accessProfile\":{\"type\":\"string\"},\"availability\":{\"additionalProperties\":false,\"if\":{\"properties\":{\"available\":{\"const\":false}}},\"properties\":{\"available\":{\"type\":\"boolean\"},\"observedRevision\":{\"minimum\":1,\"type\":\"integer\"},\"reason\":{\"enum\":[\"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\":{\"enum\":[\"refresh\",\"revise\",\"retry\",\"rebase\",\"correct-input\",\"receipt-only\"]}},\"required\":[\"available\",\"observedRevision\"],\"then\":{\"required\":[\"reason\",\"recovery\"]},\"type\":\"object\"},\"ifMatch\":{\"type\":\"string\"},\"method\":{\"enum\":[\"GET\",\"PATCH\",\"DELETE\"]},\"operation\":{\"enum\":[\"download\",\"upload\",\"remove\"]},\"path\":{\"type\":\"string\"}},\"required\":[\"method\",\"path\",\"accessProfile\",\"operation\"],\"type\":\"object\"},\"type\":\"object\"},\"maximumBytes\":{\"maximum\":16777216,\"minimum\":1,\"type\":\"integer\"},\"required\":{\"type\":\"boolean\"},\"value\":{\"additionalProperties\":false,\"properties\":{\"byteSize\":{\"minimum\":1,\"type\":\"integer\"},\"contentType\":{\"type\":\"string\"},\"sha256\":{\"pattern\":\"^[a-f0-9]{64}$\",\"type\":\"string\"},\"submissionVersion\":{\"minimum\":0,\"type\":\"integer\"},\"uploadedAt\":{\"type\":\"string\"},\"verificationStatus\":{\"enum\":[\"notRequired\",\"pending\",\"approved\",\"rejected\"]}},\"required\":[\"submissionVersion\",\"sha256\",\"contentType\",\"byteSize\",\"verificationStatus\"],\"type\":\"object\"}},\"required\":[\"id\",\"required\",\"maximumBytes\",\"contentTypes\",\"classification\",\"links\"],\"type\":\"object\"},\"maxProperties\":8,\"type\":\"object\"},\"blockedReason\":{\"enum\":[\"package-changed\"]},\"createdAt\":{\"type\":\"string\"},\"decision\":{\"additionalProperties\":false,\"properties\":{\"decidedAt\":{\"type\":\"string\"},\"publicReason\":{\"minLength\":1,\"pattern\":\"^[^\\\\u0000-\\\\u001F\\\\u007F-\\\\u009F]*[^\\\\u0000-\\\\u0020\\\\u007F-\\\\u00A0\\\\u1680\\\\u2000-\\\\u200A\\\\u2028\\\\u2029\\\\u202F\\\\u205F\\\\u3000][^\\\\u0000-\\\\u001F\\\\u007F-\\\\u009F]*$\",\"type\":\"string\"},\"status\":{\"enum\":[\"approved\",\"rejected\",\"changes-requested\",\"answered\"]}},\"required\":[\"status\",\"decidedAt\"],\"type\":\"object\"},\"effectDigest\":{\"type\":\"string\"},\"handoffRefusal\":{\"additionalProperties\":false,\"properties\":{\"code\":{\"enum\":[\"review.initiator-required\",\"review.initiator-excluded\",\"review.policy-mismatch\",\"review.refused\"]}},\"required\":[\"code\"],\"type\":\"object\"},\"id\":{\"type\":\"string\"},\"input\":{\"type\":\"object\"},\"links\":{\"additionalProperties\":{\"additionalProperties\":false,\"properties\":{\"accessProfile\":{\"type\":\"string\"},\"availability\":{\"additionalProperties\":false,\"if\":{\"properties\":{\"available\":{\"const\":false}}},\"properties\":{\"available\":{\"type\":\"boolean\"},\"observedRevision\":{\"minimum\":1,\"type\":\"integer\"},\"reason\":{\"enum\":[\"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\":{\"enum\":[\"refresh\",\"revise\",\"retry\",\"rebase\",\"correct-input\",\"receipt-only\"]}},\"required\":[\"available\",\"observedRevision\"],\"then\":{\"required\":[\"reason\",\"recovery\"]},\"type\":\"object\"},\"ifMatch\":{\"type\":\"string\"},\"method\":{\"enum\":[\"GET\",\"POST\"]},\"operation\":{\"type\":\"string\"},\"path\":{\"type\":\"string\"}},\"required\":[\"method\",\"path\",\"accessProfile\",\"operation\"],\"type\":\"object\"},\"type\":\"object\"},\"revision\":{\"minimum\":1,\"type\":\"integer\"},\"state\":{\"enum\":[\"draft\",\"submitted\",\"applied\",\"cancelled\",\"rejected\"]},\"status\":{\"enum\":[\"draft\",\"awaiting-party\",\"in-review\",\"approved\",\"processing\",\"applied\",\"rejected\",\"cancelled\"]},\"submissionVersion\":{\"minimum\":0,\"type\":\"integer\"},\"title\":{\"maxLength\":1024,\"type\":\"string\"},\"turn\":{\"enum\":[\"party\",\"official\",\"nobody\"]}},\"required\":[\"id\",\"actionId\",\"actionRevision\",\"submissionVersion\",\"revision\",\"state\",\"turn\",\"links\"],\"type\":\"object\"}")], + ["/paths/~1v1~1proposals~1{proposal_id}~1edit/post/responses/200/content/application~1json/schema", JSON.parse("{\"additionalProperties\":false,\"properties\":{\"actionId\":{\"type\":\"string\"},\"actionRevision\":{\"type\":\"string\"},\"application\":{\"additionalProperties\":false,\"properties\":{\"applicationId\":{\"type\":\"string\"},\"effectDigest\":{\"pattern\":\"^sha256:[0-9a-f]{64}$\",\"type\":\"string\"},\"resultLinks\":{\"items\":{\"additionalProperties\":false,\"properties\":{\"recordId\":{\"type\":\"string\"},\"recordType\":{\"type\":\"string\"},\"revision\":{\"minimum\":1,\"type\":\"integer\"}},\"required\":[\"recordType\",\"recordId\",\"revision\"],\"type\":\"object\"},\"maxItems\":16,\"type\":\"array\"},\"submissionVersion\":{\"minimum\":1,\"type\":\"integer\"}},\"required\":[\"applicationId\",\"submissionVersion\",\"effectDigest\",\"resultLinks\"],\"type\":\"object\"},\"applicationStatus\":{\"additionalProperties\":false,\"properties\":{\"automaticRetry\":{\"additionalProperties\":false,\"properties\":{\"attempts\":{\"maximum\":1000,\"minimum\":0,\"type\":\"integer\"},\"maximumAttempts\":{\"maximum\":1000,\"minimum\":1,\"type\":\"integer\"},\"scheduled\":{\"type\":\"boolean\"}},\"required\":[\"scheduled\",\"attempts\",\"maximumAttempts\"],\"type\":\"object\"},\"mode\":{\"enum\":[\"automatic\",\"manual\"]},\"reason\":{\"enum\":[\"package-changed\",\"dependency-outage\",\"lease-expired\",\"application-refused\",\"attempts-exhausted\"]},\"recovery\":{\"enum\":[\"retry\",\"rebase\",\"revise\",\"correct-input\"]},\"state\":{\"enum\":[\"awaiting-review\",\"pending\",\"applying\",\"blocked\",\"applied\",\"cancelled\",\"rejected\"]}},\"required\":[\"state\",\"mode\"],\"type\":\"object\"},\"asks\":{\"items\":{\"additionalProperties\":false,\"properties\":{\"answer\":{\"additionalProperties\":false,\"properties\":{\"additions\":{\"items\":{\"type\":\"string\"},\"maxItems\":32,\"type\":\"array\",\"uniqueItems\":true},\"answeredAt\":{\"type\":\"string\"},\"formEntries\":{\"items\":{\"type\":\"string\"},\"maxItems\":32,\"type\":\"array\",\"uniqueItems\":true},\"text\":{\"maxLength\":2000,\"minLength\":1,\"type\":\"string\"}},\"required\":[\"additions\",\"answeredAt\"],\"type\":\"object\"},\"askedAt\":{\"type\":\"string\"},\"dueAt\":{\"type\":\"string\"},\"id\":{\"type\":\"string\"},\"links\":{\"additionalProperties\":false,\"properties\":{\"answer\":{\"additionalProperties\":false,\"properties\":{\"accessProfile\":{\"type\":\"string\"},\"availability\":{\"additionalProperties\":false,\"if\":{\"properties\":{\"available\":{\"const\":false}}},\"properties\":{\"available\":{\"type\":\"boolean\"},\"observedRevision\":{\"minimum\":1,\"type\":\"integer\"},\"reason\":{\"enum\":[\"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\":{\"enum\":[\"refresh\",\"revise\",\"retry\",\"rebase\",\"correct-input\",\"receipt-only\"]}},\"required\":[\"available\",\"observedRevision\"],\"then\":{\"required\":[\"reason\",\"recovery\"]},\"type\":\"object\"},\"ifMatch\":{\"type\":\"string\"},\"method\":{\"const\":\"POST\"},\"operation\":{\"const\":\"answer\"},\"path\":{\"type\":\"string\"}},\"required\":[\"method\",\"path\",\"accessProfile\",\"operation\",\"ifMatch\",\"availability\"],\"type\":\"object\"}},\"type\":\"object\"},\"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\",\"links\"],\"type\":\"object\"},\"maxItems\":50,\"type\":\"array\"},\"attachments\":{\"additionalProperties\":{\"additionalProperties\":false,\"properties\":{\"classification\":{\"enum\":[\"public\",\"internal\",\"restricted\"]},\"contentTypes\":{\"items\":{\"type\":\"string\"},\"maxItems\":16,\"minItems\":1,\"type\":\"array\",\"uniqueItems\":true},\"id\":{\"type\":\"string\"},\"links\":{\"additionalProperties\":{\"additionalProperties\":false,\"properties\":{\"accessProfile\":{\"type\":\"string\"},\"availability\":{\"additionalProperties\":false,\"if\":{\"properties\":{\"available\":{\"const\":false}}},\"properties\":{\"available\":{\"type\":\"boolean\"},\"observedRevision\":{\"minimum\":1,\"type\":\"integer\"},\"reason\":{\"enum\":[\"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\":{\"enum\":[\"refresh\",\"revise\",\"retry\",\"rebase\",\"correct-input\",\"receipt-only\"]}},\"required\":[\"available\",\"observedRevision\"],\"then\":{\"required\":[\"reason\",\"recovery\"]},\"type\":\"object\"},\"ifMatch\":{\"type\":\"string\"},\"method\":{\"enum\":[\"GET\",\"PATCH\",\"DELETE\"]},\"operation\":{\"enum\":[\"download\",\"upload\",\"remove\"]},\"path\":{\"type\":\"string\"}},\"required\":[\"method\",\"path\",\"accessProfile\",\"operation\"],\"type\":\"object\"},\"type\":\"object\"},\"maximumBytes\":{\"maximum\":16777216,\"minimum\":1,\"type\":\"integer\"},\"required\":{\"type\":\"boolean\"},\"value\":{\"additionalProperties\":false,\"properties\":{\"byteSize\":{\"minimum\":1,\"type\":\"integer\"},\"contentType\":{\"type\":\"string\"},\"sha256\":{\"pattern\":\"^[a-f0-9]{64}$\",\"type\":\"string\"},\"submissionVersion\":{\"minimum\":0,\"type\":\"integer\"},\"uploadedAt\":{\"type\":\"string\"},\"verificationStatus\":{\"enum\":[\"notRequired\",\"pending\",\"approved\",\"rejected\"]}},\"required\":[\"submissionVersion\",\"sha256\",\"contentType\",\"byteSize\",\"verificationStatus\"],\"type\":\"object\"}},\"required\":[\"id\",\"required\",\"maximumBytes\",\"contentTypes\",\"classification\",\"links\"],\"type\":\"object\"},\"maxProperties\":8,\"type\":\"object\"},\"blockedReason\":{\"enum\":[\"package-changed\"]},\"createdAt\":{\"type\":\"string\"},\"decision\":{\"additionalProperties\":false,\"properties\":{\"decidedAt\":{\"type\":\"string\"},\"publicReason\":{\"minLength\":1,\"pattern\":\"^[^\\\\u0000-\\\\u001F\\\\u007F-\\\\u009F]*[^\\\\u0000-\\\\u0020\\\\u007F-\\\\u00A0\\\\u1680\\\\u2000-\\\\u200A\\\\u2028\\\\u2029\\\\u202F\\\\u205F\\\\u3000][^\\\\u0000-\\\\u001F\\\\u007F-\\\\u009F]*$\",\"type\":\"string\"},\"status\":{\"enum\":[\"approved\",\"rejected\",\"changes-requested\",\"answered\"]}},\"required\":[\"status\",\"decidedAt\"],\"type\":\"object\"},\"effectDigest\":{\"type\":\"string\"},\"handoffRefusal\":{\"additionalProperties\":false,\"properties\":{\"code\":{\"enum\":[\"review.initiator-required\",\"review.initiator-excluded\",\"review.policy-mismatch\",\"review.refused\"]}},\"required\":[\"code\"],\"type\":\"object\"},\"id\":{\"type\":\"string\"},\"input\":{\"type\":\"object\"},\"links\":{\"additionalProperties\":{\"additionalProperties\":false,\"properties\":{\"accessProfile\":{\"type\":\"string\"},\"availability\":{\"additionalProperties\":false,\"if\":{\"properties\":{\"available\":{\"const\":false}}},\"properties\":{\"available\":{\"type\":\"boolean\"},\"observedRevision\":{\"minimum\":1,\"type\":\"integer\"},\"reason\":{\"enum\":[\"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\":{\"enum\":[\"refresh\",\"revise\",\"retry\",\"rebase\",\"correct-input\",\"receipt-only\"]}},\"required\":[\"available\",\"observedRevision\"],\"then\":{\"required\":[\"reason\",\"recovery\"]},\"type\":\"object\"},\"ifMatch\":{\"type\":\"string\"},\"method\":{\"enum\":[\"GET\",\"POST\"]},\"operation\":{\"type\":\"string\"},\"path\":{\"type\":\"string\"}},\"required\":[\"method\",\"path\",\"accessProfile\",\"operation\"],\"type\":\"object\"},\"type\":\"object\"},\"partyRole\":{\"enum\":[\"owner\",\"subject\"]},\"revision\":{\"minimum\":1,\"type\":\"integer\"},\"state\":{\"enum\":[\"draft\",\"submitted\",\"applied\",\"cancelled\",\"rejected\"]},\"status\":{\"enum\":[\"draft\",\"awaiting-party\",\"in-review\",\"approved\",\"processing\",\"applied\",\"rejected\",\"cancelled\"]},\"submissionVersion\":{\"minimum\":0,\"type\":\"integer\"},\"title\":{\"maxLength\":1024,\"type\":\"string\"},\"turn\":{\"enum\":[\"party\",\"official\",\"nobody\"]}},\"required\":[\"id\",\"actionId\",\"actionRevision\",\"submissionVersion\",\"revision\",\"state\",\"turn\",\"links\"],\"type\":\"object\"}")], ["/paths/~1v1~1proposals~1{proposal_id}~1edit/post/responses/400/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"access-profile.ambiguous\",\"request.invalid\"]}},\"type\":\"object\"}]}")], ["/paths/~1v1~1proposals~1{proposal_id}~1edit/post/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}~1edit/post/responses/403/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"profile.not-authorized\"]}},\"type\":\"object\"}]}")], @@ -247,7 +251,7 @@ const rules: Record = Object.fromEntries([ ["/paths/~1v1~1proposals~1{proposal_id}~1edit/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}~1edit/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}~1edit/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}~1rebase/post/responses/200/content/application~1json/schema", JSON.parse("{\"additionalProperties\":false,\"properties\":{\"actionId\":{\"type\":\"string\"},\"actionRevision\":{\"type\":\"string\"},\"application\":{\"additionalProperties\":false,\"properties\":{\"applicationId\":{\"type\":\"string\"},\"effectDigest\":{\"pattern\":\"^sha256:[0-9a-f]{64}$\",\"type\":\"string\"},\"resultLinks\":{\"items\":{\"additionalProperties\":false,\"properties\":{\"recordId\":{\"type\":\"string\"},\"recordType\":{\"type\":\"string\"},\"revision\":{\"minimum\":1,\"type\":\"integer\"}},\"required\":[\"recordType\",\"recordId\",\"revision\"],\"type\":\"object\"},\"maxItems\":16,\"type\":\"array\"},\"submissionVersion\":{\"minimum\":1,\"type\":\"integer\"}},\"required\":[\"applicationId\",\"submissionVersion\",\"effectDigest\",\"resultLinks\"],\"type\":\"object\"},\"applicationStatus\":{\"additionalProperties\":false,\"properties\":{\"automaticRetry\":{\"additionalProperties\":false,\"properties\":{\"attempts\":{\"maximum\":1000,\"minimum\":0,\"type\":\"integer\"},\"maximumAttempts\":{\"maximum\":1000,\"minimum\":1,\"type\":\"integer\"},\"scheduled\":{\"type\":\"boolean\"}},\"required\":[\"scheduled\",\"attempts\",\"maximumAttempts\"],\"type\":\"object\"},\"mode\":{\"enum\":[\"automatic\",\"manual\"]},\"reason\":{\"enum\":[\"package-changed\",\"dependency-outage\",\"lease-expired\",\"application-refused\",\"attempts-exhausted\"]},\"recovery\":{\"enum\":[\"retry\",\"rebase\",\"revise\",\"correct-input\"]},\"state\":{\"enum\":[\"awaiting-review\",\"pending\",\"applying\",\"blocked\",\"applied\",\"cancelled\",\"rejected\"]}},\"required\":[\"state\",\"mode\"],\"type\":\"object\"},\"asks\":{\"items\":{\"additionalProperties\":false,\"properties\":{\"answer\":{\"additionalProperties\":false,\"properties\":{\"additions\":{\"items\":{\"type\":\"string\"},\"maxItems\":32,\"type\":\"array\",\"uniqueItems\":true},\"answeredAt\":{\"type\":\"string\"},\"text\":{\"maxLength\":2000,\"minLength\":1,\"type\":\"string\"}},\"required\":[\"additions\",\"answeredAt\"],\"type\":\"object\"},\"askedAt\":{\"type\":\"string\"},\"dueAt\":{\"type\":\"string\"},\"id\":{\"type\":\"string\"},\"links\":{\"additionalProperties\":false,\"properties\":{\"answer\":{\"additionalProperties\":false,\"properties\":{\"accessProfile\":{\"type\":\"string\"},\"availability\":{\"additionalProperties\":false,\"if\":{\"properties\":{\"available\":{\"const\":false}}},\"properties\":{\"available\":{\"type\":\"boolean\"},\"observedRevision\":{\"minimum\":1,\"type\":\"integer\"},\"reason\":{\"enum\":[\"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\":{\"enum\":[\"refresh\",\"revise\",\"retry\",\"rebase\",\"correct-input\",\"receipt-only\"]}},\"required\":[\"available\",\"observedRevision\"],\"then\":{\"required\":[\"reason\",\"recovery\"]},\"type\":\"object\"},\"ifMatch\":{\"type\":\"string\"},\"method\":{\"const\":\"POST\"},\"operation\":{\"const\":\"answer\"},\"path\":{\"type\":\"string\"}},\"required\":[\"method\",\"path\",\"accessProfile\",\"operation\",\"ifMatch\",\"availability\"],\"type\":\"object\"}},\"type\":\"object\"},\"state\":{\"enum\":[\"open\",\"answered\",\"expired\",\"closed\"]},\"text\":{\"maxLength\":2000,\"minLength\":1,\"type\":\"string\"},\"wants\":{\"items\":{\"additionalProperties\":false,\"properties\":{\"kind\":{\"enum\":[\"answer\",\"document\"]}},\"required\":[\"kind\"],\"type\":\"object\"},\"maxItems\":8,\"type\":\"array\",\"uniqueItems\":true}},\"required\":[\"id\",\"text\",\"wants\",\"askedAt\",\"state\",\"links\"],\"type\":\"object\"},\"maxItems\":50,\"type\":\"array\"},\"attachments\":{\"additionalProperties\":{\"additionalProperties\":false,\"properties\":{\"classification\":{\"enum\":[\"public\",\"internal\",\"restricted\"]},\"contentTypes\":{\"items\":{\"type\":\"string\"},\"maxItems\":16,\"minItems\":1,\"type\":\"array\",\"uniqueItems\":true},\"id\":{\"type\":\"string\"},\"links\":{\"additionalProperties\":{\"additionalProperties\":false,\"properties\":{\"accessProfile\":{\"type\":\"string\"},\"availability\":{\"additionalProperties\":false,\"if\":{\"properties\":{\"available\":{\"const\":false}}},\"properties\":{\"available\":{\"type\":\"boolean\"},\"observedRevision\":{\"minimum\":1,\"type\":\"integer\"},\"reason\":{\"enum\":[\"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\":{\"enum\":[\"refresh\",\"revise\",\"retry\",\"rebase\",\"correct-input\",\"receipt-only\"]}},\"required\":[\"available\",\"observedRevision\"],\"then\":{\"required\":[\"reason\",\"recovery\"]},\"type\":\"object\"},\"ifMatch\":{\"type\":\"string\"},\"method\":{\"enum\":[\"GET\",\"PATCH\",\"DELETE\"]},\"operation\":{\"enum\":[\"download\",\"upload\",\"remove\"]},\"path\":{\"type\":\"string\"}},\"required\":[\"method\",\"path\",\"accessProfile\",\"operation\"],\"type\":\"object\"},\"type\":\"object\"},\"maximumBytes\":{\"maximum\":16777216,\"minimum\":1,\"type\":\"integer\"},\"required\":{\"type\":\"boolean\"},\"value\":{\"additionalProperties\":false,\"properties\":{\"byteSize\":{\"minimum\":1,\"type\":\"integer\"},\"contentType\":{\"type\":\"string\"},\"sha256\":{\"pattern\":\"^[a-f0-9]{64}$\",\"type\":\"string\"},\"submissionVersion\":{\"minimum\":0,\"type\":\"integer\"},\"uploadedAt\":{\"type\":\"string\"},\"verificationStatus\":{\"enum\":[\"notRequired\",\"pending\",\"approved\",\"rejected\"]}},\"required\":[\"submissionVersion\",\"sha256\",\"contentType\",\"byteSize\",\"verificationStatus\"],\"type\":\"object\"}},\"required\":[\"id\",\"required\",\"maximumBytes\",\"contentTypes\",\"classification\",\"links\"],\"type\":\"object\"},\"maxProperties\":8,\"type\":\"object\"},\"blockedReason\":{\"enum\":[\"package-changed\"]},\"createdAt\":{\"type\":\"string\"},\"decision\":{\"additionalProperties\":false,\"properties\":{\"decidedAt\":{\"type\":\"string\"},\"publicReason\":{\"minLength\":1,\"pattern\":\"^[^\\\\u0000-\\\\u001F\\\\u007F-\\\\u009F]*[^\\\\u0000-\\\\u0020\\\\u007F-\\\\u00A0\\\\u1680\\\\u2000-\\\\u200A\\\\u2028\\\\u2029\\\\u202F\\\\u205F\\\\u3000][^\\\\u0000-\\\\u001F\\\\u007F-\\\\u009F]*$\",\"type\":\"string\"},\"status\":{\"enum\":[\"approved\",\"rejected\",\"changes-requested\",\"answered\"]}},\"required\":[\"status\",\"decidedAt\"],\"type\":\"object\"},\"effectDigest\":{\"type\":\"string\"},\"handoffRefusal\":{\"additionalProperties\":false,\"properties\":{\"code\":{\"enum\":[\"review.initiator-required\",\"review.initiator-excluded\",\"review.policy-mismatch\",\"review.refused\"]}},\"required\":[\"code\"],\"type\":\"object\"},\"id\":{\"type\":\"string\"},\"input\":{\"type\":\"object\"},\"links\":{\"additionalProperties\":{\"additionalProperties\":false,\"properties\":{\"accessProfile\":{\"type\":\"string\"},\"availability\":{\"additionalProperties\":false,\"if\":{\"properties\":{\"available\":{\"const\":false}}},\"properties\":{\"available\":{\"type\":\"boolean\"},\"observedRevision\":{\"minimum\":1,\"type\":\"integer\"},\"reason\":{\"enum\":[\"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\":{\"enum\":[\"refresh\",\"revise\",\"retry\",\"rebase\",\"correct-input\",\"receipt-only\"]}},\"required\":[\"available\",\"observedRevision\"],\"then\":{\"required\":[\"reason\",\"recovery\"]},\"type\":\"object\"},\"ifMatch\":{\"type\":\"string\"},\"method\":{\"enum\":[\"GET\",\"POST\"]},\"operation\":{\"type\":\"string\"},\"path\":{\"type\":\"string\"}},\"required\":[\"method\",\"path\",\"accessProfile\",\"operation\"],\"type\":\"object\"},\"type\":\"object\"},\"revision\":{\"minimum\":1,\"type\":\"integer\"},\"state\":{\"enum\":[\"draft\",\"submitted\",\"applied\",\"cancelled\",\"rejected\"]},\"status\":{\"enum\":[\"draft\",\"awaiting-party\",\"in-review\",\"approved\",\"processing\",\"applied\",\"rejected\",\"cancelled\"]},\"submissionVersion\":{\"minimum\":0,\"type\":\"integer\"},\"title\":{\"maxLength\":1024,\"type\":\"string\"},\"turn\":{\"enum\":[\"party\",\"official\",\"nobody\"]}},\"required\":[\"id\",\"actionId\",\"actionRevision\",\"submissionVersion\",\"revision\",\"state\",\"turn\",\"links\"],\"type\":\"object\"}")], + ["/paths/~1v1~1proposals~1{proposal_id}~1rebase/post/responses/200/content/application~1json/schema", JSON.parse("{\"additionalProperties\":false,\"properties\":{\"actionId\":{\"type\":\"string\"},\"actionRevision\":{\"type\":\"string\"},\"application\":{\"additionalProperties\":false,\"properties\":{\"applicationId\":{\"type\":\"string\"},\"effectDigest\":{\"pattern\":\"^sha256:[0-9a-f]{64}$\",\"type\":\"string\"},\"resultLinks\":{\"items\":{\"additionalProperties\":false,\"properties\":{\"recordId\":{\"type\":\"string\"},\"recordType\":{\"type\":\"string\"},\"revision\":{\"minimum\":1,\"type\":\"integer\"}},\"required\":[\"recordType\",\"recordId\",\"revision\"],\"type\":\"object\"},\"maxItems\":16,\"type\":\"array\"},\"submissionVersion\":{\"minimum\":1,\"type\":\"integer\"}},\"required\":[\"applicationId\",\"submissionVersion\",\"effectDigest\",\"resultLinks\"],\"type\":\"object\"},\"applicationStatus\":{\"additionalProperties\":false,\"properties\":{\"automaticRetry\":{\"additionalProperties\":false,\"properties\":{\"attempts\":{\"maximum\":1000,\"minimum\":0,\"type\":\"integer\"},\"maximumAttempts\":{\"maximum\":1000,\"minimum\":1,\"type\":\"integer\"},\"scheduled\":{\"type\":\"boolean\"}},\"required\":[\"scheduled\",\"attempts\",\"maximumAttempts\"],\"type\":\"object\"},\"mode\":{\"enum\":[\"automatic\",\"manual\"]},\"reason\":{\"enum\":[\"package-changed\",\"dependency-outage\",\"lease-expired\",\"application-refused\",\"attempts-exhausted\"]},\"recovery\":{\"enum\":[\"retry\",\"rebase\",\"revise\",\"correct-input\"]},\"state\":{\"enum\":[\"awaiting-review\",\"pending\",\"applying\",\"blocked\",\"applied\",\"cancelled\",\"rejected\"]}},\"required\":[\"state\",\"mode\"],\"type\":\"object\"},\"asks\":{\"items\":{\"additionalProperties\":false,\"properties\":{\"answer\":{\"additionalProperties\":false,\"properties\":{\"additions\":{\"items\":{\"type\":\"string\"},\"maxItems\":32,\"type\":\"array\",\"uniqueItems\":true},\"answeredAt\":{\"type\":\"string\"},\"formEntries\":{\"items\":{\"type\":\"string\"},\"maxItems\":32,\"type\":\"array\",\"uniqueItems\":true},\"text\":{\"maxLength\":2000,\"minLength\":1,\"type\":\"string\"}},\"required\":[\"additions\",\"answeredAt\"],\"type\":\"object\"},\"askedAt\":{\"type\":\"string\"},\"dueAt\":{\"type\":\"string\"},\"id\":{\"type\":\"string\"},\"links\":{\"additionalProperties\":false,\"properties\":{\"answer\":{\"additionalProperties\":false,\"properties\":{\"accessProfile\":{\"type\":\"string\"},\"availability\":{\"additionalProperties\":false,\"if\":{\"properties\":{\"available\":{\"const\":false}}},\"properties\":{\"available\":{\"type\":\"boolean\"},\"observedRevision\":{\"minimum\":1,\"type\":\"integer\"},\"reason\":{\"enum\":[\"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\":{\"enum\":[\"refresh\",\"revise\",\"retry\",\"rebase\",\"correct-input\",\"receipt-only\"]}},\"required\":[\"available\",\"observedRevision\"],\"then\":{\"required\":[\"reason\",\"recovery\"]},\"type\":\"object\"},\"ifMatch\":{\"type\":\"string\"},\"method\":{\"const\":\"POST\"},\"operation\":{\"const\":\"answer\"},\"path\":{\"type\":\"string\"}},\"required\":[\"method\",\"path\",\"accessProfile\",\"operation\",\"ifMatch\",\"availability\"],\"type\":\"object\"}},\"type\":\"object\"},\"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\",\"links\"],\"type\":\"object\"},\"maxItems\":50,\"type\":\"array\"},\"attachments\":{\"additionalProperties\":{\"additionalProperties\":false,\"properties\":{\"classification\":{\"enum\":[\"public\",\"internal\",\"restricted\"]},\"contentTypes\":{\"items\":{\"type\":\"string\"},\"maxItems\":16,\"minItems\":1,\"type\":\"array\",\"uniqueItems\":true},\"id\":{\"type\":\"string\"},\"links\":{\"additionalProperties\":{\"additionalProperties\":false,\"properties\":{\"accessProfile\":{\"type\":\"string\"},\"availability\":{\"additionalProperties\":false,\"if\":{\"properties\":{\"available\":{\"const\":false}}},\"properties\":{\"available\":{\"type\":\"boolean\"},\"observedRevision\":{\"minimum\":1,\"type\":\"integer\"},\"reason\":{\"enum\":[\"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\":{\"enum\":[\"refresh\",\"revise\",\"retry\",\"rebase\",\"correct-input\",\"receipt-only\"]}},\"required\":[\"available\",\"observedRevision\"],\"then\":{\"required\":[\"reason\",\"recovery\"]},\"type\":\"object\"},\"ifMatch\":{\"type\":\"string\"},\"method\":{\"enum\":[\"GET\",\"PATCH\",\"DELETE\"]},\"operation\":{\"enum\":[\"download\",\"upload\",\"remove\"]},\"path\":{\"type\":\"string\"}},\"required\":[\"method\",\"path\",\"accessProfile\",\"operation\"],\"type\":\"object\"},\"type\":\"object\"},\"maximumBytes\":{\"maximum\":16777216,\"minimum\":1,\"type\":\"integer\"},\"required\":{\"type\":\"boolean\"},\"value\":{\"additionalProperties\":false,\"properties\":{\"byteSize\":{\"minimum\":1,\"type\":\"integer\"},\"contentType\":{\"type\":\"string\"},\"sha256\":{\"pattern\":\"^[a-f0-9]{64}$\",\"type\":\"string\"},\"submissionVersion\":{\"minimum\":0,\"type\":\"integer\"},\"uploadedAt\":{\"type\":\"string\"},\"verificationStatus\":{\"enum\":[\"notRequired\",\"pending\",\"approved\",\"rejected\"]}},\"required\":[\"submissionVersion\",\"sha256\",\"contentType\",\"byteSize\",\"verificationStatus\"],\"type\":\"object\"}},\"required\":[\"id\",\"required\",\"maximumBytes\",\"contentTypes\",\"classification\",\"links\"],\"type\":\"object\"},\"maxProperties\":8,\"type\":\"object\"},\"blockedReason\":{\"enum\":[\"package-changed\"]},\"createdAt\":{\"type\":\"string\"},\"decision\":{\"additionalProperties\":false,\"properties\":{\"decidedAt\":{\"type\":\"string\"},\"publicReason\":{\"minLength\":1,\"pattern\":\"^[^\\\\u0000-\\\\u001F\\\\u007F-\\\\u009F]*[^\\\\u0000-\\\\u0020\\\\u007F-\\\\u00A0\\\\u1680\\\\u2000-\\\\u200A\\\\u2028\\\\u2029\\\\u202F\\\\u205F\\\\u3000][^\\\\u0000-\\\\u001F\\\\u007F-\\\\u009F]*$\",\"type\":\"string\"},\"status\":{\"enum\":[\"approved\",\"rejected\",\"changes-requested\",\"answered\"]}},\"required\":[\"status\",\"decidedAt\"],\"type\":\"object\"},\"effectDigest\":{\"type\":\"string\"},\"handoffRefusal\":{\"additionalProperties\":false,\"properties\":{\"code\":{\"enum\":[\"review.initiator-required\",\"review.initiator-excluded\",\"review.policy-mismatch\",\"review.refused\"]}},\"required\":[\"code\"],\"type\":\"object\"},\"id\":{\"type\":\"string\"},\"input\":{\"type\":\"object\"},\"links\":{\"additionalProperties\":{\"additionalProperties\":false,\"properties\":{\"accessProfile\":{\"type\":\"string\"},\"availability\":{\"additionalProperties\":false,\"if\":{\"properties\":{\"available\":{\"const\":false}}},\"properties\":{\"available\":{\"type\":\"boolean\"},\"observedRevision\":{\"minimum\":1,\"type\":\"integer\"},\"reason\":{\"enum\":[\"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\":{\"enum\":[\"refresh\",\"revise\",\"retry\",\"rebase\",\"correct-input\",\"receipt-only\"]}},\"required\":[\"available\",\"observedRevision\"],\"then\":{\"required\":[\"reason\",\"recovery\"]},\"type\":\"object\"},\"ifMatch\":{\"type\":\"string\"},\"method\":{\"enum\":[\"GET\",\"POST\"]},\"operation\":{\"type\":\"string\"},\"path\":{\"type\":\"string\"}},\"required\":[\"method\",\"path\",\"accessProfile\",\"operation\"],\"type\":\"object\"},\"type\":\"object\"},\"partyRole\":{\"enum\":[\"owner\",\"subject\"]},\"revision\":{\"minimum\":1,\"type\":\"integer\"},\"state\":{\"enum\":[\"draft\",\"submitted\",\"applied\",\"cancelled\",\"rejected\"]},\"status\":{\"enum\":[\"draft\",\"awaiting-party\",\"in-review\",\"approved\",\"processing\",\"applied\",\"rejected\",\"cancelled\"]},\"submissionVersion\":{\"minimum\":0,\"type\":\"integer\"},\"title\":{\"maxLength\":1024,\"type\":\"string\"},\"turn\":{\"enum\":[\"party\",\"official\",\"nobody\"]}},\"required\":[\"id\",\"actionId\",\"actionRevision\",\"submissionVersion\",\"revision\",\"state\",\"turn\",\"links\"],\"type\":\"object\"}")], ["/paths/~1v1~1proposals~1{proposal_id}~1rebase/post/responses/400/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"access-profile.ambiguous\",\"request.invalid\"]}},\"type\":\"object\"}]}")], ["/paths/~1v1~1proposals~1{proposal_id}~1rebase/post/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}~1rebase/post/responses/403/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"profile.not-authorized\"]}},\"type\":\"object\"}]}")], @@ -259,7 +263,7 @@ const rules: Record = Object.fromEntries([ ["/paths/~1v1~1proposals~1{proposal_id}~1rebase/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}~1rebase/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}~1rebase/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}~1retry/post/responses/200/content/application~1json/schema", JSON.parse("{\"additionalProperties\":false,\"properties\":{\"actionId\":{\"type\":\"string\"},\"actionRevision\":{\"type\":\"string\"},\"application\":{\"additionalProperties\":false,\"properties\":{\"applicationId\":{\"type\":\"string\"},\"effectDigest\":{\"pattern\":\"^sha256:[0-9a-f]{64}$\",\"type\":\"string\"},\"resultLinks\":{\"items\":{\"additionalProperties\":false,\"properties\":{\"recordId\":{\"type\":\"string\"},\"recordType\":{\"type\":\"string\"},\"revision\":{\"minimum\":1,\"type\":\"integer\"}},\"required\":[\"recordType\",\"recordId\",\"revision\"],\"type\":\"object\"},\"maxItems\":16,\"type\":\"array\"},\"submissionVersion\":{\"minimum\":1,\"type\":\"integer\"}},\"required\":[\"applicationId\",\"submissionVersion\",\"effectDigest\",\"resultLinks\"],\"type\":\"object\"},\"applicationStatus\":{\"additionalProperties\":false,\"properties\":{\"automaticRetry\":{\"additionalProperties\":false,\"properties\":{\"attempts\":{\"maximum\":1000,\"minimum\":0,\"type\":\"integer\"},\"maximumAttempts\":{\"maximum\":1000,\"minimum\":1,\"type\":\"integer\"},\"scheduled\":{\"type\":\"boolean\"}},\"required\":[\"scheduled\",\"attempts\",\"maximumAttempts\"],\"type\":\"object\"},\"mode\":{\"enum\":[\"automatic\",\"manual\"]},\"reason\":{\"enum\":[\"package-changed\",\"dependency-outage\",\"lease-expired\",\"application-refused\",\"attempts-exhausted\"]},\"recovery\":{\"enum\":[\"retry\",\"rebase\",\"revise\",\"correct-input\"]},\"state\":{\"enum\":[\"awaiting-review\",\"pending\",\"applying\",\"blocked\",\"applied\",\"cancelled\",\"rejected\"]}},\"required\":[\"state\",\"mode\"],\"type\":\"object\"},\"asks\":{\"items\":{\"additionalProperties\":false,\"properties\":{\"answer\":{\"additionalProperties\":false,\"properties\":{\"additions\":{\"items\":{\"type\":\"string\"},\"maxItems\":32,\"type\":\"array\",\"uniqueItems\":true},\"answeredAt\":{\"type\":\"string\"},\"text\":{\"maxLength\":2000,\"minLength\":1,\"type\":\"string\"}},\"required\":[\"additions\",\"answeredAt\"],\"type\":\"object\"},\"askedAt\":{\"type\":\"string\"},\"dueAt\":{\"type\":\"string\"},\"id\":{\"type\":\"string\"},\"links\":{\"additionalProperties\":false,\"properties\":{\"answer\":{\"additionalProperties\":false,\"properties\":{\"accessProfile\":{\"type\":\"string\"},\"availability\":{\"additionalProperties\":false,\"if\":{\"properties\":{\"available\":{\"const\":false}}},\"properties\":{\"available\":{\"type\":\"boolean\"},\"observedRevision\":{\"minimum\":1,\"type\":\"integer\"},\"reason\":{\"enum\":[\"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\":{\"enum\":[\"refresh\",\"revise\",\"retry\",\"rebase\",\"correct-input\",\"receipt-only\"]}},\"required\":[\"available\",\"observedRevision\"],\"then\":{\"required\":[\"reason\",\"recovery\"]},\"type\":\"object\"},\"ifMatch\":{\"type\":\"string\"},\"method\":{\"const\":\"POST\"},\"operation\":{\"const\":\"answer\"},\"path\":{\"type\":\"string\"}},\"required\":[\"method\",\"path\",\"accessProfile\",\"operation\",\"ifMatch\",\"availability\"],\"type\":\"object\"}},\"type\":\"object\"},\"state\":{\"enum\":[\"open\",\"answered\",\"expired\",\"closed\"]},\"text\":{\"maxLength\":2000,\"minLength\":1,\"type\":\"string\"},\"wants\":{\"items\":{\"additionalProperties\":false,\"properties\":{\"kind\":{\"enum\":[\"answer\",\"document\"]}},\"required\":[\"kind\"],\"type\":\"object\"},\"maxItems\":8,\"type\":\"array\",\"uniqueItems\":true}},\"required\":[\"id\",\"text\",\"wants\",\"askedAt\",\"state\",\"links\"],\"type\":\"object\"},\"maxItems\":50,\"type\":\"array\"},\"attachments\":{\"additionalProperties\":{\"additionalProperties\":false,\"properties\":{\"classification\":{\"enum\":[\"public\",\"internal\",\"restricted\"]},\"contentTypes\":{\"items\":{\"type\":\"string\"},\"maxItems\":16,\"minItems\":1,\"type\":\"array\",\"uniqueItems\":true},\"id\":{\"type\":\"string\"},\"links\":{\"additionalProperties\":{\"additionalProperties\":false,\"properties\":{\"accessProfile\":{\"type\":\"string\"},\"availability\":{\"additionalProperties\":false,\"if\":{\"properties\":{\"available\":{\"const\":false}}},\"properties\":{\"available\":{\"type\":\"boolean\"},\"observedRevision\":{\"minimum\":1,\"type\":\"integer\"},\"reason\":{\"enum\":[\"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\":{\"enum\":[\"refresh\",\"revise\",\"retry\",\"rebase\",\"correct-input\",\"receipt-only\"]}},\"required\":[\"available\",\"observedRevision\"],\"then\":{\"required\":[\"reason\",\"recovery\"]},\"type\":\"object\"},\"ifMatch\":{\"type\":\"string\"},\"method\":{\"enum\":[\"GET\",\"PATCH\",\"DELETE\"]},\"operation\":{\"enum\":[\"download\",\"upload\",\"remove\"]},\"path\":{\"type\":\"string\"}},\"required\":[\"method\",\"path\",\"accessProfile\",\"operation\"],\"type\":\"object\"},\"type\":\"object\"},\"maximumBytes\":{\"maximum\":16777216,\"minimum\":1,\"type\":\"integer\"},\"required\":{\"type\":\"boolean\"},\"value\":{\"additionalProperties\":false,\"properties\":{\"byteSize\":{\"minimum\":1,\"type\":\"integer\"},\"contentType\":{\"type\":\"string\"},\"sha256\":{\"pattern\":\"^[a-f0-9]{64}$\",\"type\":\"string\"},\"submissionVersion\":{\"minimum\":0,\"type\":\"integer\"},\"uploadedAt\":{\"type\":\"string\"},\"verificationStatus\":{\"enum\":[\"notRequired\",\"pending\",\"approved\",\"rejected\"]}},\"required\":[\"submissionVersion\",\"sha256\",\"contentType\",\"byteSize\",\"verificationStatus\"],\"type\":\"object\"}},\"required\":[\"id\",\"required\",\"maximumBytes\",\"contentTypes\",\"classification\",\"links\"],\"type\":\"object\"},\"maxProperties\":8,\"type\":\"object\"},\"blockedReason\":{\"enum\":[\"package-changed\"]},\"createdAt\":{\"type\":\"string\"},\"decision\":{\"additionalProperties\":false,\"properties\":{\"decidedAt\":{\"type\":\"string\"},\"publicReason\":{\"minLength\":1,\"pattern\":\"^[^\\\\u0000-\\\\u001F\\\\u007F-\\\\u009F]*[^\\\\u0000-\\\\u0020\\\\u007F-\\\\u00A0\\\\u1680\\\\u2000-\\\\u200A\\\\u2028\\\\u2029\\\\u202F\\\\u205F\\\\u3000][^\\\\u0000-\\\\u001F\\\\u007F-\\\\u009F]*$\",\"type\":\"string\"},\"status\":{\"enum\":[\"approved\",\"rejected\",\"changes-requested\",\"answered\"]}},\"required\":[\"status\",\"decidedAt\"],\"type\":\"object\"},\"effectDigest\":{\"type\":\"string\"},\"handoffRefusal\":{\"additionalProperties\":false,\"properties\":{\"code\":{\"enum\":[\"review.initiator-required\",\"review.initiator-excluded\",\"review.policy-mismatch\",\"review.refused\"]}},\"required\":[\"code\"],\"type\":\"object\"},\"id\":{\"type\":\"string\"},\"input\":{\"type\":\"object\"},\"links\":{\"additionalProperties\":{\"additionalProperties\":false,\"properties\":{\"accessProfile\":{\"type\":\"string\"},\"availability\":{\"additionalProperties\":false,\"if\":{\"properties\":{\"available\":{\"const\":false}}},\"properties\":{\"available\":{\"type\":\"boolean\"},\"observedRevision\":{\"minimum\":1,\"type\":\"integer\"},\"reason\":{\"enum\":[\"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\":{\"enum\":[\"refresh\",\"revise\",\"retry\",\"rebase\",\"correct-input\",\"receipt-only\"]}},\"required\":[\"available\",\"observedRevision\"],\"then\":{\"required\":[\"reason\",\"recovery\"]},\"type\":\"object\"},\"ifMatch\":{\"type\":\"string\"},\"method\":{\"enum\":[\"GET\",\"POST\"]},\"operation\":{\"type\":\"string\"},\"path\":{\"type\":\"string\"}},\"required\":[\"method\",\"path\",\"accessProfile\",\"operation\"],\"type\":\"object\"},\"type\":\"object\"},\"revision\":{\"minimum\":1,\"type\":\"integer\"},\"state\":{\"enum\":[\"draft\",\"submitted\",\"applied\",\"cancelled\",\"rejected\"]},\"status\":{\"enum\":[\"draft\",\"awaiting-party\",\"in-review\",\"approved\",\"processing\",\"applied\",\"rejected\",\"cancelled\"]},\"submissionVersion\":{\"minimum\":0,\"type\":\"integer\"},\"title\":{\"maxLength\":1024,\"type\":\"string\"},\"turn\":{\"enum\":[\"party\",\"official\",\"nobody\"]}},\"required\":[\"id\",\"actionId\",\"actionRevision\",\"submissionVersion\",\"revision\",\"state\",\"turn\",\"links\"],\"type\":\"object\"}")], + ["/paths/~1v1~1proposals~1{proposal_id}~1retry/post/responses/200/content/application~1json/schema", JSON.parse("{\"additionalProperties\":false,\"properties\":{\"actionId\":{\"type\":\"string\"},\"actionRevision\":{\"type\":\"string\"},\"application\":{\"additionalProperties\":false,\"properties\":{\"applicationId\":{\"type\":\"string\"},\"effectDigest\":{\"pattern\":\"^sha256:[0-9a-f]{64}$\",\"type\":\"string\"},\"resultLinks\":{\"items\":{\"additionalProperties\":false,\"properties\":{\"recordId\":{\"type\":\"string\"},\"recordType\":{\"type\":\"string\"},\"revision\":{\"minimum\":1,\"type\":\"integer\"}},\"required\":[\"recordType\",\"recordId\",\"revision\"],\"type\":\"object\"},\"maxItems\":16,\"type\":\"array\"},\"submissionVersion\":{\"minimum\":1,\"type\":\"integer\"}},\"required\":[\"applicationId\",\"submissionVersion\",\"effectDigest\",\"resultLinks\"],\"type\":\"object\"},\"applicationStatus\":{\"additionalProperties\":false,\"properties\":{\"automaticRetry\":{\"additionalProperties\":false,\"properties\":{\"attempts\":{\"maximum\":1000,\"minimum\":0,\"type\":\"integer\"},\"maximumAttempts\":{\"maximum\":1000,\"minimum\":1,\"type\":\"integer\"},\"scheduled\":{\"type\":\"boolean\"}},\"required\":[\"scheduled\",\"attempts\",\"maximumAttempts\"],\"type\":\"object\"},\"mode\":{\"enum\":[\"automatic\",\"manual\"]},\"reason\":{\"enum\":[\"package-changed\",\"dependency-outage\",\"lease-expired\",\"application-refused\",\"attempts-exhausted\"]},\"recovery\":{\"enum\":[\"retry\",\"rebase\",\"revise\",\"correct-input\"]},\"state\":{\"enum\":[\"awaiting-review\",\"pending\",\"applying\",\"blocked\",\"applied\",\"cancelled\",\"rejected\"]}},\"required\":[\"state\",\"mode\"],\"type\":\"object\"},\"asks\":{\"items\":{\"additionalProperties\":false,\"properties\":{\"answer\":{\"additionalProperties\":false,\"properties\":{\"additions\":{\"items\":{\"type\":\"string\"},\"maxItems\":32,\"type\":\"array\",\"uniqueItems\":true},\"answeredAt\":{\"type\":\"string\"},\"formEntries\":{\"items\":{\"type\":\"string\"},\"maxItems\":32,\"type\":\"array\",\"uniqueItems\":true},\"text\":{\"maxLength\":2000,\"minLength\":1,\"type\":\"string\"}},\"required\":[\"additions\",\"answeredAt\"],\"type\":\"object\"},\"askedAt\":{\"type\":\"string\"},\"dueAt\":{\"type\":\"string\"},\"id\":{\"type\":\"string\"},\"links\":{\"additionalProperties\":false,\"properties\":{\"answer\":{\"additionalProperties\":false,\"properties\":{\"accessProfile\":{\"type\":\"string\"},\"availability\":{\"additionalProperties\":false,\"if\":{\"properties\":{\"available\":{\"const\":false}}},\"properties\":{\"available\":{\"type\":\"boolean\"},\"observedRevision\":{\"minimum\":1,\"type\":\"integer\"},\"reason\":{\"enum\":[\"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\":{\"enum\":[\"refresh\",\"revise\",\"retry\",\"rebase\",\"correct-input\",\"receipt-only\"]}},\"required\":[\"available\",\"observedRevision\"],\"then\":{\"required\":[\"reason\",\"recovery\"]},\"type\":\"object\"},\"ifMatch\":{\"type\":\"string\"},\"method\":{\"const\":\"POST\"},\"operation\":{\"const\":\"answer\"},\"path\":{\"type\":\"string\"}},\"required\":[\"method\",\"path\",\"accessProfile\",\"operation\",\"ifMatch\",\"availability\"],\"type\":\"object\"}},\"type\":\"object\"},\"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\",\"links\"],\"type\":\"object\"},\"maxItems\":50,\"type\":\"array\"},\"attachments\":{\"additionalProperties\":{\"additionalProperties\":false,\"properties\":{\"classification\":{\"enum\":[\"public\",\"internal\",\"restricted\"]},\"contentTypes\":{\"items\":{\"type\":\"string\"},\"maxItems\":16,\"minItems\":1,\"type\":\"array\",\"uniqueItems\":true},\"id\":{\"type\":\"string\"},\"links\":{\"additionalProperties\":{\"additionalProperties\":false,\"properties\":{\"accessProfile\":{\"type\":\"string\"},\"availability\":{\"additionalProperties\":false,\"if\":{\"properties\":{\"available\":{\"const\":false}}},\"properties\":{\"available\":{\"type\":\"boolean\"},\"observedRevision\":{\"minimum\":1,\"type\":\"integer\"},\"reason\":{\"enum\":[\"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\":{\"enum\":[\"refresh\",\"revise\",\"retry\",\"rebase\",\"correct-input\",\"receipt-only\"]}},\"required\":[\"available\",\"observedRevision\"],\"then\":{\"required\":[\"reason\",\"recovery\"]},\"type\":\"object\"},\"ifMatch\":{\"type\":\"string\"},\"method\":{\"enum\":[\"GET\",\"PATCH\",\"DELETE\"]},\"operation\":{\"enum\":[\"download\",\"upload\",\"remove\"]},\"path\":{\"type\":\"string\"}},\"required\":[\"method\",\"path\",\"accessProfile\",\"operation\"],\"type\":\"object\"},\"type\":\"object\"},\"maximumBytes\":{\"maximum\":16777216,\"minimum\":1,\"type\":\"integer\"},\"required\":{\"type\":\"boolean\"},\"value\":{\"additionalProperties\":false,\"properties\":{\"byteSize\":{\"minimum\":1,\"type\":\"integer\"},\"contentType\":{\"type\":\"string\"},\"sha256\":{\"pattern\":\"^[a-f0-9]{64}$\",\"type\":\"string\"},\"submissionVersion\":{\"minimum\":0,\"type\":\"integer\"},\"uploadedAt\":{\"type\":\"string\"},\"verificationStatus\":{\"enum\":[\"notRequired\",\"pending\",\"approved\",\"rejected\"]}},\"required\":[\"submissionVersion\",\"sha256\",\"contentType\",\"byteSize\",\"verificationStatus\"],\"type\":\"object\"}},\"required\":[\"id\",\"required\",\"maximumBytes\",\"contentTypes\",\"classification\",\"links\"],\"type\":\"object\"},\"maxProperties\":8,\"type\":\"object\"},\"blockedReason\":{\"enum\":[\"package-changed\"]},\"createdAt\":{\"type\":\"string\"},\"decision\":{\"additionalProperties\":false,\"properties\":{\"decidedAt\":{\"type\":\"string\"},\"publicReason\":{\"minLength\":1,\"pattern\":\"^[^\\\\u0000-\\\\u001F\\\\u007F-\\\\u009F]*[^\\\\u0000-\\\\u0020\\\\u007F-\\\\u00A0\\\\u1680\\\\u2000-\\\\u200A\\\\u2028\\\\u2029\\\\u202F\\\\u205F\\\\u3000][^\\\\u0000-\\\\u001F\\\\u007F-\\\\u009F]*$\",\"type\":\"string\"},\"status\":{\"enum\":[\"approved\",\"rejected\",\"changes-requested\",\"answered\"]}},\"required\":[\"status\",\"decidedAt\"],\"type\":\"object\"},\"effectDigest\":{\"type\":\"string\"},\"handoffRefusal\":{\"additionalProperties\":false,\"properties\":{\"code\":{\"enum\":[\"review.initiator-required\",\"review.initiator-excluded\",\"review.policy-mismatch\",\"review.refused\"]}},\"required\":[\"code\"],\"type\":\"object\"},\"id\":{\"type\":\"string\"},\"input\":{\"type\":\"object\"},\"links\":{\"additionalProperties\":{\"additionalProperties\":false,\"properties\":{\"accessProfile\":{\"type\":\"string\"},\"availability\":{\"additionalProperties\":false,\"if\":{\"properties\":{\"available\":{\"const\":false}}},\"properties\":{\"available\":{\"type\":\"boolean\"},\"observedRevision\":{\"minimum\":1,\"type\":\"integer\"},\"reason\":{\"enum\":[\"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\":{\"enum\":[\"refresh\",\"revise\",\"retry\",\"rebase\",\"correct-input\",\"receipt-only\"]}},\"required\":[\"available\",\"observedRevision\"],\"then\":{\"required\":[\"reason\",\"recovery\"]},\"type\":\"object\"},\"ifMatch\":{\"type\":\"string\"},\"method\":{\"enum\":[\"GET\",\"POST\"]},\"operation\":{\"type\":\"string\"},\"path\":{\"type\":\"string\"}},\"required\":[\"method\",\"path\",\"accessProfile\",\"operation\"],\"type\":\"object\"},\"type\":\"object\"},\"partyRole\":{\"enum\":[\"owner\",\"subject\"]},\"revision\":{\"minimum\":1,\"type\":\"integer\"},\"state\":{\"enum\":[\"draft\",\"submitted\",\"applied\",\"cancelled\",\"rejected\"]},\"status\":{\"enum\":[\"draft\",\"awaiting-party\",\"in-review\",\"approved\",\"processing\",\"applied\",\"rejected\",\"cancelled\"]},\"submissionVersion\":{\"minimum\":0,\"type\":\"integer\"},\"title\":{\"maxLength\":1024,\"type\":\"string\"},\"turn\":{\"enum\":[\"party\",\"official\",\"nobody\"]}},\"required\":[\"id\",\"actionId\",\"actionRevision\",\"submissionVersion\",\"revision\",\"state\",\"turn\",\"links\"],\"type\":\"object\"}")], ["/paths/~1v1~1proposals~1{proposal_id}~1retry/post/responses/400/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"access-profile.ambiguous\",\"request.invalid\"]}},\"type\":\"object\"}]}")], ["/paths/~1v1~1proposals~1{proposal_id}~1retry/post/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}~1retry/post/responses/403/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"profile.not-authorized\"]}},\"type\":\"object\"}]}")], @@ -271,21 +275,21 @@ 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\"},\"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\":{\"additionalProperties\":false,\"properties\":{\"kind\":{\"enum\":[\"answer\",\"document\"]}},\"required\":[\"kind\"],\"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\"}]}")], ["/paths/~1v1~1proposals~1{proposal_id}~1review-status/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-status/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-status/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}~1revise/post/responses/200/content/application~1json/schema", JSON.parse("{\"additionalProperties\":false,\"properties\":{\"actionId\":{\"type\":\"string\"},\"actionRevision\":{\"type\":\"string\"},\"application\":{\"additionalProperties\":false,\"properties\":{\"applicationId\":{\"type\":\"string\"},\"effectDigest\":{\"pattern\":\"^sha256:[0-9a-f]{64}$\",\"type\":\"string\"},\"resultLinks\":{\"items\":{\"additionalProperties\":false,\"properties\":{\"recordId\":{\"type\":\"string\"},\"recordType\":{\"type\":\"string\"},\"revision\":{\"minimum\":1,\"type\":\"integer\"}},\"required\":[\"recordType\",\"recordId\",\"revision\"],\"type\":\"object\"},\"maxItems\":16,\"type\":\"array\"},\"submissionVersion\":{\"minimum\":1,\"type\":\"integer\"}},\"required\":[\"applicationId\",\"submissionVersion\",\"effectDigest\",\"resultLinks\"],\"type\":\"object\"},\"applicationStatus\":{\"additionalProperties\":false,\"properties\":{\"automaticRetry\":{\"additionalProperties\":false,\"properties\":{\"attempts\":{\"maximum\":1000,\"minimum\":0,\"type\":\"integer\"},\"maximumAttempts\":{\"maximum\":1000,\"minimum\":1,\"type\":\"integer\"},\"scheduled\":{\"type\":\"boolean\"}},\"required\":[\"scheduled\",\"attempts\",\"maximumAttempts\"],\"type\":\"object\"},\"mode\":{\"enum\":[\"automatic\",\"manual\"]},\"reason\":{\"enum\":[\"package-changed\",\"dependency-outage\",\"lease-expired\",\"application-refused\",\"attempts-exhausted\"]},\"recovery\":{\"enum\":[\"retry\",\"rebase\",\"revise\",\"correct-input\"]},\"state\":{\"enum\":[\"awaiting-review\",\"pending\",\"applying\",\"blocked\",\"applied\",\"cancelled\",\"rejected\"]}},\"required\":[\"state\",\"mode\"],\"type\":\"object\"},\"asks\":{\"items\":{\"additionalProperties\":false,\"properties\":{\"answer\":{\"additionalProperties\":false,\"properties\":{\"additions\":{\"items\":{\"type\":\"string\"},\"maxItems\":32,\"type\":\"array\",\"uniqueItems\":true},\"answeredAt\":{\"type\":\"string\"},\"text\":{\"maxLength\":2000,\"minLength\":1,\"type\":\"string\"}},\"required\":[\"additions\",\"answeredAt\"],\"type\":\"object\"},\"askedAt\":{\"type\":\"string\"},\"dueAt\":{\"type\":\"string\"},\"id\":{\"type\":\"string\"},\"links\":{\"additionalProperties\":false,\"properties\":{\"answer\":{\"additionalProperties\":false,\"properties\":{\"accessProfile\":{\"type\":\"string\"},\"availability\":{\"additionalProperties\":false,\"if\":{\"properties\":{\"available\":{\"const\":false}}},\"properties\":{\"available\":{\"type\":\"boolean\"},\"observedRevision\":{\"minimum\":1,\"type\":\"integer\"},\"reason\":{\"enum\":[\"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\":{\"enum\":[\"refresh\",\"revise\",\"retry\",\"rebase\",\"correct-input\",\"receipt-only\"]}},\"required\":[\"available\",\"observedRevision\"],\"then\":{\"required\":[\"reason\",\"recovery\"]},\"type\":\"object\"},\"ifMatch\":{\"type\":\"string\"},\"method\":{\"const\":\"POST\"},\"operation\":{\"const\":\"answer\"},\"path\":{\"type\":\"string\"}},\"required\":[\"method\",\"path\",\"accessProfile\",\"operation\",\"ifMatch\",\"availability\"],\"type\":\"object\"}},\"type\":\"object\"},\"state\":{\"enum\":[\"open\",\"answered\",\"expired\",\"closed\"]},\"text\":{\"maxLength\":2000,\"minLength\":1,\"type\":\"string\"},\"wants\":{\"items\":{\"additionalProperties\":false,\"properties\":{\"kind\":{\"enum\":[\"answer\",\"document\"]}},\"required\":[\"kind\"],\"type\":\"object\"},\"maxItems\":8,\"type\":\"array\",\"uniqueItems\":true}},\"required\":[\"id\",\"text\",\"wants\",\"askedAt\",\"state\",\"links\"],\"type\":\"object\"},\"maxItems\":50,\"type\":\"array\"},\"attachments\":{\"additionalProperties\":{\"additionalProperties\":false,\"properties\":{\"classification\":{\"enum\":[\"public\",\"internal\",\"restricted\"]},\"contentTypes\":{\"items\":{\"type\":\"string\"},\"maxItems\":16,\"minItems\":1,\"type\":\"array\",\"uniqueItems\":true},\"id\":{\"type\":\"string\"},\"links\":{\"additionalProperties\":{\"additionalProperties\":false,\"properties\":{\"accessProfile\":{\"type\":\"string\"},\"availability\":{\"additionalProperties\":false,\"if\":{\"properties\":{\"available\":{\"const\":false}}},\"properties\":{\"available\":{\"type\":\"boolean\"},\"observedRevision\":{\"minimum\":1,\"type\":\"integer\"},\"reason\":{\"enum\":[\"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\":{\"enum\":[\"refresh\",\"revise\",\"retry\",\"rebase\",\"correct-input\",\"receipt-only\"]}},\"required\":[\"available\",\"observedRevision\"],\"then\":{\"required\":[\"reason\",\"recovery\"]},\"type\":\"object\"},\"ifMatch\":{\"type\":\"string\"},\"method\":{\"enum\":[\"GET\",\"PATCH\",\"DELETE\"]},\"operation\":{\"enum\":[\"download\",\"upload\",\"remove\"]},\"path\":{\"type\":\"string\"}},\"required\":[\"method\",\"path\",\"accessProfile\",\"operation\"],\"type\":\"object\"},\"type\":\"object\"},\"maximumBytes\":{\"maximum\":16777216,\"minimum\":1,\"type\":\"integer\"},\"required\":{\"type\":\"boolean\"},\"value\":{\"additionalProperties\":false,\"properties\":{\"byteSize\":{\"minimum\":1,\"type\":\"integer\"},\"contentType\":{\"type\":\"string\"},\"sha256\":{\"pattern\":\"^[a-f0-9]{64}$\",\"type\":\"string\"},\"submissionVersion\":{\"minimum\":0,\"type\":\"integer\"},\"uploadedAt\":{\"type\":\"string\"},\"verificationStatus\":{\"enum\":[\"notRequired\",\"pending\",\"approved\",\"rejected\"]}},\"required\":[\"submissionVersion\",\"sha256\",\"contentType\",\"byteSize\",\"verificationStatus\"],\"type\":\"object\"}},\"required\":[\"id\",\"required\",\"maximumBytes\",\"contentTypes\",\"classification\",\"links\"],\"type\":\"object\"},\"maxProperties\":8,\"type\":\"object\"},\"blockedReason\":{\"enum\":[\"package-changed\"]},\"createdAt\":{\"type\":\"string\"},\"decision\":{\"additionalProperties\":false,\"properties\":{\"decidedAt\":{\"type\":\"string\"},\"publicReason\":{\"minLength\":1,\"pattern\":\"^[^\\\\u0000-\\\\u001F\\\\u007F-\\\\u009F]*[^\\\\u0000-\\\\u0020\\\\u007F-\\\\u00A0\\\\u1680\\\\u2000-\\\\u200A\\\\u2028\\\\u2029\\\\u202F\\\\u205F\\\\u3000][^\\\\u0000-\\\\u001F\\\\u007F-\\\\u009F]*$\",\"type\":\"string\"},\"status\":{\"enum\":[\"approved\",\"rejected\",\"changes-requested\",\"answered\"]}},\"required\":[\"status\",\"decidedAt\"],\"type\":\"object\"},\"effectDigest\":{\"type\":\"string\"},\"handoffRefusal\":{\"additionalProperties\":false,\"properties\":{\"code\":{\"enum\":[\"review.initiator-required\",\"review.initiator-excluded\",\"review.policy-mismatch\",\"review.refused\"]}},\"required\":[\"code\"],\"type\":\"object\"},\"id\":{\"type\":\"string\"},\"input\":{\"type\":\"object\"},\"links\":{\"additionalProperties\":{\"additionalProperties\":false,\"properties\":{\"accessProfile\":{\"type\":\"string\"},\"availability\":{\"additionalProperties\":false,\"if\":{\"properties\":{\"available\":{\"const\":false}}},\"properties\":{\"available\":{\"type\":\"boolean\"},\"observedRevision\":{\"minimum\":1,\"type\":\"integer\"},\"reason\":{\"enum\":[\"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\":{\"enum\":[\"refresh\",\"revise\",\"retry\",\"rebase\",\"correct-input\",\"receipt-only\"]}},\"required\":[\"available\",\"observedRevision\"],\"then\":{\"required\":[\"reason\",\"recovery\"]},\"type\":\"object\"},\"ifMatch\":{\"type\":\"string\"},\"method\":{\"enum\":[\"GET\",\"POST\"]},\"operation\":{\"type\":\"string\"},\"path\":{\"type\":\"string\"}},\"required\":[\"method\",\"path\",\"accessProfile\",\"operation\"],\"type\":\"object\"},\"type\":\"object\"},\"revision\":{\"minimum\":1,\"type\":\"integer\"},\"state\":{\"enum\":[\"draft\",\"submitted\",\"applied\",\"cancelled\",\"rejected\"]},\"status\":{\"enum\":[\"draft\",\"awaiting-party\",\"in-review\",\"approved\",\"processing\",\"applied\",\"rejected\",\"cancelled\"]},\"submissionVersion\":{\"minimum\":0,\"type\":\"integer\"},\"title\":{\"maxLength\":1024,\"type\":\"string\"},\"turn\":{\"enum\":[\"party\",\"official\",\"nobody\"]}},\"required\":[\"id\",\"actionId\",\"actionRevision\",\"submissionVersion\",\"revision\",\"state\",\"turn\",\"links\"],\"type\":\"object\"}")], + ["/paths/~1v1~1proposals~1{proposal_id}~1revise/post/responses/200/content/application~1json/schema", JSON.parse("{\"additionalProperties\":false,\"properties\":{\"actionId\":{\"type\":\"string\"},\"actionRevision\":{\"type\":\"string\"},\"application\":{\"additionalProperties\":false,\"properties\":{\"applicationId\":{\"type\":\"string\"},\"effectDigest\":{\"pattern\":\"^sha256:[0-9a-f]{64}$\",\"type\":\"string\"},\"resultLinks\":{\"items\":{\"additionalProperties\":false,\"properties\":{\"recordId\":{\"type\":\"string\"},\"recordType\":{\"type\":\"string\"},\"revision\":{\"minimum\":1,\"type\":\"integer\"}},\"required\":[\"recordType\",\"recordId\",\"revision\"],\"type\":\"object\"},\"maxItems\":16,\"type\":\"array\"},\"submissionVersion\":{\"minimum\":1,\"type\":\"integer\"}},\"required\":[\"applicationId\",\"submissionVersion\",\"effectDigest\",\"resultLinks\"],\"type\":\"object\"},\"applicationStatus\":{\"additionalProperties\":false,\"properties\":{\"automaticRetry\":{\"additionalProperties\":false,\"properties\":{\"attempts\":{\"maximum\":1000,\"minimum\":0,\"type\":\"integer\"},\"maximumAttempts\":{\"maximum\":1000,\"minimum\":1,\"type\":\"integer\"},\"scheduled\":{\"type\":\"boolean\"}},\"required\":[\"scheduled\",\"attempts\",\"maximumAttempts\"],\"type\":\"object\"},\"mode\":{\"enum\":[\"automatic\",\"manual\"]},\"reason\":{\"enum\":[\"package-changed\",\"dependency-outage\",\"lease-expired\",\"application-refused\",\"attempts-exhausted\"]},\"recovery\":{\"enum\":[\"retry\",\"rebase\",\"revise\",\"correct-input\"]},\"state\":{\"enum\":[\"awaiting-review\",\"pending\",\"applying\",\"blocked\",\"applied\",\"cancelled\",\"rejected\"]}},\"required\":[\"state\",\"mode\"],\"type\":\"object\"},\"asks\":{\"items\":{\"additionalProperties\":false,\"properties\":{\"answer\":{\"additionalProperties\":false,\"properties\":{\"additions\":{\"items\":{\"type\":\"string\"},\"maxItems\":32,\"type\":\"array\",\"uniqueItems\":true},\"answeredAt\":{\"type\":\"string\"},\"formEntries\":{\"items\":{\"type\":\"string\"},\"maxItems\":32,\"type\":\"array\",\"uniqueItems\":true},\"text\":{\"maxLength\":2000,\"minLength\":1,\"type\":\"string\"}},\"required\":[\"additions\",\"answeredAt\"],\"type\":\"object\"},\"askedAt\":{\"type\":\"string\"},\"dueAt\":{\"type\":\"string\"},\"id\":{\"type\":\"string\"},\"links\":{\"additionalProperties\":false,\"properties\":{\"answer\":{\"additionalProperties\":false,\"properties\":{\"accessProfile\":{\"type\":\"string\"},\"availability\":{\"additionalProperties\":false,\"if\":{\"properties\":{\"available\":{\"const\":false}}},\"properties\":{\"available\":{\"type\":\"boolean\"},\"observedRevision\":{\"minimum\":1,\"type\":\"integer\"},\"reason\":{\"enum\":[\"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\":{\"enum\":[\"refresh\",\"revise\",\"retry\",\"rebase\",\"correct-input\",\"receipt-only\"]}},\"required\":[\"available\",\"observedRevision\"],\"then\":{\"required\":[\"reason\",\"recovery\"]},\"type\":\"object\"},\"ifMatch\":{\"type\":\"string\"},\"method\":{\"const\":\"POST\"},\"operation\":{\"const\":\"answer\"},\"path\":{\"type\":\"string\"}},\"required\":[\"method\",\"path\",\"accessProfile\",\"operation\",\"ifMatch\",\"availability\"],\"type\":\"object\"}},\"type\":\"object\"},\"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\",\"links\"],\"type\":\"object\"},\"maxItems\":50,\"type\":\"array\"},\"attachments\":{\"additionalProperties\":{\"additionalProperties\":false,\"properties\":{\"classification\":{\"enum\":[\"public\",\"internal\",\"restricted\"]},\"contentTypes\":{\"items\":{\"type\":\"string\"},\"maxItems\":16,\"minItems\":1,\"type\":\"array\",\"uniqueItems\":true},\"id\":{\"type\":\"string\"},\"links\":{\"additionalProperties\":{\"additionalProperties\":false,\"properties\":{\"accessProfile\":{\"type\":\"string\"},\"availability\":{\"additionalProperties\":false,\"if\":{\"properties\":{\"available\":{\"const\":false}}},\"properties\":{\"available\":{\"type\":\"boolean\"},\"observedRevision\":{\"minimum\":1,\"type\":\"integer\"},\"reason\":{\"enum\":[\"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\":{\"enum\":[\"refresh\",\"revise\",\"retry\",\"rebase\",\"correct-input\",\"receipt-only\"]}},\"required\":[\"available\",\"observedRevision\"],\"then\":{\"required\":[\"reason\",\"recovery\"]},\"type\":\"object\"},\"ifMatch\":{\"type\":\"string\"},\"method\":{\"enum\":[\"GET\",\"PATCH\",\"DELETE\"]},\"operation\":{\"enum\":[\"download\",\"upload\",\"remove\"]},\"path\":{\"type\":\"string\"}},\"required\":[\"method\",\"path\",\"accessProfile\",\"operation\"],\"type\":\"object\"},\"type\":\"object\"},\"maximumBytes\":{\"maximum\":16777216,\"minimum\":1,\"type\":\"integer\"},\"required\":{\"type\":\"boolean\"},\"value\":{\"additionalProperties\":false,\"properties\":{\"byteSize\":{\"minimum\":1,\"type\":\"integer\"},\"contentType\":{\"type\":\"string\"},\"sha256\":{\"pattern\":\"^[a-f0-9]{64}$\",\"type\":\"string\"},\"submissionVersion\":{\"minimum\":0,\"type\":\"integer\"},\"uploadedAt\":{\"type\":\"string\"},\"verificationStatus\":{\"enum\":[\"notRequired\",\"pending\",\"approved\",\"rejected\"]}},\"required\":[\"submissionVersion\",\"sha256\",\"contentType\",\"byteSize\",\"verificationStatus\"],\"type\":\"object\"}},\"required\":[\"id\",\"required\",\"maximumBytes\",\"contentTypes\",\"classification\",\"links\"],\"type\":\"object\"},\"maxProperties\":8,\"type\":\"object\"},\"blockedReason\":{\"enum\":[\"package-changed\"]},\"createdAt\":{\"type\":\"string\"},\"decision\":{\"additionalProperties\":false,\"properties\":{\"decidedAt\":{\"type\":\"string\"},\"publicReason\":{\"minLength\":1,\"pattern\":\"^[^\\\\u0000-\\\\u001F\\\\u007F-\\\\u009F]*[^\\\\u0000-\\\\u0020\\\\u007F-\\\\u00A0\\\\u1680\\\\u2000-\\\\u200A\\\\u2028\\\\u2029\\\\u202F\\\\u205F\\\\u3000][^\\\\u0000-\\\\u001F\\\\u007F-\\\\u009F]*$\",\"type\":\"string\"},\"status\":{\"enum\":[\"approved\",\"rejected\",\"changes-requested\",\"answered\"]}},\"required\":[\"status\",\"decidedAt\"],\"type\":\"object\"},\"effectDigest\":{\"type\":\"string\"},\"handoffRefusal\":{\"additionalProperties\":false,\"properties\":{\"code\":{\"enum\":[\"review.initiator-required\",\"review.initiator-excluded\",\"review.policy-mismatch\",\"review.refused\"]}},\"required\":[\"code\"],\"type\":\"object\"},\"id\":{\"type\":\"string\"},\"input\":{\"type\":\"object\"},\"links\":{\"additionalProperties\":{\"additionalProperties\":false,\"properties\":{\"accessProfile\":{\"type\":\"string\"},\"availability\":{\"additionalProperties\":false,\"if\":{\"properties\":{\"available\":{\"const\":false}}},\"properties\":{\"available\":{\"type\":\"boolean\"},\"observedRevision\":{\"minimum\":1,\"type\":\"integer\"},\"reason\":{\"enum\":[\"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\":{\"enum\":[\"refresh\",\"revise\",\"retry\",\"rebase\",\"correct-input\",\"receipt-only\"]}},\"required\":[\"available\",\"observedRevision\"],\"then\":{\"required\":[\"reason\",\"recovery\"]},\"type\":\"object\"},\"ifMatch\":{\"type\":\"string\"},\"method\":{\"enum\":[\"GET\",\"POST\"]},\"operation\":{\"type\":\"string\"},\"path\":{\"type\":\"string\"}},\"required\":[\"method\",\"path\",\"accessProfile\",\"operation\"],\"type\":\"object\"},\"type\":\"object\"},\"partyRole\":{\"enum\":[\"owner\",\"subject\"]},\"revision\":{\"minimum\":1,\"type\":\"integer\"},\"state\":{\"enum\":[\"draft\",\"submitted\",\"applied\",\"cancelled\",\"rejected\"]},\"status\":{\"enum\":[\"draft\",\"awaiting-party\",\"in-review\",\"approved\",\"processing\",\"applied\",\"rejected\",\"cancelled\"]},\"submissionVersion\":{\"minimum\":0,\"type\":\"integer\"},\"title\":{\"maxLength\":1024,\"type\":\"string\"},\"turn\":{\"enum\":[\"party\",\"official\",\"nobody\"]}},\"required\":[\"id\",\"actionId\",\"actionRevision\",\"submissionVersion\",\"revision\",\"state\",\"turn\",\"links\"],\"type\":\"object\"}")], ["/paths/~1v1~1proposals~1{proposal_id}~1revise/post/responses/400/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"access-profile.ambiguous\",\"request.invalid\"]}},\"type\":\"object\"}]}")], ["/paths/~1v1~1proposals~1{proposal_id}~1revise/post/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}~1revise/post/responses/403/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"profile.not-authorized\"]}},\"type\":\"object\"}]}")], @@ -305,12 +309,12 @@ const rules: Record = Object.fromEntries([ ["/paths/~1v1~1proposals~1{proposal_id}~1submissions~1{submission_version}/get/responses/410/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"proposal.submission-expired\"]}},\"type\":\"object\"}]}")], ["/paths/~1v1~1proposals~1{proposal_id}~1submissions~1{submission_version}/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}~1submissions~1{submission_version}/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}~1submit/post/responses/200/content/application~1json/schema", JSON.parse("{\"additionalProperties\":false,\"properties\":{\"actionId\":{\"type\":\"string\"},\"actionRevision\":{\"type\":\"string\"},\"application\":{\"additionalProperties\":false,\"properties\":{\"applicationId\":{\"type\":\"string\"},\"effectDigest\":{\"pattern\":\"^sha256:[0-9a-f]{64}$\",\"type\":\"string\"},\"resultLinks\":{\"items\":{\"additionalProperties\":false,\"properties\":{\"recordId\":{\"type\":\"string\"},\"recordType\":{\"type\":\"string\"},\"revision\":{\"minimum\":1,\"type\":\"integer\"}},\"required\":[\"recordType\",\"recordId\",\"revision\"],\"type\":\"object\"},\"maxItems\":16,\"type\":\"array\"},\"submissionVersion\":{\"minimum\":1,\"type\":\"integer\"}},\"required\":[\"applicationId\",\"submissionVersion\",\"effectDigest\",\"resultLinks\"],\"type\":\"object\"},\"applicationStatus\":{\"additionalProperties\":false,\"properties\":{\"automaticRetry\":{\"additionalProperties\":false,\"properties\":{\"attempts\":{\"maximum\":1000,\"minimum\":0,\"type\":\"integer\"},\"maximumAttempts\":{\"maximum\":1000,\"minimum\":1,\"type\":\"integer\"},\"scheduled\":{\"type\":\"boolean\"}},\"required\":[\"scheduled\",\"attempts\",\"maximumAttempts\"],\"type\":\"object\"},\"mode\":{\"enum\":[\"automatic\",\"manual\"]},\"reason\":{\"enum\":[\"package-changed\",\"dependency-outage\",\"lease-expired\",\"application-refused\",\"attempts-exhausted\"]},\"recovery\":{\"enum\":[\"retry\",\"rebase\",\"revise\",\"correct-input\"]},\"state\":{\"enum\":[\"awaiting-review\",\"pending\",\"applying\",\"blocked\",\"applied\",\"cancelled\",\"rejected\"]}},\"required\":[\"state\",\"mode\"],\"type\":\"object\"},\"asks\":{\"items\":{\"additionalProperties\":false,\"properties\":{\"answer\":{\"additionalProperties\":false,\"properties\":{\"additions\":{\"items\":{\"type\":\"string\"},\"maxItems\":32,\"type\":\"array\",\"uniqueItems\":true},\"answeredAt\":{\"type\":\"string\"},\"text\":{\"maxLength\":2000,\"minLength\":1,\"type\":\"string\"}},\"required\":[\"additions\",\"answeredAt\"],\"type\":\"object\"},\"askedAt\":{\"type\":\"string\"},\"dueAt\":{\"type\":\"string\"},\"id\":{\"type\":\"string\"},\"links\":{\"additionalProperties\":false,\"properties\":{\"answer\":{\"additionalProperties\":false,\"properties\":{\"accessProfile\":{\"type\":\"string\"},\"availability\":{\"additionalProperties\":false,\"if\":{\"properties\":{\"available\":{\"const\":false}}},\"properties\":{\"available\":{\"type\":\"boolean\"},\"observedRevision\":{\"minimum\":1,\"type\":\"integer\"},\"reason\":{\"enum\":[\"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\":{\"enum\":[\"refresh\",\"revise\",\"retry\",\"rebase\",\"correct-input\",\"receipt-only\"]}},\"required\":[\"available\",\"observedRevision\"],\"then\":{\"required\":[\"reason\",\"recovery\"]},\"type\":\"object\"},\"ifMatch\":{\"type\":\"string\"},\"method\":{\"const\":\"POST\"},\"operation\":{\"const\":\"answer\"},\"path\":{\"type\":\"string\"}},\"required\":[\"method\",\"path\",\"accessProfile\",\"operation\",\"ifMatch\",\"availability\"],\"type\":\"object\"}},\"type\":\"object\"},\"state\":{\"enum\":[\"open\",\"answered\",\"expired\",\"closed\"]},\"text\":{\"maxLength\":2000,\"minLength\":1,\"type\":\"string\"},\"wants\":{\"items\":{\"additionalProperties\":false,\"properties\":{\"kind\":{\"enum\":[\"answer\",\"document\"]}},\"required\":[\"kind\"],\"type\":\"object\"},\"maxItems\":8,\"type\":\"array\",\"uniqueItems\":true}},\"required\":[\"id\",\"text\",\"wants\",\"askedAt\",\"state\",\"links\"],\"type\":\"object\"},\"maxItems\":50,\"type\":\"array\"},\"attachments\":{\"additionalProperties\":{\"additionalProperties\":false,\"properties\":{\"classification\":{\"enum\":[\"public\",\"internal\",\"restricted\"]},\"contentTypes\":{\"items\":{\"type\":\"string\"},\"maxItems\":16,\"minItems\":1,\"type\":\"array\",\"uniqueItems\":true},\"id\":{\"type\":\"string\"},\"links\":{\"additionalProperties\":{\"additionalProperties\":false,\"properties\":{\"accessProfile\":{\"type\":\"string\"},\"availability\":{\"additionalProperties\":false,\"if\":{\"properties\":{\"available\":{\"const\":false}}},\"properties\":{\"available\":{\"type\":\"boolean\"},\"observedRevision\":{\"minimum\":1,\"type\":\"integer\"},\"reason\":{\"enum\":[\"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\":{\"enum\":[\"refresh\",\"revise\",\"retry\",\"rebase\",\"correct-input\",\"receipt-only\"]}},\"required\":[\"available\",\"observedRevision\"],\"then\":{\"required\":[\"reason\",\"recovery\"]},\"type\":\"object\"},\"ifMatch\":{\"type\":\"string\"},\"method\":{\"enum\":[\"GET\",\"PATCH\",\"DELETE\"]},\"operation\":{\"enum\":[\"download\",\"upload\",\"remove\"]},\"path\":{\"type\":\"string\"}},\"required\":[\"method\",\"path\",\"accessProfile\",\"operation\"],\"type\":\"object\"},\"type\":\"object\"},\"maximumBytes\":{\"maximum\":16777216,\"minimum\":1,\"type\":\"integer\"},\"required\":{\"type\":\"boolean\"},\"value\":{\"additionalProperties\":false,\"properties\":{\"byteSize\":{\"minimum\":1,\"type\":\"integer\"},\"contentType\":{\"type\":\"string\"},\"sha256\":{\"pattern\":\"^[a-f0-9]{64}$\",\"type\":\"string\"},\"submissionVersion\":{\"minimum\":0,\"type\":\"integer\"},\"uploadedAt\":{\"type\":\"string\"},\"verificationStatus\":{\"enum\":[\"notRequired\",\"pending\",\"approved\",\"rejected\"]}},\"required\":[\"submissionVersion\",\"sha256\",\"contentType\",\"byteSize\",\"verificationStatus\"],\"type\":\"object\"}},\"required\":[\"id\",\"required\",\"maximumBytes\",\"contentTypes\",\"classification\",\"links\"],\"type\":\"object\"},\"maxProperties\":8,\"type\":\"object\"},\"blockedReason\":{\"enum\":[\"package-changed\"]},\"createdAt\":{\"type\":\"string\"},\"decision\":{\"additionalProperties\":false,\"properties\":{\"decidedAt\":{\"type\":\"string\"},\"publicReason\":{\"minLength\":1,\"pattern\":\"^[^\\\\u0000-\\\\u001F\\\\u007F-\\\\u009F]*[^\\\\u0000-\\\\u0020\\\\u007F-\\\\u00A0\\\\u1680\\\\u2000-\\\\u200A\\\\u2028\\\\u2029\\\\u202F\\\\u205F\\\\u3000][^\\\\u0000-\\\\u001F\\\\u007F-\\\\u009F]*$\",\"type\":\"string\"},\"status\":{\"enum\":[\"approved\",\"rejected\",\"changes-requested\",\"answered\"]}},\"required\":[\"status\",\"decidedAt\"],\"type\":\"object\"},\"effectDigest\":{\"type\":\"string\"},\"handoffRefusal\":{\"additionalProperties\":false,\"properties\":{\"code\":{\"enum\":[\"review.initiator-required\",\"review.initiator-excluded\",\"review.policy-mismatch\",\"review.refused\"]}},\"required\":[\"code\"],\"type\":\"object\"},\"id\":{\"type\":\"string\"},\"input\":{\"type\":\"object\"},\"links\":{\"additionalProperties\":{\"additionalProperties\":false,\"properties\":{\"accessProfile\":{\"type\":\"string\"},\"availability\":{\"additionalProperties\":false,\"if\":{\"properties\":{\"available\":{\"const\":false}}},\"properties\":{\"available\":{\"type\":\"boolean\"},\"observedRevision\":{\"minimum\":1,\"type\":\"integer\"},\"reason\":{\"enum\":[\"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\":{\"enum\":[\"refresh\",\"revise\",\"retry\",\"rebase\",\"correct-input\",\"receipt-only\"]}},\"required\":[\"available\",\"observedRevision\"],\"then\":{\"required\":[\"reason\",\"recovery\"]},\"type\":\"object\"},\"ifMatch\":{\"type\":\"string\"},\"method\":{\"enum\":[\"GET\",\"POST\"]},\"operation\":{\"type\":\"string\"},\"path\":{\"type\":\"string\"}},\"required\":[\"method\",\"path\",\"accessProfile\",\"operation\"],\"type\":\"object\"},\"type\":\"object\"},\"revision\":{\"minimum\":1,\"type\":\"integer\"},\"state\":{\"enum\":[\"draft\",\"submitted\",\"applied\",\"cancelled\",\"rejected\"]},\"status\":{\"enum\":[\"draft\",\"awaiting-party\",\"in-review\",\"approved\",\"processing\",\"applied\",\"rejected\",\"cancelled\"]},\"submissionVersion\":{\"minimum\":0,\"type\":\"integer\"},\"title\":{\"maxLength\":1024,\"type\":\"string\"},\"turn\":{\"enum\":[\"party\",\"official\",\"nobody\"]}},\"required\":[\"id\",\"actionId\",\"actionRevision\",\"submissionVersion\",\"revision\",\"state\",\"turn\",\"links\"],\"type\":\"object\"}")], + ["/paths/~1v1~1proposals~1{proposal_id}~1submit/post/responses/200/content/application~1json/schema", JSON.parse("{\"additionalProperties\":false,\"properties\":{\"actionId\":{\"type\":\"string\"},\"actionRevision\":{\"type\":\"string\"},\"application\":{\"additionalProperties\":false,\"properties\":{\"applicationId\":{\"type\":\"string\"},\"effectDigest\":{\"pattern\":\"^sha256:[0-9a-f]{64}$\",\"type\":\"string\"},\"resultLinks\":{\"items\":{\"additionalProperties\":false,\"properties\":{\"recordId\":{\"type\":\"string\"},\"recordType\":{\"type\":\"string\"},\"revision\":{\"minimum\":1,\"type\":\"integer\"}},\"required\":[\"recordType\",\"recordId\",\"revision\"],\"type\":\"object\"},\"maxItems\":16,\"type\":\"array\"},\"submissionVersion\":{\"minimum\":1,\"type\":\"integer\"}},\"required\":[\"applicationId\",\"submissionVersion\",\"effectDigest\",\"resultLinks\"],\"type\":\"object\"},\"applicationStatus\":{\"additionalProperties\":false,\"properties\":{\"automaticRetry\":{\"additionalProperties\":false,\"properties\":{\"attempts\":{\"maximum\":1000,\"minimum\":0,\"type\":\"integer\"},\"maximumAttempts\":{\"maximum\":1000,\"minimum\":1,\"type\":\"integer\"},\"scheduled\":{\"type\":\"boolean\"}},\"required\":[\"scheduled\",\"attempts\",\"maximumAttempts\"],\"type\":\"object\"},\"mode\":{\"enum\":[\"automatic\",\"manual\"]},\"reason\":{\"enum\":[\"package-changed\",\"dependency-outage\",\"lease-expired\",\"application-refused\",\"attempts-exhausted\"]},\"recovery\":{\"enum\":[\"retry\",\"rebase\",\"revise\",\"correct-input\"]},\"state\":{\"enum\":[\"awaiting-review\",\"pending\",\"applying\",\"blocked\",\"applied\",\"cancelled\",\"rejected\"]}},\"required\":[\"state\",\"mode\"],\"type\":\"object\"},\"asks\":{\"items\":{\"additionalProperties\":false,\"properties\":{\"answer\":{\"additionalProperties\":false,\"properties\":{\"additions\":{\"items\":{\"type\":\"string\"},\"maxItems\":32,\"type\":\"array\",\"uniqueItems\":true},\"answeredAt\":{\"type\":\"string\"},\"formEntries\":{\"items\":{\"type\":\"string\"},\"maxItems\":32,\"type\":\"array\",\"uniqueItems\":true},\"text\":{\"maxLength\":2000,\"minLength\":1,\"type\":\"string\"}},\"required\":[\"additions\",\"answeredAt\"],\"type\":\"object\"},\"askedAt\":{\"type\":\"string\"},\"dueAt\":{\"type\":\"string\"},\"id\":{\"type\":\"string\"},\"links\":{\"additionalProperties\":false,\"properties\":{\"answer\":{\"additionalProperties\":false,\"properties\":{\"accessProfile\":{\"type\":\"string\"},\"availability\":{\"additionalProperties\":false,\"if\":{\"properties\":{\"available\":{\"const\":false}}},\"properties\":{\"available\":{\"type\":\"boolean\"},\"observedRevision\":{\"minimum\":1,\"type\":\"integer\"},\"reason\":{\"enum\":[\"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\":{\"enum\":[\"refresh\",\"revise\",\"retry\",\"rebase\",\"correct-input\",\"receipt-only\"]}},\"required\":[\"available\",\"observedRevision\"],\"then\":{\"required\":[\"reason\",\"recovery\"]},\"type\":\"object\"},\"ifMatch\":{\"type\":\"string\"},\"method\":{\"const\":\"POST\"},\"operation\":{\"const\":\"answer\"},\"path\":{\"type\":\"string\"}},\"required\":[\"method\",\"path\",\"accessProfile\",\"operation\",\"ifMatch\",\"availability\"],\"type\":\"object\"}},\"type\":\"object\"},\"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\",\"links\"],\"type\":\"object\"},\"maxItems\":50,\"type\":\"array\"},\"attachments\":{\"additionalProperties\":{\"additionalProperties\":false,\"properties\":{\"classification\":{\"enum\":[\"public\",\"internal\",\"restricted\"]},\"contentTypes\":{\"items\":{\"type\":\"string\"},\"maxItems\":16,\"minItems\":1,\"type\":\"array\",\"uniqueItems\":true},\"id\":{\"type\":\"string\"},\"links\":{\"additionalProperties\":{\"additionalProperties\":false,\"properties\":{\"accessProfile\":{\"type\":\"string\"},\"availability\":{\"additionalProperties\":false,\"if\":{\"properties\":{\"available\":{\"const\":false}}},\"properties\":{\"available\":{\"type\":\"boolean\"},\"observedRevision\":{\"minimum\":1,\"type\":\"integer\"},\"reason\":{\"enum\":[\"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\":{\"enum\":[\"refresh\",\"revise\",\"retry\",\"rebase\",\"correct-input\",\"receipt-only\"]}},\"required\":[\"available\",\"observedRevision\"],\"then\":{\"required\":[\"reason\",\"recovery\"]},\"type\":\"object\"},\"ifMatch\":{\"type\":\"string\"},\"method\":{\"enum\":[\"GET\",\"PATCH\",\"DELETE\"]},\"operation\":{\"enum\":[\"download\",\"upload\",\"remove\"]},\"path\":{\"type\":\"string\"}},\"required\":[\"method\",\"path\",\"accessProfile\",\"operation\"],\"type\":\"object\"},\"type\":\"object\"},\"maximumBytes\":{\"maximum\":16777216,\"minimum\":1,\"type\":\"integer\"},\"required\":{\"type\":\"boolean\"},\"value\":{\"additionalProperties\":false,\"properties\":{\"byteSize\":{\"minimum\":1,\"type\":\"integer\"},\"contentType\":{\"type\":\"string\"},\"sha256\":{\"pattern\":\"^[a-f0-9]{64}$\",\"type\":\"string\"},\"submissionVersion\":{\"minimum\":0,\"type\":\"integer\"},\"uploadedAt\":{\"type\":\"string\"},\"verificationStatus\":{\"enum\":[\"notRequired\",\"pending\",\"approved\",\"rejected\"]}},\"required\":[\"submissionVersion\",\"sha256\",\"contentType\",\"byteSize\",\"verificationStatus\"],\"type\":\"object\"}},\"required\":[\"id\",\"required\",\"maximumBytes\",\"contentTypes\",\"classification\",\"links\"],\"type\":\"object\"},\"maxProperties\":8,\"type\":\"object\"},\"blockedReason\":{\"enum\":[\"package-changed\"]},\"createdAt\":{\"type\":\"string\"},\"decision\":{\"additionalProperties\":false,\"properties\":{\"decidedAt\":{\"type\":\"string\"},\"publicReason\":{\"minLength\":1,\"pattern\":\"^[^\\\\u0000-\\\\u001F\\\\u007F-\\\\u009F]*[^\\\\u0000-\\\\u0020\\\\u007F-\\\\u00A0\\\\u1680\\\\u2000-\\\\u200A\\\\u2028\\\\u2029\\\\u202F\\\\u205F\\\\u3000][^\\\\u0000-\\\\u001F\\\\u007F-\\\\u009F]*$\",\"type\":\"string\"},\"status\":{\"enum\":[\"approved\",\"rejected\",\"changes-requested\",\"answered\"]}},\"required\":[\"status\",\"decidedAt\"],\"type\":\"object\"},\"effectDigest\":{\"type\":\"string\"},\"handoffRefusal\":{\"additionalProperties\":false,\"properties\":{\"code\":{\"enum\":[\"review.initiator-required\",\"review.initiator-excluded\",\"review.policy-mismatch\",\"review.refused\"]}},\"required\":[\"code\"],\"type\":\"object\"},\"id\":{\"type\":\"string\"},\"input\":{\"type\":\"object\"},\"links\":{\"additionalProperties\":{\"additionalProperties\":false,\"properties\":{\"accessProfile\":{\"type\":\"string\"},\"availability\":{\"additionalProperties\":false,\"if\":{\"properties\":{\"available\":{\"const\":false}}},\"properties\":{\"available\":{\"type\":\"boolean\"},\"observedRevision\":{\"minimum\":1,\"type\":\"integer\"},\"reason\":{\"enum\":[\"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\":{\"enum\":[\"refresh\",\"revise\",\"retry\",\"rebase\",\"correct-input\",\"receipt-only\"]}},\"required\":[\"available\",\"observedRevision\"],\"then\":{\"required\":[\"reason\",\"recovery\"]},\"type\":\"object\"},\"ifMatch\":{\"type\":\"string\"},\"method\":{\"enum\":[\"GET\",\"POST\"]},\"operation\":{\"type\":\"string\"},\"path\":{\"type\":\"string\"}},\"required\":[\"method\",\"path\",\"accessProfile\",\"operation\"],\"type\":\"object\"},\"type\":\"object\"},\"partyRole\":{\"enum\":[\"owner\",\"subject\"]},\"revision\":{\"minimum\":1,\"type\":\"integer\"},\"state\":{\"enum\":[\"draft\",\"submitted\",\"applied\",\"cancelled\",\"rejected\"]},\"status\":{\"enum\":[\"draft\",\"awaiting-party\",\"in-review\",\"approved\",\"processing\",\"applied\",\"rejected\",\"cancelled\"]},\"submissionVersion\":{\"minimum\":0,\"type\":\"integer\"},\"title\":{\"maxLength\":1024,\"type\":\"string\"},\"turn\":{\"enum\":[\"party\",\"official\",\"nobody\"]}},\"required\":[\"id\",\"actionId\",\"actionRevision\",\"submissionVersion\",\"revision\",\"state\",\"turn\",\"links\"],\"type\":\"object\"}")], ["/paths/~1v1~1proposals~1{proposal_id}~1submit/post/responses/400/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"access-profile.ambiguous\",\"request.invalid\"]}},\"type\":\"object\"}]}")], ["/paths/~1v1~1proposals~1{proposal_id}~1submit/post/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}~1submit/post/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}~1submit/post/responses/403/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"profile.not-authorized\",\"proposal.subject-not-caller\"]}},\"type\":\"object\"}]}")], ["/paths/~1v1~1proposals~1{proposal_id}~1submit/post/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}~1submit/post/responses/409/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"attachment.verification-pending\",\"idempotency.key-reused\",\"mutation.conflict\",\"proposal.rejected\"]}},\"type\":\"object\"}]}")], + ["/paths/~1v1~1proposals~1{proposal_id}~1submit/post/responses/409/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"attachment.verification-pending\",\"idempotency.key-reused\",\"mutation.conflict\",\"proposal.rejected\",\"proposal.subject-changed\"]}},\"type\":\"object\"}]}")], ["/paths/~1v1~1proposals~1{proposal_id}~1submit/post/responses/410/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"idempotency.expired\"]}},\"type\":\"object\"}]}")], ["/paths/~1v1~1proposals~1{proposal_id}~1submit/post/responses/412/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"action.guard-failed\",\"precondition.failed\"]}},\"type\":\"object\"}]}")], ["/paths/~1v1~1proposals~1{proposal_id}~1submit/post/responses/415/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"unsupported.media-type\"]}},\"type\":\"object\"}]}")], @@ -500,7 +504,7 @@ export class Client { if (!route) throw new TypeError("Unknown operation") return this.#transport.call(route, options) } - async proposals_listPage(options: Operations["proposals.list"]["input"] = {}, cursor?: string): Promise); "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); "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") })>) })>); "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); "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") })>> { + async proposals_listPage(options: Operations["proposals.list"]["input"] = {}, cursor?: string): Promise); "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") })>> { const { data } = await this.call("proposals.list", { ...options, query: cursor === undefined ? options.query : { ...options.query, cursor } }) return { items: data.items, nextCursor: data.nextCursor ?? null } } diff --git a/clients/typescript/generated/breg-minimal.ts b/clients/typescript/generated/breg-minimal.ts index 78795d9df4..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 bce07d69a8eed5bb72b32568719f0ad0dc4ed711148c6f57735cc64e379193f1 -// 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" @@ -9,10 +11,10 @@ import { listPage, listQuery, type FieldValue, type Filter, type ListPage, type export type Schema_ImmediateActionPrecondition = ({ "ifMatch": (string) }) export type Schema_ImmediateActionResultReference = ({ "recordId": (string); "recordType": (string); "revision": (number) }) -export type Schema_Problem = (({ "code"?: "access-profile.ambiguous"; "status"?: 400; "type"?: "https://id.registrystack.org/problems/registry-breg/access-profile/ambiguous" }) | ({ "code"?: "action.evidence-failed"; "status"?: 503; "type"?: "https://id.registrystack.org/problems/registry-breg/action/evidence-failed" }) | ({ "code"?: "action.guard-failed"; "status"?: 412; "type"?: "https://id.registrystack.org/problems/registry-breg/action/guard-failed" }) | ({ "code"?: "action.handler-failed"; "status"?: 500; "type"?: "https://id.registrystack.org/problems/registry-breg/action/handler-failed" }) | ({ "code"?: "action.refused"; "status"?: 422; "type"?: "https://id.registrystack.org/problems/registry-breg/action/refused" }) | ({ "code"?: "attachment.content-type"; "status"?: 415; "type"?: "https://id.registrystack.org/problems/registry-breg/attachment/content-type" }) | ({ "code"?: "attachment.digest-mismatch"; "status"?: 422; "type"?: "https://id.registrystack.org/problems/registry-breg/attachment/digest-mismatch" }) | ({ "code"?: "attachment.limit-reached"; "status"?: 409; "type"?: "https://id.registrystack.org/problems/registry-breg/attachment/limit-reached" }) | ({ "code"?: "attachment.required"; "status"?: 422; "type"?: "https://id.registrystack.org/problems/registry-breg/attachment/required" }) | ({ "code"?: "attachment.slot-write-once"; "status"?: 409; "type"?: "https://id.registrystack.org/problems/registry-breg/attachment/slot-write-once" }) | ({ "code"?: "attachment.too-large"; "status"?: 413; "type"?: "https://id.registrystack.org/problems/registry-breg/attachment/too-large" }) | ({ "code"?: "attachment.verification-pending"; "status"?: 409; "type"?: "https://id.registrystack.org/problems/registry-breg/attachment/verification-pending" }) | ({ "code"?: "attachment.verification-rejected"; "status"?: 422; "type"?: "https://id.registrystack.org/problems/registry-breg/attachment/verification-rejected" }) | ({ "code"?: "authentication.refused"; "status"?: 401; "type"?: "https://id.registrystack.org/problems/registry-breg/authentication/refused" }) | ({ "code"?: "idempotency.expired"; "status"?: 410; "type"?: "https://id.registrystack.org/problems/registry-breg/idempotency/expired" }) | ({ "code"?: "idempotency.key-reused"; "status"?: 409; "type"?: "https://id.registrystack.org/problems/registry-breg/idempotency/key-reused" }) | ({ "code"?: "ingestion.chunk-mismatch"; "status"?: 409; "type"?: "https://id.registrystack.org/problems/registry-breg/ingestion/chunk-mismatch" }) | ({ "code"?: "ingestion.profile-mismatch"; "status"?: 403; "type"?: "https://id.registrystack.org/problems/registry-breg/ingestion/profile-mismatch" }) | ({ "code"?: "ingestion.receipt-erased"; "status"?: 410; "type"?: "https://id.registrystack.org/problems/registry-breg/ingestion/receipt-erased" }) | ({ "code"?: "ingestion.run-blocked"; "status"?: 409; "type"?: "https://id.registrystack.org/problems/registry-breg/ingestion/run-blocked" }) | ({ "code"?: "ingestion.run-not-open"; "status"?: 409; "type"?: "https://id.registrystack.org/problems/registry-breg/ingestion/run-not-open" }) | ({ "code"?: "lookup.unresolved"; "status"?: 404; "type"?: "https://id.registrystack.org/problems/registry-breg/lookup/unresolved" }) | ({ "code"?: "mutation.conflict"; "status"?: 409; "type"?: "https://id.registrystack.org/problems/registry-breg/mutation/conflict" }) | ({ "code"?: "precondition.failed"; "status"?: 412; "type"?: "https://id.registrystack.org/problems/registry-breg/precondition/failed" }) | ({ "code"?: "precondition.required"; "status"?: 428; "type"?: "https://id.registrystack.org/problems/registry-breg/precondition/required" }) | ({ "code"?: "profile.not-authorized"; "status"?: 403; "type"?: "https://id.registrystack.org/problems/registry-breg/profile/not-authorized" }) | ({ "code"?: "proposal.rejected"; "status"?: 409; "type"?: "https://id.registrystack.org/problems/registry-breg/proposal/rejected" }) | ({ "code"?: "proposal.review-result-mismatch"; "status"?: 412; "type"?: "https://id.registrystack.org/problems/registry-breg/proposal/review-result-mismatch" }) | ({ "code"?: "proposal.submission-expired"; "status"?: 410; "type"?: "https://id.registrystack.org/problems/registry-breg/proposal/submission-expired" }) | ({ "code"?: "query.cursor-invalid"; "status"?: 400; "type"?: "https://id.registrystack.org/problems/registry-breg/query/cursor-invalid" }) | ({ "code"?: "query.filter-required"; "status"?: 400; "type"?: "https://id.registrystack.org/problems/registry-breg/query/filter-required" }) | ({ "code"?: "query.invalid"; "status"?: 400; "type"?: "https://id.registrystack.org/problems/registry-breg/query/invalid" }) | ({ "code"?: "request.access-reason-required"; "status"?: 400; "type"?: "https://id.registrystack.org/problems/registry-breg/request/access-reason-required" }) | ({ "code"?: "request.invalid"; "status"?: 400; "type"?: "https://id.registrystack.org/problems/registry-breg/request/invalid" }) | ({ "code"?: "request.timeout"; "status"?: 504; "type"?: "https://id.registrystack.org/problems/registry-breg/request/timeout" }) | ({ "code"?: "resource.not-found"; "status"?: 404; "type"?: "https://id.registrystack.org/problems/registry-breg/resource/not-found" }) | ({ "code"?: "runtime.field-encryption.unavailable"; "status"?: 503; "type"?: "https://id.registrystack.org/problems/registry-breg/runtime/field-encryption/unavailable" }) | ({ "code"?: "service.unavailable"; "status"?: 503; "type"?: "https://id.registrystack.org/problems/registry-breg/service/unavailable" }) | ({ "code"?: "source.unavailable"; "status"?: 503; "type"?: "https://id.registrystack.org/problems/registry-breg/source/unavailable" }) | ({ "code"?: "statistical-dataset.domain-violation"; "status"?: 500; "type"?: "https://id.registrystack.org/problems/registry-breg/statistical-dataset/domain-violation" }) | ({ "code"?: "statistical-dataset.release-refused"; "status"?: 422; "type"?: "https://id.registrystack.org/problems/registry-breg/statistical-dataset/release-refused" }) | ({ "code"?: "statistical-dataset.version-conflict"; "status"?: 409; "type"?: "https://id.registrystack.org/problems/registry-breg/statistical-dataset/version-conflict" }) | ({ "code"?: "statistical-dataset.version-withdrawn"; "status"?: 410; "type"?: "https://id.registrystack.org/problems/registry-breg/statistical-dataset/version-withdrawn" }) | ({ "code"?: "unsupported.media-type"; "status"?: 415; "type"?: "https://id.registrystack.org/problems/registry-breg/unsupported/media-type" }) | ({ "code"?: "write.outside-boundary"; "status"?: 403; "type"?: "https://id.registrystack.org/problems/registry-breg/write/outside-boundary" })) & ({ "accessProfiles"?: (Array<(string)>); "atField"?: (string); "code": ("access-profile.ambiguous" | "action.evidence-failed" | "action.guard-failed" | "action.handler-failed" | "action.refused" | "attachment.content-type" | "attachment.digest-mismatch" | "attachment.limit-reached" | "attachment.required" | "attachment.slot-write-once" | "attachment.too-large" | "attachment.verification-pending" | "attachment.verification-rejected" | "authentication.refused" | "idempotency.expired" | "idempotency.key-reused" | "ingestion.chunk-mismatch" | "ingestion.profile-mismatch" | "ingestion.receipt-erased" | "ingestion.run-blocked" | "ingestion.run-not-open" | "lookup.unresolved" | "mutation.conflict" | "precondition.failed" | "precondition.required" | "profile.not-authorized" | "proposal.rejected" | "proposal.review-result-mismatch" | "proposal.submission-expired" | "query.cursor-invalid" | "query.filter-required" | "query.invalid" | "request.access-reason-required" | "request.invalid" | "request.timeout" | "resource.not-found" | "runtime.field-encryption.unavailable" | "service.unavailable" | "source.unavailable" | "statistical-dataset.domain-violation" | "statistical-dataset.release-refused" | "statistical-dataset.version-conflict" | "statistical-dataset.version-withdrawn" | "unsupported.media-type" | "write.outside-boundary") & (string); "constraintId"?: (string); "constraintKind"?: ("compare" | "int-range" | "vocabulary") & (string); "detail": (string); "failedCheck"?: (string); "field"?: (string); "fieldId"?: (string); "fieldPath"?: (string); "guardReason"?: (string); "left"?: (string); "notAfterField"?: (string); "reasonCode"?: ("computation-error" | "source-data-error" | "disclosure-risk") & (string); "recordType"?: (string); "refusalCode"?: (string); "requiredFilters"?: (Array<(Array<(string)>)>); "right"?: (string); "status": (number); "title": (string); "traceId": (string); "type": (string) }) & (({ "code": "access-profile.ambiguous" } & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & ({ "status"?: 400; "accessProfiles": {} | null })) | ({ "code": "action.evidence-failed" } & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never } & ({ "detail"?: "The declared Evidence dependency could not be accepted."; "fieldPath"?: (string); "status"?: 503 })) | ({ "code": "action.guard-failed" } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "action.handler-failed" } & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never } & ({ "status"?: 500 })) | ({ "code": "action.refused" } & { "guardReason"?: never } & ({ "status"?: 422; "refusalCode": {} | null }) & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "attachment.content-type" } & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "attachment.digest-mismatch" } & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "attachment.limit-reached" } & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "attachment.required" } & ({ "fieldPath": (string) }) & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "attachment.slot-write-once" } & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "attachment.too-large" } & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "attachment.verification-pending" } & ({ "fieldPath": (string) }) & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "attachment.verification-rejected" } & ({ "fieldPath": (string) }) & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "authentication.refused" } & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "idempotency.expired" } & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "idempotency.key-reused" } & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "ingestion.chunk-mismatch" } & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "ingestion.profile-mismatch" } & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "ingestion.receipt-erased" } & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "ingestion.run-blocked" } & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "ingestion.run-not-open" } & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "lookup.unresolved" } & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "mutation.conflict" } & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "precondition.failed" } & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "precondition.required" } & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "profile.not-authorized" } & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "proposal.rejected" } & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "proposal.review-result-mismatch" } & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "proposal.submission-expired" } & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "query.cursor-invalid" } & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "query.filter-required" } & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "query.invalid" } & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "request.access-reason-required" } & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "request.invalid" } & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "request.timeout" } & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "resource.not-found" } & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "runtime.field-encryption.unavailable" } & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "service.unavailable" } & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "source.unavailable" } & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "statistical-dataset.domain-violation" } & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "statistical-dataset.release-refused" } & { "guardReason"?: never } & ({ "refusalCode": ("period-not-ended" | "before-first-period" | "provisional-after-final" | "already-withdrawn" | "negative-value"); "status"?: 422 }) & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "statistical-dataset.version-conflict" } & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "statistical-dataset.version-withdrawn" } & { "guardReason"?: never } & { "refusalCode"?: never } & ({ "status"?: 410; "reasonCode": {} | null }) & { "accessProfiles"?: never }) | ({ "code": "unsupported.media-type" } & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "write.outside-boundary" } & ({ "code"?: "write.outside-boundary"; "detail"?: "The write falls outside what the selected access profile may write: its row boundary or a disclosure condition."; "status"?: 403; "title"?: "Forbidden"; "type"?: "https://id.registrystack.org/problems/registry-breg/write/outside-boundary" }) & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never })) +export type Schema_Problem = (({ "code"?: "access-profile.ambiguous"; "status"?: 400; "type"?: "https://id.registrystack.org/problems/registry-breg/access-profile/ambiguous" }) | ({ "code"?: "action.evidence-failed"; "status"?: 503; "type"?: "https://id.registrystack.org/problems/registry-breg/action/evidence-failed" }) | ({ "code"?: "action.guard-failed"; "status"?: 412; "type"?: "https://id.registrystack.org/problems/registry-breg/action/guard-failed" }) | ({ "code"?: "action.handler-failed"; "status"?: 500; "type"?: "https://id.registrystack.org/problems/registry-breg/action/handler-failed" }) | ({ "code"?: "action.refused"; "status"?: 422; "type"?: "https://id.registrystack.org/problems/registry-breg/action/refused" }) | ({ "code"?: "attachment.content-type"; "status"?: 415; "type"?: "https://id.registrystack.org/problems/registry-breg/attachment/content-type" }) | ({ "code"?: "attachment.digest-mismatch"; "status"?: 422; "type"?: "https://id.registrystack.org/problems/registry-breg/attachment/digest-mismatch" }) | ({ "code"?: "attachment.limit-reached"; "status"?: 409; "type"?: "https://id.registrystack.org/problems/registry-breg/attachment/limit-reached" }) | ({ "code"?: "attachment.required"; "status"?: 422; "type"?: "https://id.registrystack.org/problems/registry-breg/attachment/required" }) | ({ "code"?: "attachment.slot-write-once"; "status"?: 409; "type"?: "https://id.registrystack.org/problems/registry-breg/attachment/slot-write-once" }) | ({ "code"?: "attachment.too-large"; "status"?: 413; "type"?: "https://id.registrystack.org/problems/registry-breg/attachment/too-large" }) | ({ "code"?: "attachment.verification-pending"; "status"?: 409; "type"?: "https://id.registrystack.org/problems/registry-breg/attachment/verification-pending" }) | ({ "code"?: "attachment.verification-rejected"; "status"?: 422; "type"?: "https://id.registrystack.org/problems/registry-breg/attachment/verification-rejected" }) | ({ "code"?: "authentication.refused"; "status"?: 401; "type"?: "https://id.registrystack.org/problems/registry-breg/authentication/refused" }) | ({ "code"?: "idempotency.expired"; "status"?: 410; "type"?: "https://id.registrystack.org/problems/registry-breg/idempotency/expired" }) | ({ "code"?: "idempotency.key-reused"; "status"?: 409; "type"?: "https://id.registrystack.org/problems/registry-breg/idempotency/key-reused" }) | ({ "code"?: "ingestion.chunk-mismatch"; "status"?: 409; "type"?: "https://id.registrystack.org/problems/registry-breg/ingestion/chunk-mismatch" }) | ({ "code"?: "ingestion.profile-mismatch"; "status"?: 403; "type"?: "https://id.registrystack.org/problems/registry-breg/ingestion/profile-mismatch" }) | ({ "code"?: "ingestion.receipt-erased"; "status"?: 410; "type"?: "https://id.registrystack.org/problems/registry-breg/ingestion/receipt-erased" }) | ({ "code"?: "ingestion.run-blocked"; "status"?: 409; "type"?: "https://id.registrystack.org/problems/registry-breg/ingestion/run-blocked" }) | ({ "code"?: "ingestion.run-not-open"; "status"?: 409; "type"?: "https://id.registrystack.org/problems/registry-breg/ingestion/run-not-open" }) | ({ "code"?: "lookup.unresolved"; "status"?: 404; "type"?: "https://id.registrystack.org/problems/registry-breg/lookup/unresolved" }) | ({ "code"?: "mutation.conflict"; "status"?: 409; "type"?: "https://id.registrystack.org/problems/registry-breg/mutation/conflict" }) | ({ "code"?: "precondition.failed"; "status"?: 412; "type"?: "https://id.registrystack.org/problems/registry-breg/precondition/failed" }) | ({ "code"?: "precondition.required"; "status"?: 428; "type"?: "https://id.registrystack.org/problems/registry-breg/precondition/required" }) | ({ "code"?: "profile.not-authorized"; "status"?: 403; "type"?: "https://id.registrystack.org/problems/registry-breg/profile/not-authorized" }) | ({ "code"?: "proposal.form-limit-reached"; "status"?: 409; "type"?: "https://id.registrystack.org/problems/registry-breg/proposal/form-limit-reached" }) | ({ "code"?: "proposal.form-undeclared"; "status"?: 404; "type"?: "https://id.registrystack.org/problems/registry-breg/proposal/form-undeclared" }) | ({ "code"?: "proposal.message-limit-reached"; "status"?: 409; "type"?: "https://id.registrystack.org/problems/registry-breg/proposal/message-limit-reached" }) | ({ "code"?: "proposal.rejected"; "status"?: 409; "type"?: "https://id.registrystack.org/problems/registry-breg/proposal/rejected" }) | ({ "code"?: "proposal.review-result-mismatch"; "status"?: 412; "type"?: "https://id.registrystack.org/problems/registry-breg/proposal/review-result-mismatch" }) | ({ "code"?: "proposal.subject-changed"; "status"?: 409; "type"?: "https://id.registrystack.org/problems/registry-breg/proposal/subject-changed" }) | ({ "code"?: "proposal.subject-not-caller"; "status"?: 403; "type"?: "https://id.registrystack.org/problems/registry-breg/proposal/subject-not-caller" }) | ({ "code"?: "proposal.submission-expired"; "status"?: 410; "type"?: "https://id.registrystack.org/problems/registry-breg/proposal/submission-expired" }) | ({ "code"?: "query.cursor-invalid"; "status"?: 400; "type"?: "https://id.registrystack.org/problems/registry-breg/query/cursor-invalid" }) | ({ "code"?: "query.filter-required"; "status"?: 400; "type"?: "https://id.registrystack.org/problems/registry-breg/query/filter-required" }) | ({ "code"?: "query.invalid"; "status"?: 400; "type"?: "https://id.registrystack.org/problems/registry-breg/query/invalid" }) | ({ "code"?: "request.access-reason-required"; "status"?: 400; "type"?: "https://id.registrystack.org/problems/registry-breg/request/access-reason-required" }) | ({ "code"?: "request.invalid"; "status"?: 400; "type"?: "https://id.registrystack.org/problems/registry-breg/request/invalid" }) | ({ "code"?: "request.timeout"; "status"?: 504; "type"?: "https://id.registrystack.org/problems/registry-breg/request/timeout" }) | ({ "code"?: "resource.not-found"; "status"?: 404; "type"?: "https://id.registrystack.org/problems/registry-breg/resource/not-found" }) | ({ "code"?: "runtime.field-encryption.unavailable"; "status"?: 503; "type"?: "https://id.registrystack.org/problems/registry-breg/runtime/field-encryption/unavailable" }) | ({ "code"?: "service.unavailable"; "status"?: 503; "type"?: "https://id.registrystack.org/problems/registry-breg/service/unavailable" }) | ({ "code"?: "source.unavailable"; "status"?: 503; "type"?: "https://id.registrystack.org/problems/registry-breg/source/unavailable" }) | ({ "code"?: "statistical-dataset.domain-violation"; "status"?: 500; "type"?: "https://id.registrystack.org/problems/registry-breg/statistical-dataset/domain-violation" }) | ({ "code"?: "statistical-dataset.release-refused"; "status"?: 422; "type"?: "https://id.registrystack.org/problems/registry-breg/statistical-dataset/release-refused" }) | ({ "code"?: "statistical-dataset.version-conflict"; "status"?: 409; "type"?: "https://id.registrystack.org/problems/registry-breg/statistical-dataset/version-conflict" }) | ({ "code"?: "statistical-dataset.version-withdrawn"; "status"?: 410; "type"?: "https://id.registrystack.org/problems/registry-breg/statistical-dataset/version-withdrawn" }) | ({ "code"?: "unsupported.media-type"; "status"?: 415; "type"?: "https://id.registrystack.org/problems/registry-breg/unsupported/media-type" }) | ({ "code"?: "write.outside-boundary"; "status"?: 403; "type"?: "https://id.registrystack.org/problems/registry-breg/write/outside-boundary" })) & ({ "accessProfiles"?: (Array<(string)>); "atField"?: (string); "code": ("access-profile.ambiguous" | "action.evidence-failed" | "action.guard-failed" | "action.handler-failed" | "action.refused" | "attachment.content-type" | "attachment.digest-mismatch" | "attachment.limit-reached" | "attachment.required" | "attachment.slot-write-once" | "attachment.too-large" | "attachment.verification-pending" | "attachment.verification-rejected" | "authentication.refused" | "idempotency.expired" | "idempotency.key-reused" | "ingestion.chunk-mismatch" | "ingestion.profile-mismatch" | "ingestion.receipt-erased" | "ingestion.run-blocked" | "ingestion.run-not-open" | "lookup.unresolved" | "mutation.conflict" | "precondition.failed" | "precondition.required" | "profile.not-authorized" | "proposal.form-limit-reached" | "proposal.form-undeclared" | "proposal.message-limit-reached" | "proposal.rejected" | "proposal.review-result-mismatch" | "proposal.subject-changed" | "proposal.subject-not-caller" | "proposal.submission-expired" | "query.cursor-invalid" | "query.filter-required" | "query.invalid" | "request.access-reason-required" | "request.invalid" | "request.timeout" | "resource.not-found" | "runtime.field-encryption.unavailable" | "service.unavailable" | "source.unavailable" | "statistical-dataset.domain-violation" | "statistical-dataset.release-refused" | "statistical-dataset.version-conflict" | "statistical-dataset.version-withdrawn" | "unsupported.media-type" | "write.outside-boundary") & (string); "constraintId"?: (string); "constraintKind"?: ("compare" | "int-range" | "vocabulary") & (string); "detail": (string); "failedCheck"?: (string); "field"?: (string); "fieldId"?: (string); "fieldPath"?: (string); "guardReason"?: (string); "left"?: (string); "notAfterField"?: (string); "reasonCode"?: ("computation-error" | "source-data-error" | "disclosure-risk") & (string); "recordType"?: (string); "refusalCode"?: (string); "requiredFilters"?: (Array<(Array<(string)>)>); "right"?: (string); "status": (number); "title": (string); "traceId": (string); "type": (string) }) & (({ "code": "access-profile.ambiguous" } & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & ({ "status"?: 400; "accessProfiles": {} | null })) | ({ "code": "action.evidence-failed" } & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never } & ({ "detail"?: "The declared Evidence dependency could not be accepted."; "fieldPath"?: (string); "status"?: 503 })) | ({ "code": "action.guard-failed" } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "action.handler-failed" } & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never } & ({ "status"?: 500 })) | ({ "code": "action.refused" } & { "guardReason"?: never } & ({ "status"?: 422; "refusalCode": {} | null }) & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "attachment.content-type" } & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "attachment.digest-mismatch" } & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "attachment.limit-reached" } & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "attachment.required" } & ({ "fieldPath": (string) }) & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "attachment.slot-write-once" } & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "attachment.too-large" } & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "attachment.verification-pending" } & ({ "fieldPath": (string) }) & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "attachment.verification-rejected" } & ({ "fieldPath": (string) }) & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "authentication.refused" } & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "idempotency.expired" } & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "idempotency.key-reused" } & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "ingestion.chunk-mismatch" } & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "ingestion.profile-mismatch" } & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "ingestion.receipt-erased" } & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "ingestion.run-blocked" } & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "ingestion.run-not-open" } & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "lookup.unresolved" } & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "mutation.conflict" } & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "precondition.failed" } & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "precondition.required" } & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "profile.not-authorized" } & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "proposal.form-limit-reached" } & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "proposal.form-undeclared" } & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "proposal.message-limit-reached" } & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "proposal.rejected" } & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "proposal.review-result-mismatch" } & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "proposal.subject-changed" } & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "proposal.subject-not-caller" } & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "proposal.submission-expired" } & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "query.cursor-invalid" } & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "query.filter-required" } & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "query.invalid" } & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "request.access-reason-required" } & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "request.invalid" } & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "request.timeout" } & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "resource.not-found" } & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "runtime.field-encryption.unavailable" } & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "service.unavailable" } & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "source.unavailable" } & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "statistical-dataset.domain-violation" } & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "statistical-dataset.release-refused" } & { "guardReason"?: never } & ({ "refusalCode": ("period-not-ended" | "before-first-period" | "provisional-after-final" | "already-withdrawn" | "negative-value"); "status"?: 422 }) & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "statistical-dataset.version-conflict" } & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "statistical-dataset.version-withdrawn" } & { "guardReason"?: never } & { "refusalCode"?: never } & ({ "status"?: 410; "reasonCode": {} | null }) & { "accessProfiles"?: never }) | ({ "code": "unsupported.media-type" } & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never }) | ({ "code": "write.outside-boundary" } & ({ "code"?: "write.outside-boundary"; "detail"?: "The write falls outside what the selected access profile may write: its row boundary or a disclosure condition."; "status"?: 403; "title"?: "Forbidden"; "type"?: "https://id.registrystack.org/problems/registry-breg/write/outside-boundary" }) & { "guardReason"?: never } & { "refusalCode"?: never } & { "reasonCode"?: never } & { "accessProfiles"?: never })) export type Schema_ReviewCompletion = ({ "completedAt": (string); "eventId": (string); "requestId": (string); "resultId": (string); "type": "review.completed" }) export type Schema_action_register_contact_invoke_input = ({ "input": ({ "email"?: (string); "jurisdiction"?: (string); "name"?: (string) }) }) -export type Schema_action_register_contact_invoke_response = ({ "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); "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") })>) })>); "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); "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") }) +export type Schema_action_register_contact_invoke_response = ({ "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") }) export type Schema_action_update_contact_email_availability_input = (({ "input"?: ({ "contactId": (string) }); "targetInput"?: "contactId" })) & ({ "input": ({ "contactId"?: (string); "email"?: (string) }); "targetInput": ("contactId") & (string) }) export type Schema_action_update_contact_email_availability_response = ({ "availability": (({ "available": true; "observedRevision": (number) }) | ({ "available": false; "guardLabel"?: (string); "guardReason"?: (string); "observedRevision": (number); "reason": "guard-not-satisfied"; "recovery": "none" }) | ({ "available": (null); "missingInputs": (Array<("contactId" | "email") & (string)>); "observedRevision": (number); "reason": "input-required"; "recovery": "correct-input" }) | ({ "available": (null); "observedRevision": (null); "reason": "not-disclosed"; "recovery": "none" })) }) export type Schema_action_update_contact_email_invoke_input = ({ "input": ({ "contactId": (string); "email": (string) }); "preconditions": ({ "contactId": ({ "ifMatch": (string) }) }) }) @@ -27,16 +29,16 @@ export interface Operations { "actions.update-contact-email.invoke": { input: CallOptions & { query?: { "accessProfile"?: "directory-editor" } } & { headers?: { "traceparent"?: (string) } } & ({ body: Schema_action_update_contact_email_invoke_input }) & { accept?: "application/json" | "*/*" }; required: true; output: Schema_action_update_contact_email_invoke_response } "actions.update-contact-email.availability": { input: CallOptions & { query?: { "accessProfile"?: "directory-editor" } } & { headers?: { "traceparent"?: (string) } } & ({ body: Schema_action_update_contact_email_availability_input }) & { accept?: "application/json" | "*/*" }; required: true; output: Schema_action_update_contact_email_availability_response } "actions.update-contact-email.target-conditions": { input: CallOptions & { query?: { "accessProfile"?: "directory-editor" } } & { headers?: { "traceparent"?: (string) } } & ({ body: Schema_action_update_contact_email_target_conditions_input }) & { accept?: "application/json" | "*/*" }; required: true; output: Schema_action_update_contact_email_target_conditions_response } - "proposals.list": { input: CallOptions & { query?: { "accessProfile"?: "directory-editor"; "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); "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") })>) })>); "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); "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": { input: CallOptions & { path: { "proposal_id": (string) } } & { query?: { "accessProfile"?: "directory-editor" } } & { 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); "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") })>) })>); "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); "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.cancel": { input: CallOptions & { path: { "proposal_id": (string) } } & { query?: { "accessProfile"?: "directory-editor" } } & { 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); "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") })>) })>); "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); "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.edit": { input: CallOptions & { path: { "proposal_id": (string) } } & { query?: { "accessProfile"?: "directory-editor" } } & { headers: { "If-Match": (string) } } & ({ body: (({ "input": ({ "email"?: (string); "jurisdiction"?: (string); "name"?: (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); "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") })>) })>); "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); "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.list": { input: CallOptions & { query?: { "accessProfile"?: "directory-editor"; "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": { input: CallOptions & { path: { "proposal_id": (string) } } & { query?: { "accessProfile"?: "directory-editor" } } & { 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.cancel": { input: CallOptions & { path: { "proposal_id": (string) } } & { query?: { "accessProfile"?: "directory-editor" } } & { 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.edit": { input: CallOptions & { path: { "proposal_id": (string) } } & { query?: { "accessProfile"?: "directory-editor" } } & { headers: { "If-Match": (string) } } & ({ body: (({ "input": ({ "email"?: (string); "jurisdiction"?: (string); "name"?: (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.get-submission": { input: CallOptions & { path: { "proposal_id": (string); "submission_version": (number) } } & { query?: { "accessProfile"?: "directory-editor" } } & { 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"?: "directory-editor" } } & { 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); "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") })>) })>); "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); "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.submit": { input: CallOptions & { path: { "proposal_id": (string) } } & { query?: { "accessProfile"?: "directory-editor" } } & { 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.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 } } @@ -68,10 +70,10 @@ function recordRow(record: RecordEnvelope & { domainData: Data }): RecordR } const rules: Record = Object.fromEntries([ - ["/components/schemas/Problem", JSON.parse("{\"additionalProperties\":false,\"allOf\":[{\"if\":{\"properties\":{\"code\":{\"enum\":[\"attachment.required\",\"attachment.verification-pending\",\"attachment.verification-rejected\"]}}},\"then\":{\"allOf\":[{\"else\":{\"properties\":{\"status\":{\"const\":422}}},\"if\":{\"properties\":{\"code\":{\"const\":\"attachment.verification-pending\"}}},\"then\":{\"properties\":{\"status\":{\"const\":409}}}}],\"properties\":{\"fieldPath\":{\"pattern\":\"^/attachments/[a-z][a-z0-9_-]{0,63}$\",\"type\":\"string\"}},\"propertyNames\":{\"enum\":[\"type\",\"title\",\"status\",\"detail\",\"code\",\"traceId\",\"fieldPath\"]},\"required\":[\"fieldPath\"]}},{\"if\":{\"properties\":{\"code\":{\"const\":\"write.outside-boundary\"}}},\"then\":{\"properties\":{\"code\":{\"const\":\"write.outside-boundary\"},\"detail\":{\"const\":\"The write falls outside what the selected access profile may write: its row boundary or a disclosure condition.\"},\"status\":{\"const\":403},\"title\":{\"const\":\"Forbidden\"},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/write/outside-boundary\"}},\"propertyNames\":{\"enum\":[\"type\",\"title\",\"status\",\"detail\",\"code\",\"traceId\",\"failedCheck\"]}}},{\"if\":{\"properties\":{\"code\":{\"not\":{\"const\":\"action.guard-failed\"}}}},\"then\":{\"not\":{\"required\":[\"guardReason\"]}}},{\"if\":{\"properties\":{\"code\":{\"const\":\"action.refused\"}}},\"then\":{\"properties\":{\"status\":{\"const\":422}},\"required\":[\"refusalCode\"]}},{\"if\":{\"properties\":{\"code\":{\"const\":\"statistical-dataset.release-refused\"}}},\"then\":{\"properties\":{\"refusalCode\":{\"enum\":[\"period-not-ended\",\"before-first-period\",\"provisional-after-final\",\"already-withdrawn\",\"negative-value\"]},\"status\":{\"const\":422}},\"required\":[\"refusalCode\"]}},{\"if\":{\"properties\":{\"code\":{\"not\":{\"enum\":[\"action.refused\",\"statistical-dataset.release-refused\"]}}}},\"then\":{\"not\":{\"required\":[\"refusalCode\"]}}},{\"if\":{\"properties\":{\"code\":{\"const\":\"statistical-dataset.version-withdrawn\"}}},\"then\":{\"properties\":{\"status\":{\"const\":410}},\"required\":[\"reasonCode\"]}},{\"if\":{\"properties\":{\"code\":{\"not\":{\"const\":\"statistical-dataset.version-withdrawn\"}}}},\"then\":{\"not\":{\"required\":[\"reasonCode\"]}}},{\"if\":{\"properties\":{\"code\":{\"const\":\"access-profile.ambiguous\"}}},\"then\":{\"additionalProperties\":true,\"not\":{\"required\":[\"failedCheck\"]},\"properties\":{\"status\":{\"const\":400}},\"required\":[\"accessProfiles\"]}},{\"if\":{\"properties\":{\"code\":{\"not\":{\"const\":\"access-profile.ambiguous\"}}}},\"then\":{\"not\":{\"required\":[\"accessProfiles\"]}}},{\"if\":{\"properties\":{\"code\":{\"const\":\"action.evidence-failed\"}}},\"then\":{\"properties\":{\"detail\":{\"const\":\"The declared Evidence dependency could not be accepted.\"},\"fieldPath\":{\"pattern\":\"^/evidence/[a-z][a-z0-9_-]{0,63}$\",\"type\":\"string\"},\"status\":{\"const\":503}}}},{\"if\":{\"properties\":{\"code\":{\"const\":\"action.handler-failed\"}}},\"then\":{\"properties\":{\"status\":{\"const\":500}}}},{\"if\":{\"anyOf\":[{\"required\":[\"atField\"]},{\"required\":[\"notAfterField\"]}]},\"then\":{\"properties\":{\"code\":{\"const\":\"request.invalid\"},\"status\":{\"const\":400}},\"required\":[\"atField\",\"notAfterField\"]}},{\"if\":{\"anyOf\":[{\"required\":[\"recordType\"]},{\"required\":[\"fieldId\"]},{\"required\":[\"constraintId\"]},{\"required\":[\"constraintKind\"]},{\"required\":[\"left\"]},{\"required\":[\"right\"]},{\"required\":[\"field\"]}]},\"then\":{\"oneOf\":[{\"not\":{\"anyOf\":[{\"required\":[\"constraintId\"]},{\"required\":[\"constraintKind\"]},{\"required\":[\"left\"]},{\"required\":[\"right\"]},{\"required\":[\"field\"]}]},\"required\":[\"fieldId\"]},{\"not\":{\"required\":[\"fieldId\"]},\"oneOf\":[{\"not\":{\"required\":[\"field\"]},\"properties\":{\"constraintKind\":{\"const\":\"compare\"}},\"required\":[\"left\",\"right\"]},{\"not\":{\"anyOf\":[{\"required\":[\"left\"]},{\"required\":[\"right\"]}]},\"properties\":{\"constraintKind\":{\"enum\":[\"int-range\",\"vocabulary\"]}},\"required\":[\"field\"]}],\"required\":[\"constraintId\",\"constraintKind\"]}],\"properties\":{\"code\":{\"const\":\"mutation.conflict\"},\"status\":{\"const\":409}},\"required\":[\"recordType\"]}}],\"anyOf\":[{\"properties\":{\"code\":{\"const\":\"access-profile.ambiguous\"},\"status\":{\"const\":400},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/access-profile/ambiguous\"}}},{\"properties\":{\"code\":{\"const\":\"action.evidence-failed\"},\"status\":{\"const\":503},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/action/evidence-failed\"}}},{\"properties\":{\"code\":{\"const\":\"action.guard-failed\"},\"status\":{\"const\":412},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/action/guard-failed\"}}},{\"properties\":{\"code\":{\"const\":\"action.handler-failed\"},\"status\":{\"const\":500},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/action/handler-failed\"}}},{\"properties\":{\"code\":{\"const\":\"action.refused\"},\"status\":{\"const\":422},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/action/refused\"}}},{\"properties\":{\"code\":{\"const\":\"attachment.content-type\"},\"status\":{\"const\":415},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/attachment/content-type\"}}},{\"properties\":{\"code\":{\"const\":\"attachment.digest-mismatch\"},\"status\":{\"const\":422},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/attachment/digest-mismatch\"}}},{\"properties\":{\"code\":{\"const\":\"attachment.limit-reached\"},\"status\":{\"const\":409},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/attachment/limit-reached\"}}},{\"properties\":{\"code\":{\"const\":\"attachment.required\"},\"status\":{\"const\":422},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/attachment/required\"}}},{\"properties\":{\"code\":{\"const\":\"attachment.slot-write-once\"},\"status\":{\"const\":409},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/attachment/slot-write-once\"}}},{\"properties\":{\"code\":{\"const\":\"attachment.too-large\"},\"status\":{\"const\":413},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/attachment/too-large\"}}},{\"properties\":{\"code\":{\"const\":\"attachment.verification-pending\"},\"status\":{\"const\":409},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/attachment/verification-pending\"}}},{\"properties\":{\"code\":{\"const\":\"attachment.verification-rejected\"},\"status\":{\"const\":422},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/attachment/verification-rejected\"}}},{\"properties\":{\"code\":{\"const\":\"authentication.refused\"},\"status\":{\"const\":401},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/authentication/refused\"}}},{\"properties\":{\"code\":{\"const\":\"idempotency.expired\"},\"status\":{\"const\":410},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/idempotency/expired\"}}},{\"properties\":{\"code\":{\"const\":\"idempotency.key-reused\"},\"status\":{\"const\":409},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/idempotency/key-reused\"}}},{\"properties\":{\"code\":{\"const\":\"ingestion.chunk-mismatch\"},\"status\":{\"const\":409},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/ingestion/chunk-mismatch\"}}},{\"properties\":{\"code\":{\"const\":\"ingestion.profile-mismatch\"},\"status\":{\"const\":403},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/ingestion/profile-mismatch\"}}},{\"properties\":{\"code\":{\"const\":\"ingestion.receipt-erased\"},\"status\":{\"const\":410},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/ingestion/receipt-erased\"}}},{\"properties\":{\"code\":{\"const\":\"ingestion.run-blocked\"},\"status\":{\"const\":409},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/ingestion/run-blocked\"}}},{\"properties\":{\"code\":{\"const\":\"ingestion.run-not-open\"},\"status\":{\"const\":409},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/ingestion/run-not-open\"}}},{\"properties\":{\"code\":{\"const\":\"lookup.unresolved\"},\"status\":{\"const\":404},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/lookup/unresolved\"}}},{\"properties\":{\"code\":{\"const\":\"mutation.conflict\"},\"status\":{\"const\":409},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/mutation/conflict\"}}},{\"properties\":{\"code\":{\"const\":\"precondition.failed\"},\"status\":{\"const\":412},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/precondition/failed\"}}},{\"properties\":{\"code\":{\"const\":\"precondition.required\"},\"status\":{\"const\":428},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/precondition/required\"}}},{\"properties\":{\"code\":{\"const\":\"profile.not-authorized\"},\"status\":{\"const\":403},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/profile/not-authorized\"}}},{\"properties\":{\"code\":{\"const\":\"proposal.rejected\"},\"status\":{\"const\":409},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/proposal/rejected\"}}},{\"properties\":{\"code\":{\"const\":\"proposal.review-result-mismatch\"},\"status\":{\"const\":412},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/proposal/review-result-mismatch\"}}},{\"properties\":{\"code\":{\"const\":\"proposal.submission-expired\"},\"status\":{\"const\":410},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/proposal/submission-expired\"}}},{\"properties\":{\"code\":{\"const\":\"query.cursor-invalid\"},\"status\":{\"const\":400},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/query/cursor-invalid\"}}},{\"properties\":{\"code\":{\"const\":\"query.filter-required\"},\"status\":{\"const\":400},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/query/filter-required\"}}},{\"properties\":{\"code\":{\"const\":\"query.invalid\"},\"status\":{\"const\":400},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/query/invalid\"}}},{\"properties\":{\"code\":{\"const\":\"request.access-reason-required\"},\"status\":{\"const\":400},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/request/access-reason-required\"}}},{\"properties\":{\"code\":{\"const\":\"request.invalid\"},\"status\":{\"const\":400},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/request/invalid\"}}},{\"properties\":{\"code\":{\"const\":\"request.timeout\"},\"status\":{\"const\":504},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/request/timeout\"}}},{\"properties\":{\"code\":{\"const\":\"resource.not-found\"},\"status\":{\"const\":404},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/resource/not-found\"}}},{\"properties\":{\"code\":{\"const\":\"runtime.field-encryption.unavailable\"},\"status\":{\"const\":503},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/runtime/field-encryption/unavailable\"}}},{\"properties\":{\"code\":{\"const\":\"service.unavailable\"},\"status\":{\"const\":503},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/service/unavailable\"}}},{\"properties\":{\"code\":{\"const\":\"source.unavailable\"},\"status\":{\"const\":503},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/source/unavailable\"}}},{\"properties\":{\"code\":{\"const\":\"statistical-dataset.domain-violation\"},\"status\":{\"const\":500},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/statistical-dataset/domain-violation\"}}},{\"properties\":{\"code\":{\"const\":\"statistical-dataset.release-refused\"},\"status\":{\"const\":422},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/statistical-dataset/release-refused\"}}},{\"properties\":{\"code\":{\"const\":\"statistical-dataset.version-conflict\"},\"status\":{\"const\":409},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/statistical-dataset/version-conflict\"}}},{\"properties\":{\"code\":{\"const\":\"statistical-dataset.version-withdrawn\"},\"status\":{\"const\":410},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/statistical-dataset/version-withdrawn\"}}},{\"properties\":{\"code\":{\"const\":\"unsupported.media-type\"},\"status\":{\"const\":415},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/unsupported/media-type\"}}},{\"properties\":{\"code\":{\"const\":\"write.outside-boundary\"},\"status\":{\"const\":403},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/write/outside-boundary\"}}}],\"properties\":{\"accessProfiles\":{\"items\":{\"maxLength\":128,\"minLength\":1,\"type\":\"string\"},\"minItems\":2,\"type\":\"array\",\"uniqueItems\":true},\"atField\":{\"maxLength\":128,\"minLength\":1,\"type\":\"string\"},\"code\":{\"enum\":[\"access-profile.ambiguous\",\"action.evidence-failed\",\"action.guard-failed\",\"action.handler-failed\",\"action.refused\",\"attachment.content-type\",\"attachment.digest-mismatch\",\"attachment.limit-reached\",\"attachment.required\",\"attachment.slot-write-once\",\"attachment.too-large\",\"attachment.verification-pending\",\"attachment.verification-rejected\",\"authentication.refused\",\"idempotency.expired\",\"idempotency.key-reused\",\"ingestion.chunk-mismatch\",\"ingestion.profile-mismatch\",\"ingestion.receipt-erased\",\"ingestion.run-blocked\",\"ingestion.run-not-open\",\"lookup.unresolved\",\"mutation.conflict\",\"precondition.failed\",\"precondition.required\",\"profile.not-authorized\",\"proposal.rejected\",\"proposal.review-result-mismatch\",\"proposal.submission-expired\",\"query.cursor-invalid\",\"query.filter-required\",\"query.invalid\",\"request.access-reason-required\",\"request.invalid\",\"request.timeout\",\"resource.not-found\",\"runtime.field-encryption.unavailable\",\"service.unavailable\",\"source.unavailable\",\"statistical-dataset.domain-violation\",\"statistical-dataset.release-refused\",\"statistical-dataset.version-conflict\",\"statistical-dataset.version-withdrawn\",\"unsupported.media-type\",\"write.outside-boundary\"],\"type\":\"string\"},\"constraintId\":{\"maxLength\":128,\"minLength\":1,\"type\":\"string\"},\"constraintKind\":{\"enum\":[\"compare\",\"int-range\",\"vocabulary\"],\"type\":\"string\"},\"detail\":{\"maxLength\":256,\"type\":\"string\"},\"failedCheck\":{\"type\":\"string\"},\"field\":{\"maxLength\":128,\"minLength\":1,\"type\":\"string\"},\"fieldId\":{\"maxLength\":128,\"minLength\":1,\"type\":\"string\"},\"fieldPath\":{\"maxLength\":256,\"type\":\"string\"},\"guardReason\":{\"pattern\":\"^[a-z][a-z0-9_-]{0,63}$\",\"type\":\"string\"},\"left\":{\"maxLength\":128,\"minLength\":1,\"type\":\"string\"},\"notAfterField\":{\"maxLength\":128,\"minLength\":1,\"type\":\"string\"},\"reasonCode\":{\"enum\":[\"computation-error\",\"source-data-error\",\"disclosure-risk\"],\"type\":\"string\"},\"recordType\":{\"maxLength\":128,\"minLength\":1,\"type\":\"string\"},\"refusalCode\":{\"maxLength\":128,\"minLength\":1,\"type\":\"string\"},\"requiredFilters\":{\"items\":{\"items\":{\"maxLength\":64,\"minLength\":1,\"type\":\"string\"},\"maxItems\":32,\"minItems\":1,\"type\":\"array\",\"uniqueItems\":true},\"maxItems\":8,\"minItems\":1,\"type\":\"array\"},\"right\":{\"maxLength\":128,\"minLength\":1,\"type\":\"string\"},\"status\":{\"maximum\":599,\"minimum\":400,\"type\":\"integer\"},\"title\":{\"maxLength\":128,\"type\":\"string\"},\"traceId\":{\"maxLength\":32,\"minLength\":32,\"pattern\":\"^[0-9a-f]{32}$\",\"type\":\"string\"},\"type\":{\"maxLength\":256,\"type\":\"string\"}},\"required\":[\"type\",\"title\",\"status\",\"detail\",\"code\",\"traceId\"],\"type\":\"object\"}")], + ["/components/schemas/Problem", JSON.parse("{\"additionalProperties\":false,\"allOf\":[{\"if\":{\"properties\":{\"code\":{\"enum\":[\"attachment.required\",\"attachment.verification-pending\",\"attachment.verification-rejected\"]}}},\"then\":{\"allOf\":[{\"else\":{\"properties\":{\"status\":{\"const\":422}}},\"if\":{\"properties\":{\"code\":{\"const\":\"attachment.verification-pending\"}}},\"then\":{\"properties\":{\"status\":{\"const\":409}}}}],\"properties\":{\"fieldPath\":{\"pattern\":\"^/attachments/[a-z][a-z0-9_-]{0,63}$\",\"type\":\"string\"}},\"propertyNames\":{\"enum\":[\"type\",\"title\",\"status\",\"detail\",\"code\",\"traceId\",\"fieldPath\"]},\"required\":[\"fieldPath\"]}},{\"if\":{\"properties\":{\"code\":{\"const\":\"write.outside-boundary\"}}},\"then\":{\"properties\":{\"code\":{\"const\":\"write.outside-boundary\"},\"detail\":{\"const\":\"The write falls outside what the selected access profile may write: its row boundary or a disclosure condition.\"},\"status\":{\"const\":403},\"title\":{\"const\":\"Forbidden\"},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/write/outside-boundary\"}},\"propertyNames\":{\"enum\":[\"type\",\"title\",\"status\",\"detail\",\"code\",\"traceId\",\"failedCheck\"]}}},{\"if\":{\"properties\":{\"code\":{\"not\":{\"const\":\"action.guard-failed\"}}}},\"then\":{\"not\":{\"required\":[\"guardReason\"]}}},{\"if\":{\"properties\":{\"code\":{\"const\":\"action.refused\"}}},\"then\":{\"properties\":{\"status\":{\"const\":422}},\"required\":[\"refusalCode\"]}},{\"if\":{\"properties\":{\"code\":{\"const\":\"statistical-dataset.release-refused\"}}},\"then\":{\"properties\":{\"refusalCode\":{\"enum\":[\"period-not-ended\",\"before-first-period\",\"provisional-after-final\",\"already-withdrawn\",\"negative-value\"]},\"status\":{\"const\":422}},\"required\":[\"refusalCode\"]}},{\"if\":{\"properties\":{\"code\":{\"not\":{\"enum\":[\"action.refused\",\"statistical-dataset.release-refused\"]}}}},\"then\":{\"not\":{\"required\":[\"refusalCode\"]}}},{\"if\":{\"properties\":{\"code\":{\"const\":\"statistical-dataset.version-withdrawn\"}}},\"then\":{\"properties\":{\"status\":{\"const\":410}},\"required\":[\"reasonCode\"]}},{\"if\":{\"properties\":{\"code\":{\"not\":{\"const\":\"statistical-dataset.version-withdrawn\"}}}},\"then\":{\"not\":{\"required\":[\"reasonCode\"]}}},{\"if\":{\"properties\":{\"code\":{\"const\":\"access-profile.ambiguous\"}}},\"then\":{\"additionalProperties\":true,\"not\":{\"required\":[\"failedCheck\"]},\"properties\":{\"status\":{\"const\":400}},\"required\":[\"accessProfiles\"]}},{\"if\":{\"properties\":{\"code\":{\"not\":{\"const\":\"access-profile.ambiguous\"}}}},\"then\":{\"not\":{\"required\":[\"accessProfiles\"]}}},{\"if\":{\"properties\":{\"code\":{\"const\":\"action.evidence-failed\"}}},\"then\":{\"properties\":{\"detail\":{\"const\":\"The declared Evidence dependency could not be accepted.\"},\"fieldPath\":{\"pattern\":\"^/evidence/[a-z][a-z0-9_-]{0,63}$\",\"type\":\"string\"},\"status\":{\"const\":503}}}},{\"if\":{\"properties\":{\"code\":{\"const\":\"action.handler-failed\"}}},\"then\":{\"properties\":{\"status\":{\"const\":500}}}},{\"if\":{\"anyOf\":[{\"required\":[\"atField\"]},{\"required\":[\"notAfterField\"]}]},\"then\":{\"properties\":{\"code\":{\"const\":\"request.invalid\"},\"status\":{\"const\":400}},\"required\":[\"atField\",\"notAfterField\"]}},{\"if\":{\"anyOf\":[{\"required\":[\"recordType\"]},{\"required\":[\"fieldId\"]},{\"required\":[\"constraintId\"]},{\"required\":[\"constraintKind\"]},{\"required\":[\"left\"]},{\"required\":[\"right\"]},{\"required\":[\"field\"]}]},\"then\":{\"oneOf\":[{\"not\":{\"anyOf\":[{\"required\":[\"constraintId\"]},{\"required\":[\"constraintKind\"]},{\"required\":[\"left\"]},{\"required\":[\"right\"]},{\"required\":[\"field\"]}]},\"required\":[\"fieldId\"]},{\"not\":{\"required\":[\"fieldId\"]},\"oneOf\":[{\"not\":{\"required\":[\"field\"]},\"properties\":{\"constraintKind\":{\"const\":\"compare\"}},\"required\":[\"left\",\"right\"]},{\"not\":{\"anyOf\":[{\"required\":[\"left\"]},{\"required\":[\"right\"]}]},\"properties\":{\"constraintKind\":{\"enum\":[\"int-range\",\"vocabulary\"]}},\"required\":[\"field\"]}],\"required\":[\"constraintId\",\"constraintKind\"]}],\"properties\":{\"code\":{\"const\":\"mutation.conflict\"},\"status\":{\"const\":409}},\"required\":[\"recordType\"]}}],\"anyOf\":[{\"properties\":{\"code\":{\"const\":\"access-profile.ambiguous\"},\"status\":{\"const\":400},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/access-profile/ambiguous\"}}},{\"properties\":{\"code\":{\"const\":\"action.evidence-failed\"},\"status\":{\"const\":503},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/action/evidence-failed\"}}},{\"properties\":{\"code\":{\"const\":\"action.guard-failed\"},\"status\":{\"const\":412},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/action/guard-failed\"}}},{\"properties\":{\"code\":{\"const\":\"action.handler-failed\"},\"status\":{\"const\":500},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/action/handler-failed\"}}},{\"properties\":{\"code\":{\"const\":\"action.refused\"},\"status\":{\"const\":422},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/action/refused\"}}},{\"properties\":{\"code\":{\"const\":\"attachment.content-type\"},\"status\":{\"const\":415},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/attachment/content-type\"}}},{\"properties\":{\"code\":{\"const\":\"attachment.digest-mismatch\"},\"status\":{\"const\":422},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/attachment/digest-mismatch\"}}},{\"properties\":{\"code\":{\"const\":\"attachment.limit-reached\"},\"status\":{\"const\":409},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/attachment/limit-reached\"}}},{\"properties\":{\"code\":{\"const\":\"attachment.required\"},\"status\":{\"const\":422},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/attachment/required\"}}},{\"properties\":{\"code\":{\"const\":\"attachment.slot-write-once\"},\"status\":{\"const\":409},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/attachment/slot-write-once\"}}},{\"properties\":{\"code\":{\"const\":\"attachment.too-large\"},\"status\":{\"const\":413},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/attachment/too-large\"}}},{\"properties\":{\"code\":{\"const\":\"attachment.verification-pending\"},\"status\":{\"const\":409},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/attachment/verification-pending\"}}},{\"properties\":{\"code\":{\"const\":\"attachment.verification-rejected\"},\"status\":{\"const\":422},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/attachment/verification-rejected\"}}},{\"properties\":{\"code\":{\"const\":\"authentication.refused\"},\"status\":{\"const\":401},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/authentication/refused\"}}},{\"properties\":{\"code\":{\"const\":\"idempotency.expired\"},\"status\":{\"const\":410},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/idempotency/expired\"}}},{\"properties\":{\"code\":{\"const\":\"idempotency.key-reused\"},\"status\":{\"const\":409},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/idempotency/key-reused\"}}},{\"properties\":{\"code\":{\"const\":\"ingestion.chunk-mismatch\"},\"status\":{\"const\":409},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/ingestion/chunk-mismatch\"}}},{\"properties\":{\"code\":{\"const\":\"ingestion.profile-mismatch\"},\"status\":{\"const\":403},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/ingestion/profile-mismatch\"}}},{\"properties\":{\"code\":{\"const\":\"ingestion.receipt-erased\"},\"status\":{\"const\":410},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/ingestion/receipt-erased\"}}},{\"properties\":{\"code\":{\"const\":\"ingestion.run-blocked\"},\"status\":{\"const\":409},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/ingestion/run-blocked\"}}},{\"properties\":{\"code\":{\"const\":\"ingestion.run-not-open\"},\"status\":{\"const\":409},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/ingestion/run-not-open\"}}},{\"properties\":{\"code\":{\"const\":\"lookup.unresolved\"},\"status\":{\"const\":404},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/lookup/unresolved\"}}},{\"properties\":{\"code\":{\"const\":\"mutation.conflict\"},\"status\":{\"const\":409},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/mutation/conflict\"}}},{\"properties\":{\"code\":{\"const\":\"precondition.failed\"},\"status\":{\"const\":412},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/precondition/failed\"}}},{\"properties\":{\"code\":{\"const\":\"precondition.required\"},\"status\":{\"const\":428},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/precondition/required\"}}},{\"properties\":{\"code\":{\"const\":\"profile.not-authorized\"},\"status\":{\"const\":403},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/profile/not-authorized\"}}},{\"properties\":{\"code\":{\"const\":\"proposal.form-limit-reached\"},\"status\":{\"const\":409},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/proposal/form-limit-reached\"}}},{\"properties\":{\"code\":{\"const\":\"proposal.form-undeclared\"},\"status\":{\"const\":404},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/proposal/form-undeclared\"}}},{\"properties\":{\"code\":{\"const\":\"proposal.message-limit-reached\"},\"status\":{\"const\":409},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/proposal/message-limit-reached\"}}},{\"properties\":{\"code\":{\"const\":\"proposal.rejected\"},\"status\":{\"const\":409},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/proposal/rejected\"}}},{\"properties\":{\"code\":{\"const\":\"proposal.review-result-mismatch\"},\"status\":{\"const\":412},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/proposal/review-result-mismatch\"}}},{\"properties\":{\"code\":{\"const\":\"proposal.subject-changed\"},\"status\":{\"const\":409},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/proposal/subject-changed\"}}},{\"properties\":{\"code\":{\"const\":\"proposal.subject-not-caller\"},\"status\":{\"const\":403},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/proposal/subject-not-caller\"}}},{\"properties\":{\"code\":{\"const\":\"proposal.submission-expired\"},\"status\":{\"const\":410},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/proposal/submission-expired\"}}},{\"properties\":{\"code\":{\"const\":\"query.cursor-invalid\"},\"status\":{\"const\":400},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/query/cursor-invalid\"}}},{\"properties\":{\"code\":{\"const\":\"query.filter-required\"},\"status\":{\"const\":400},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/query/filter-required\"}}},{\"properties\":{\"code\":{\"const\":\"query.invalid\"},\"status\":{\"const\":400},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/query/invalid\"}}},{\"properties\":{\"code\":{\"const\":\"request.access-reason-required\"},\"status\":{\"const\":400},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/request/access-reason-required\"}}},{\"properties\":{\"code\":{\"const\":\"request.invalid\"},\"status\":{\"const\":400},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/request/invalid\"}}},{\"properties\":{\"code\":{\"const\":\"request.timeout\"},\"status\":{\"const\":504},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/request/timeout\"}}},{\"properties\":{\"code\":{\"const\":\"resource.not-found\"},\"status\":{\"const\":404},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/resource/not-found\"}}},{\"properties\":{\"code\":{\"const\":\"runtime.field-encryption.unavailable\"},\"status\":{\"const\":503},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/runtime/field-encryption/unavailable\"}}},{\"properties\":{\"code\":{\"const\":\"service.unavailable\"},\"status\":{\"const\":503},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/service/unavailable\"}}},{\"properties\":{\"code\":{\"const\":\"source.unavailable\"},\"status\":{\"const\":503},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/source/unavailable\"}}},{\"properties\":{\"code\":{\"const\":\"statistical-dataset.domain-violation\"},\"status\":{\"const\":500},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/statistical-dataset/domain-violation\"}}},{\"properties\":{\"code\":{\"const\":\"statistical-dataset.release-refused\"},\"status\":{\"const\":422},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/statistical-dataset/release-refused\"}}},{\"properties\":{\"code\":{\"const\":\"statistical-dataset.version-conflict\"},\"status\":{\"const\":409},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/statistical-dataset/version-conflict\"}}},{\"properties\":{\"code\":{\"const\":\"statistical-dataset.version-withdrawn\"},\"status\":{\"const\":410},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/statistical-dataset/version-withdrawn\"}}},{\"properties\":{\"code\":{\"const\":\"unsupported.media-type\"},\"status\":{\"const\":415},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/unsupported/media-type\"}}},{\"properties\":{\"code\":{\"const\":\"write.outside-boundary\"},\"status\":{\"const\":403},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-breg/write/outside-boundary\"}}}],\"properties\":{\"accessProfiles\":{\"items\":{\"maxLength\":128,\"minLength\":1,\"type\":\"string\"},\"minItems\":2,\"type\":\"array\",\"uniqueItems\":true},\"atField\":{\"maxLength\":128,\"minLength\":1,\"type\":\"string\"},\"code\":{\"enum\":[\"access-profile.ambiguous\",\"action.evidence-failed\",\"action.guard-failed\",\"action.handler-failed\",\"action.refused\",\"attachment.content-type\",\"attachment.digest-mismatch\",\"attachment.limit-reached\",\"attachment.required\",\"attachment.slot-write-once\",\"attachment.too-large\",\"attachment.verification-pending\",\"attachment.verification-rejected\",\"authentication.refused\",\"idempotency.expired\",\"idempotency.key-reused\",\"ingestion.chunk-mismatch\",\"ingestion.profile-mismatch\",\"ingestion.receipt-erased\",\"ingestion.run-blocked\",\"ingestion.run-not-open\",\"lookup.unresolved\",\"mutation.conflict\",\"precondition.failed\",\"precondition.required\",\"profile.not-authorized\",\"proposal.form-limit-reached\",\"proposal.form-undeclared\",\"proposal.message-limit-reached\",\"proposal.rejected\",\"proposal.review-result-mismatch\",\"proposal.subject-changed\",\"proposal.subject-not-caller\",\"proposal.submission-expired\",\"query.cursor-invalid\",\"query.filter-required\",\"query.invalid\",\"request.access-reason-required\",\"request.invalid\",\"request.timeout\",\"resource.not-found\",\"runtime.field-encryption.unavailable\",\"service.unavailable\",\"source.unavailable\",\"statistical-dataset.domain-violation\",\"statistical-dataset.release-refused\",\"statistical-dataset.version-conflict\",\"statistical-dataset.version-withdrawn\",\"unsupported.media-type\",\"write.outside-boundary\"],\"type\":\"string\"},\"constraintId\":{\"maxLength\":128,\"minLength\":1,\"type\":\"string\"},\"constraintKind\":{\"enum\":[\"compare\",\"int-range\",\"vocabulary\"],\"type\":\"string\"},\"detail\":{\"maxLength\":256,\"type\":\"string\"},\"failedCheck\":{\"type\":\"string\"},\"field\":{\"maxLength\":128,\"minLength\":1,\"type\":\"string\"},\"fieldId\":{\"maxLength\":128,\"minLength\":1,\"type\":\"string\"},\"fieldPath\":{\"maxLength\":256,\"type\":\"string\"},\"guardReason\":{\"pattern\":\"^[a-z][a-z0-9_-]{0,63}$\",\"type\":\"string\"},\"left\":{\"maxLength\":128,\"minLength\":1,\"type\":\"string\"},\"notAfterField\":{\"maxLength\":128,\"minLength\":1,\"type\":\"string\"},\"reasonCode\":{\"enum\":[\"computation-error\",\"source-data-error\",\"disclosure-risk\"],\"type\":\"string\"},\"recordType\":{\"maxLength\":128,\"minLength\":1,\"type\":\"string\"},\"refusalCode\":{\"maxLength\":128,\"minLength\":1,\"type\":\"string\"},\"requiredFilters\":{\"items\":{\"items\":{\"maxLength\":64,\"minLength\":1,\"type\":\"string\"},\"maxItems\":32,\"minItems\":1,\"type\":\"array\",\"uniqueItems\":true},\"maxItems\":8,\"minItems\":1,\"type\":\"array\"},\"right\":{\"maxLength\":128,\"minLength\":1,\"type\":\"string\"},\"status\":{\"maximum\":599,\"minimum\":400,\"type\":\"integer\"},\"title\":{\"maxLength\":128,\"type\":\"string\"},\"traceId\":{\"maxLength\":32,\"minLength\":32,\"pattern\":\"^[0-9a-f]{32}$\",\"type\":\"string\"},\"type\":{\"maxLength\":256,\"type\":\"string\"}},\"required\":[\"type\",\"title\",\"status\",\"detail\",\"code\",\"traceId\"],\"type\":\"object\"}")], ["/components/schemas/ReviewCompletion", JSON.parse("{\"additionalProperties\":false,\"properties\":{\"completedAt\":{\"type\":\"string\"},\"eventId\":{\"type\":\"string\"},\"requestId\":{\"type\":\"string\"},\"resultId\":{\"type\":\"string\"},\"type\":{\"const\":\"review.completed\"}},\"required\":[\"type\",\"eventId\",\"requestId\",\"resultId\",\"completedAt\"],\"type\":\"object\"}")], ["/components/schemas/action-register-contact-invoke-input", JSON.parse("{\"additionalProperties\":false,\"properties\":{\"input\":{\"additionalProperties\":false,\"properties\":{\"email\":{\"maxLength\":254,\"minLength\":1,\"type\":\"string\"},\"jurisdiction\":{\"maxLength\":40,\"minLength\":1,\"type\":\"string\"},\"name\":{\"maxLength\":160,\"minLength\":1,\"type\":\"string\"}},\"required\":[],\"type\":\"object\"}},\"required\":[\"input\"],\"type\":\"object\"}")], - ["/components/schemas/action-register-contact-invoke-response", JSON.parse("{\"additionalProperties\":false,\"properties\":{\"actionId\":{\"type\":\"string\"},\"actionRevision\":{\"type\":\"string\"},\"application\":{\"additionalProperties\":false,\"properties\":{\"applicationId\":{\"type\":\"string\"},\"effectDigest\":{\"pattern\":\"^sha256:[0-9a-f]{64}$\",\"type\":\"string\"},\"resultLinks\":{\"items\":{\"additionalProperties\":false,\"properties\":{\"recordId\":{\"type\":\"string\"},\"recordType\":{\"type\":\"string\"},\"revision\":{\"minimum\":1,\"type\":\"integer\"}},\"required\":[\"recordType\",\"recordId\",\"revision\"],\"type\":\"object\"},\"maxItems\":16,\"type\":\"array\"},\"submissionVersion\":{\"minimum\":1,\"type\":\"integer\"}},\"required\":[\"applicationId\",\"submissionVersion\",\"effectDigest\",\"resultLinks\"],\"type\":\"object\"},\"applicationStatus\":{\"additionalProperties\":false,\"properties\":{\"automaticRetry\":{\"additionalProperties\":false,\"properties\":{\"attempts\":{\"maximum\":1000,\"minimum\":0,\"type\":\"integer\"},\"maximumAttempts\":{\"maximum\":1000,\"minimum\":1,\"type\":\"integer\"},\"scheduled\":{\"type\":\"boolean\"}},\"required\":[\"scheduled\",\"attempts\",\"maximumAttempts\"],\"type\":\"object\"},\"mode\":{\"enum\":[\"automatic\",\"manual\"]},\"reason\":{\"enum\":[\"package-changed\",\"dependency-outage\",\"lease-expired\",\"application-refused\",\"attempts-exhausted\"]},\"recovery\":{\"enum\":[\"retry\",\"rebase\",\"revise\",\"correct-input\"]},\"state\":{\"enum\":[\"awaiting-review\",\"pending\",\"applying\",\"blocked\",\"applied\",\"cancelled\",\"rejected\"]}},\"required\":[\"state\",\"mode\"],\"type\":\"object\"},\"asks\":{\"items\":{\"additionalProperties\":false,\"properties\":{\"answer\":{\"additionalProperties\":false,\"properties\":{\"additions\":{\"items\":{\"type\":\"string\"},\"maxItems\":32,\"type\":\"array\",\"uniqueItems\":true},\"answeredAt\":{\"type\":\"string\"},\"text\":{\"maxLength\":2000,\"minLength\":1,\"type\":\"string\"}},\"required\":[\"additions\",\"answeredAt\"],\"type\":\"object\"},\"askedAt\":{\"type\":\"string\"},\"dueAt\":{\"type\":\"string\"},\"id\":{\"type\":\"string\"},\"links\":{\"additionalProperties\":false,\"properties\":{\"answer\":{\"additionalProperties\":false,\"properties\":{\"accessProfile\":{\"type\":\"string\"},\"availability\":{\"additionalProperties\":false,\"if\":{\"properties\":{\"available\":{\"const\":false}}},\"properties\":{\"available\":{\"type\":\"boolean\"},\"observedRevision\":{\"minimum\":1,\"type\":\"integer\"},\"reason\":{\"enum\":[\"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\":{\"enum\":[\"refresh\",\"revise\",\"retry\",\"rebase\",\"correct-input\",\"receipt-only\"]}},\"required\":[\"available\",\"observedRevision\"],\"then\":{\"required\":[\"reason\",\"recovery\"]},\"type\":\"object\"},\"ifMatch\":{\"type\":\"string\"},\"method\":{\"const\":\"POST\"},\"operation\":{\"const\":\"answer\"},\"path\":{\"type\":\"string\"}},\"required\":[\"method\",\"path\",\"accessProfile\",\"operation\",\"ifMatch\",\"availability\"],\"type\":\"object\"}},\"type\":\"object\"},\"state\":{\"enum\":[\"open\",\"answered\",\"expired\",\"closed\"]},\"text\":{\"maxLength\":2000,\"minLength\":1,\"type\":\"string\"},\"wants\":{\"items\":{\"additionalProperties\":false,\"properties\":{\"kind\":{\"enum\":[\"answer\",\"document\"]}},\"required\":[\"kind\"],\"type\":\"object\"},\"maxItems\":8,\"type\":\"array\",\"uniqueItems\":true}},\"required\":[\"id\",\"text\",\"wants\",\"askedAt\",\"state\",\"links\"],\"type\":\"object\"},\"maxItems\":50,\"type\":\"array\"},\"attachments\":{\"additionalProperties\":{\"additionalProperties\":false,\"properties\":{\"classification\":{\"enum\":[\"public\",\"internal\",\"restricted\"]},\"contentTypes\":{\"items\":{\"type\":\"string\"},\"maxItems\":16,\"minItems\":1,\"type\":\"array\",\"uniqueItems\":true},\"id\":{\"type\":\"string\"},\"links\":{\"additionalProperties\":{\"additionalProperties\":false,\"properties\":{\"accessProfile\":{\"type\":\"string\"},\"availability\":{\"additionalProperties\":false,\"if\":{\"properties\":{\"available\":{\"const\":false}}},\"properties\":{\"available\":{\"type\":\"boolean\"},\"observedRevision\":{\"minimum\":1,\"type\":\"integer\"},\"reason\":{\"enum\":[\"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\":{\"enum\":[\"refresh\",\"revise\",\"retry\",\"rebase\",\"correct-input\",\"receipt-only\"]}},\"required\":[\"available\",\"observedRevision\"],\"then\":{\"required\":[\"reason\",\"recovery\"]},\"type\":\"object\"},\"ifMatch\":{\"type\":\"string\"},\"method\":{\"enum\":[\"GET\",\"PATCH\",\"DELETE\"]},\"operation\":{\"enum\":[\"download\",\"upload\",\"remove\"]},\"path\":{\"type\":\"string\"}},\"required\":[\"method\",\"path\",\"accessProfile\",\"operation\"],\"type\":\"object\"},\"type\":\"object\"},\"maximumBytes\":{\"maximum\":16777216,\"minimum\":1,\"type\":\"integer\"},\"required\":{\"type\":\"boolean\"},\"value\":{\"additionalProperties\":false,\"properties\":{\"byteSize\":{\"minimum\":1,\"type\":\"integer\"},\"contentType\":{\"type\":\"string\"},\"sha256\":{\"pattern\":\"^[a-f0-9]{64}$\",\"type\":\"string\"},\"submissionVersion\":{\"minimum\":0,\"type\":\"integer\"},\"uploadedAt\":{\"type\":\"string\"},\"verificationStatus\":{\"enum\":[\"notRequired\",\"pending\",\"approved\",\"rejected\"]}},\"required\":[\"submissionVersion\",\"sha256\",\"contentType\",\"byteSize\",\"verificationStatus\"],\"type\":\"object\"}},\"required\":[\"id\",\"required\",\"maximumBytes\",\"contentTypes\",\"classification\",\"links\"],\"type\":\"object\"},\"maxProperties\":8,\"type\":\"object\"},\"blockedReason\":{\"enum\":[\"package-changed\"]},\"createdAt\":{\"type\":\"string\"},\"decision\":{\"additionalProperties\":false,\"properties\":{\"decidedAt\":{\"type\":\"string\"},\"publicReason\":{\"minLength\":1,\"pattern\":\"^[^\\\\u0000-\\\\u001F\\\\u007F-\\\\u009F]*[^\\\\u0000-\\\\u0020\\\\u007F-\\\\u00A0\\\\u1680\\\\u2000-\\\\u200A\\\\u2028\\\\u2029\\\\u202F\\\\u205F\\\\u3000][^\\\\u0000-\\\\u001F\\\\u007F-\\\\u009F]*$\",\"type\":\"string\"},\"status\":{\"enum\":[\"approved\",\"rejected\",\"changes-requested\",\"answered\"]}},\"required\":[\"status\",\"decidedAt\"],\"type\":\"object\"},\"effectDigest\":{\"type\":\"string\"},\"handoffRefusal\":{\"additionalProperties\":false,\"properties\":{\"code\":{\"enum\":[\"review.initiator-required\",\"review.initiator-excluded\",\"review.policy-mismatch\",\"review.refused\"]}},\"required\":[\"code\"],\"type\":\"object\"},\"id\":{\"type\":\"string\"},\"input\":{\"type\":\"object\"},\"links\":{\"additionalProperties\":{\"additionalProperties\":false,\"properties\":{\"accessProfile\":{\"type\":\"string\"},\"availability\":{\"additionalProperties\":false,\"if\":{\"properties\":{\"available\":{\"const\":false}}},\"properties\":{\"available\":{\"type\":\"boolean\"},\"observedRevision\":{\"minimum\":1,\"type\":\"integer\"},\"reason\":{\"enum\":[\"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\":{\"enum\":[\"refresh\",\"revise\",\"retry\",\"rebase\",\"correct-input\",\"receipt-only\"]}},\"required\":[\"available\",\"observedRevision\"],\"then\":{\"required\":[\"reason\",\"recovery\"]},\"type\":\"object\"},\"ifMatch\":{\"type\":\"string\"},\"method\":{\"enum\":[\"GET\",\"POST\"]},\"operation\":{\"type\":\"string\"},\"path\":{\"type\":\"string\"}},\"required\":[\"method\",\"path\",\"accessProfile\",\"operation\"],\"type\":\"object\"},\"type\":\"object\"},\"revision\":{\"minimum\":1,\"type\":\"integer\"},\"state\":{\"enum\":[\"draft\",\"submitted\",\"applied\",\"cancelled\",\"rejected\"]},\"status\":{\"enum\":[\"draft\",\"awaiting-party\",\"in-review\",\"approved\",\"processing\",\"applied\",\"rejected\",\"cancelled\"]},\"submissionVersion\":{\"minimum\":0,\"type\":\"integer\"},\"title\":{\"maxLength\":1024,\"type\":\"string\"},\"turn\":{\"enum\":[\"party\",\"official\",\"nobody\"]}},\"required\":[\"id\",\"actionId\",\"actionRevision\",\"submissionVersion\",\"revision\",\"state\",\"turn\",\"links\"],\"type\":\"object\"}")], + ["/components/schemas/action-register-contact-invoke-response", JSON.parse("{\"additionalProperties\":false,\"properties\":{\"actionId\":{\"type\":\"string\"},\"actionRevision\":{\"type\":\"string\"},\"application\":{\"additionalProperties\":false,\"properties\":{\"applicationId\":{\"type\":\"string\"},\"effectDigest\":{\"pattern\":\"^sha256:[0-9a-f]{64}$\",\"type\":\"string\"},\"resultLinks\":{\"items\":{\"additionalProperties\":false,\"properties\":{\"recordId\":{\"type\":\"string\"},\"recordType\":{\"type\":\"string\"},\"revision\":{\"minimum\":1,\"type\":\"integer\"}},\"required\":[\"recordType\",\"recordId\",\"revision\"],\"type\":\"object\"},\"maxItems\":16,\"type\":\"array\"},\"submissionVersion\":{\"minimum\":1,\"type\":\"integer\"}},\"required\":[\"applicationId\",\"submissionVersion\",\"effectDigest\",\"resultLinks\"],\"type\":\"object\"},\"applicationStatus\":{\"additionalProperties\":false,\"properties\":{\"automaticRetry\":{\"additionalProperties\":false,\"properties\":{\"attempts\":{\"maximum\":1000,\"minimum\":0,\"type\":\"integer\"},\"maximumAttempts\":{\"maximum\":1000,\"minimum\":1,\"type\":\"integer\"},\"scheduled\":{\"type\":\"boolean\"}},\"required\":[\"scheduled\",\"attempts\",\"maximumAttempts\"],\"type\":\"object\"},\"mode\":{\"enum\":[\"automatic\",\"manual\"]},\"reason\":{\"enum\":[\"package-changed\",\"dependency-outage\",\"lease-expired\",\"application-refused\",\"attempts-exhausted\"]},\"recovery\":{\"enum\":[\"retry\",\"rebase\",\"revise\",\"correct-input\"]},\"state\":{\"enum\":[\"awaiting-review\",\"pending\",\"applying\",\"blocked\",\"applied\",\"cancelled\",\"rejected\"]}},\"required\":[\"state\",\"mode\"],\"type\":\"object\"},\"asks\":{\"items\":{\"additionalProperties\":false,\"properties\":{\"answer\":{\"additionalProperties\":false,\"properties\":{\"additions\":{\"items\":{\"type\":\"string\"},\"maxItems\":32,\"type\":\"array\",\"uniqueItems\":true},\"answeredAt\":{\"type\":\"string\"},\"formEntries\":{\"items\":{\"type\":\"string\"},\"maxItems\":32,\"type\":\"array\",\"uniqueItems\":true},\"text\":{\"maxLength\":2000,\"minLength\":1,\"type\":\"string\"}},\"required\":[\"additions\",\"answeredAt\"],\"type\":\"object\"},\"askedAt\":{\"type\":\"string\"},\"dueAt\":{\"type\":\"string\"},\"id\":{\"type\":\"string\"},\"links\":{\"additionalProperties\":false,\"properties\":{\"answer\":{\"additionalProperties\":false,\"properties\":{\"accessProfile\":{\"type\":\"string\"},\"availability\":{\"additionalProperties\":false,\"if\":{\"properties\":{\"available\":{\"const\":false}}},\"properties\":{\"available\":{\"type\":\"boolean\"},\"observedRevision\":{\"minimum\":1,\"type\":\"integer\"},\"reason\":{\"enum\":[\"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\":{\"enum\":[\"refresh\",\"revise\",\"retry\",\"rebase\",\"correct-input\",\"receipt-only\"]}},\"required\":[\"available\",\"observedRevision\"],\"then\":{\"required\":[\"reason\",\"recovery\"]},\"type\":\"object\"},\"ifMatch\":{\"type\":\"string\"},\"method\":{\"const\":\"POST\"},\"operation\":{\"const\":\"answer\"},\"path\":{\"type\":\"string\"}},\"required\":[\"method\",\"path\",\"accessProfile\",\"operation\",\"ifMatch\",\"availability\"],\"type\":\"object\"}},\"type\":\"object\"},\"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\",\"links\"],\"type\":\"object\"},\"maxItems\":50,\"type\":\"array\"},\"attachments\":{\"additionalProperties\":{\"additionalProperties\":false,\"properties\":{\"classification\":{\"enum\":[\"public\",\"internal\",\"restricted\"]},\"contentTypes\":{\"items\":{\"type\":\"string\"},\"maxItems\":16,\"minItems\":1,\"type\":\"array\",\"uniqueItems\":true},\"id\":{\"type\":\"string\"},\"links\":{\"additionalProperties\":{\"additionalProperties\":false,\"properties\":{\"accessProfile\":{\"type\":\"string\"},\"availability\":{\"additionalProperties\":false,\"if\":{\"properties\":{\"available\":{\"const\":false}}},\"properties\":{\"available\":{\"type\":\"boolean\"},\"observedRevision\":{\"minimum\":1,\"type\":\"integer\"},\"reason\":{\"enum\":[\"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\":{\"enum\":[\"refresh\",\"revise\",\"retry\",\"rebase\",\"correct-input\",\"receipt-only\"]}},\"required\":[\"available\",\"observedRevision\"],\"then\":{\"required\":[\"reason\",\"recovery\"]},\"type\":\"object\"},\"ifMatch\":{\"type\":\"string\"},\"method\":{\"enum\":[\"GET\",\"PATCH\",\"DELETE\"]},\"operation\":{\"enum\":[\"download\",\"upload\",\"remove\"]},\"path\":{\"type\":\"string\"}},\"required\":[\"method\",\"path\",\"accessProfile\",\"operation\"],\"type\":\"object\"},\"type\":\"object\"},\"maximumBytes\":{\"maximum\":16777216,\"minimum\":1,\"type\":\"integer\"},\"required\":{\"type\":\"boolean\"},\"value\":{\"additionalProperties\":false,\"properties\":{\"byteSize\":{\"minimum\":1,\"type\":\"integer\"},\"contentType\":{\"type\":\"string\"},\"sha256\":{\"pattern\":\"^[a-f0-9]{64}$\",\"type\":\"string\"},\"submissionVersion\":{\"minimum\":0,\"type\":\"integer\"},\"uploadedAt\":{\"type\":\"string\"},\"verificationStatus\":{\"enum\":[\"notRequired\",\"pending\",\"approved\",\"rejected\"]}},\"required\":[\"submissionVersion\",\"sha256\",\"contentType\",\"byteSize\",\"verificationStatus\"],\"type\":\"object\"}},\"required\":[\"id\",\"required\",\"maximumBytes\",\"contentTypes\",\"classification\",\"links\"],\"type\":\"object\"},\"maxProperties\":8,\"type\":\"object\"},\"blockedReason\":{\"enum\":[\"package-changed\"]},\"createdAt\":{\"type\":\"string\"},\"decision\":{\"additionalProperties\":false,\"properties\":{\"decidedAt\":{\"type\":\"string\"},\"publicReason\":{\"minLength\":1,\"pattern\":\"^[^\\\\u0000-\\\\u001F\\\\u007F-\\\\u009F]*[^\\\\u0000-\\\\u0020\\\\u007F-\\\\u00A0\\\\u1680\\\\u2000-\\\\u200A\\\\u2028\\\\u2029\\\\u202F\\\\u205F\\\\u3000][^\\\\u0000-\\\\u001F\\\\u007F-\\\\u009F]*$\",\"type\":\"string\"},\"status\":{\"enum\":[\"approved\",\"rejected\",\"changes-requested\",\"answered\"]}},\"required\":[\"status\",\"decidedAt\"],\"type\":\"object\"},\"effectDigest\":{\"type\":\"string\"},\"handoffRefusal\":{\"additionalProperties\":false,\"properties\":{\"code\":{\"enum\":[\"review.initiator-required\",\"review.initiator-excluded\",\"review.policy-mismatch\",\"review.refused\"]}},\"required\":[\"code\"],\"type\":\"object\"},\"id\":{\"type\":\"string\"},\"input\":{\"type\":\"object\"},\"links\":{\"additionalProperties\":{\"additionalProperties\":false,\"properties\":{\"accessProfile\":{\"type\":\"string\"},\"availability\":{\"additionalProperties\":false,\"if\":{\"properties\":{\"available\":{\"const\":false}}},\"properties\":{\"available\":{\"type\":\"boolean\"},\"observedRevision\":{\"minimum\":1,\"type\":\"integer\"},\"reason\":{\"enum\":[\"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\":{\"enum\":[\"refresh\",\"revise\",\"retry\",\"rebase\",\"correct-input\",\"receipt-only\"]}},\"required\":[\"available\",\"observedRevision\"],\"then\":{\"required\":[\"reason\",\"recovery\"]},\"type\":\"object\"},\"ifMatch\":{\"type\":\"string\"},\"method\":{\"enum\":[\"GET\",\"POST\"]},\"operation\":{\"type\":\"string\"},\"path\":{\"type\":\"string\"}},\"required\":[\"method\",\"path\",\"accessProfile\",\"operation\"],\"type\":\"object\"},\"type\":\"object\"},\"partyRole\":{\"enum\":[\"owner\",\"subject\"]},\"revision\":{\"minimum\":1,\"type\":\"integer\"},\"state\":{\"enum\":[\"draft\",\"submitted\",\"applied\",\"cancelled\",\"rejected\"]},\"status\":{\"enum\":[\"draft\",\"awaiting-party\",\"in-review\",\"approved\",\"processing\",\"applied\",\"rejected\",\"cancelled\"]},\"submissionVersion\":{\"minimum\":0,\"type\":\"integer\"},\"title\":{\"maxLength\":1024,\"type\":\"string\"},\"turn\":{\"enum\":[\"party\",\"official\",\"nobody\"]}},\"required\":[\"id\",\"actionId\",\"actionRevision\",\"submissionVersion\",\"revision\",\"state\",\"turn\",\"links\"],\"type\":\"object\"}")], ["/components/schemas/action-update-contact-email-availability-input", JSON.parse("{\"additionalProperties\":false,\"oneOf\":[{\"properties\":{\"input\":{\"properties\":{\"contactId\":{\"type\":\"string\"}},\"required\":[\"contactId\"]},\"targetInput\":{\"const\":\"contactId\"}}}],\"properties\":{\"input\":{\"additionalProperties\":false,\"properties\":{\"contactId\":{\"type\":\"string\"},\"email\":{\"maxLength\":254,\"minLength\":1,\"type\":\"string\"}},\"required\":[],\"type\":\"object\"},\"targetInput\":{\"enum\":[\"contactId\"],\"type\":\"string\"}},\"required\":[\"targetInput\",\"input\"],\"type\":\"object\"}")], ["/components/schemas/action-update-contact-email-availability-response", JSON.parse("{\"additionalProperties\":false,\"properties\":{\"availability\":{\"oneOf\":[{\"additionalProperties\":false,\"properties\":{\"available\":{\"const\":true},\"observedRevision\":{\"minimum\":1,\"type\":\"integer\"}},\"required\":[\"available\",\"observedRevision\"],\"type\":\"object\"},{\"additionalProperties\":false,\"properties\":{\"available\":{\"const\":false},\"guardLabel\":{\"maxLength\":256,\"minLength\":1,\"type\":\"string\"},\"guardReason\":{\"pattern\":\"^[a-z][a-z0-9_-]{0,63}$\",\"type\":\"string\"},\"observedRevision\":{\"minimum\":1,\"type\":\"integer\"},\"reason\":{\"const\":\"guard-not-satisfied\"},\"recovery\":{\"const\":\"none\"}},\"required\":[\"available\",\"observedRevision\",\"reason\",\"recovery\"],\"type\":\"object\"},{\"additionalProperties\":false,\"properties\":{\"available\":{\"type\":\"null\"},\"missingInputs\":{\"items\":{\"enum\":[\"contactId\",\"email\"],\"type\":\"string\"},\"minItems\":1,\"type\":\"array\",\"uniqueItems\":true},\"observedRevision\":{\"minimum\":1,\"type\":\"integer\"},\"reason\":{\"const\":\"input-required\"},\"recovery\":{\"const\":\"correct-input\"}},\"required\":[\"available\",\"observedRevision\",\"reason\",\"recovery\",\"missingInputs\"],\"type\":\"object\"},{\"additionalProperties\":false,\"properties\":{\"available\":{\"type\":\"null\"},\"observedRevision\":{\"type\":\"null\"},\"reason\":{\"const\":\"not-disclosed\"},\"recovery\":{\"const\":\"none\"}},\"required\":[\"available\",\"observedRevision\",\"reason\",\"recovery\"],\"type\":\"object\"}]}},\"required\":[\"availability\"],\"type\":\"object\"}")], ["/components/schemas/action-update-contact-email-invoke-input", JSON.parse("{\"additionalProperties\":false,\"properties\":{\"input\":{\"additionalProperties\":false,\"properties\":{\"contactId\":{\"type\":\"string\"},\"email\":{\"maxLength\":254,\"minLength\":1,\"type\":\"string\"}},\"required\":[\"contactId\",\"email\"],\"type\":\"object\"},\"preconditions\":{\"additionalProperties\":false,\"properties\":{\"contactId\":{\"additionalProperties\":false,\"properties\":{\"ifMatch\":{\"maxLength\":256,\"minLength\":3,\"pattern\":\"^\\\"[\\\\x21\\\\x23-\\\\x7E]+\\\"$\",\"type\":\"string\"}},\"required\":[\"ifMatch\"],\"type\":\"object\"}},\"required\":[\"contactId\"],\"type\":\"object\"}},\"required\":[\"input\",\"preconditions\"],\"type\":\"object\"}")], @@ -118,21 +120,21 @@ const rules: Record = Object.fromEntries([ ["/paths/~1v1~1actions~1update-contact-email~1target-conditions/post/responses/415/content/application~1problem+json/schema", JSON.parse("{\"$ref\":\"/components/schemas/Problem\"}")], ["/paths/~1v1~1actions~1update-contact-email~1target-conditions/post/responses/503/content/application~1problem+json/schema", JSON.parse("{\"$ref\":\"/components/schemas/Problem\"}")], ["/paths/~1v1~1actions~1update-contact-email~1target-conditions/post/responses/504/content/application~1problem+json/schema", JSON.parse("{\"$ref\":\"/components/schemas/Problem\"}")], - ["/paths/~1v1~1proposals/get/responses/200/content/application~1json/schema", JSON.parse("{\"additionalProperties\":false,\"properties\":{\"items\":{\"items\":{\"additionalProperties\":false,\"properties\":{\"actionId\":{\"type\":\"string\"},\"actionRevision\":{\"type\":\"string\"},\"application\":{\"additionalProperties\":false,\"properties\":{\"applicationId\":{\"type\":\"string\"},\"effectDigest\":{\"pattern\":\"^sha256:[0-9a-f]{64}$\",\"type\":\"string\"},\"resultLinks\":{\"items\":{\"additionalProperties\":false,\"properties\":{\"recordId\":{\"type\":\"string\"},\"recordType\":{\"type\":\"string\"},\"revision\":{\"minimum\":1,\"type\":\"integer\"}},\"required\":[\"recordType\",\"recordId\",\"revision\"],\"type\":\"object\"},\"maxItems\":16,\"type\":\"array\"},\"submissionVersion\":{\"minimum\":1,\"type\":\"integer\"}},\"required\":[\"applicationId\",\"submissionVersion\",\"effectDigest\",\"resultLinks\"],\"type\":\"object\"},\"applicationStatus\":{\"additionalProperties\":false,\"properties\":{\"automaticRetry\":{\"additionalProperties\":false,\"properties\":{\"attempts\":{\"maximum\":1000,\"minimum\":0,\"type\":\"integer\"},\"maximumAttempts\":{\"maximum\":1000,\"minimum\":1,\"type\":\"integer\"},\"scheduled\":{\"type\":\"boolean\"}},\"required\":[\"scheduled\",\"attempts\",\"maximumAttempts\"],\"type\":\"object\"},\"mode\":{\"enum\":[\"automatic\",\"manual\"]},\"reason\":{\"enum\":[\"package-changed\",\"dependency-outage\",\"lease-expired\",\"application-refused\",\"attempts-exhausted\"]},\"recovery\":{\"enum\":[\"retry\",\"rebase\",\"revise\",\"correct-input\"]},\"state\":{\"enum\":[\"awaiting-review\",\"pending\",\"applying\",\"blocked\",\"applied\",\"cancelled\",\"rejected\"]}},\"required\":[\"state\",\"mode\"],\"type\":\"object\"},\"asks\":{\"items\":{\"additionalProperties\":false,\"properties\":{\"answer\":{\"additionalProperties\":false,\"properties\":{\"additions\":{\"items\":{\"type\":\"string\"},\"maxItems\":32,\"type\":\"array\",\"uniqueItems\":true},\"answeredAt\":{\"type\":\"string\"},\"text\":{\"maxLength\":2000,\"minLength\":1,\"type\":\"string\"}},\"required\":[\"additions\",\"answeredAt\"],\"type\":\"object\"},\"askedAt\":{\"type\":\"string\"},\"dueAt\":{\"type\":\"string\"},\"id\":{\"type\":\"string\"},\"links\":{\"additionalProperties\":false,\"properties\":{\"answer\":{\"additionalProperties\":false,\"properties\":{\"accessProfile\":{\"type\":\"string\"},\"availability\":{\"additionalProperties\":false,\"if\":{\"properties\":{\"available\":{\"const\":false}}},\"properties\":{\"available\":{\"type\":\"boolean\"},\"observedRevision\":{\"minimum\":1,\"type\":\"integer\"},\"reason\":{\"enum\":[\"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\":{\"enum\":[\"refresh\",\"revise\",\"retry\",\"rebase\",\"correct-input\",\"receipt-only\"]}},\"required\":[\"available\",\"observedRevision\"],\"then\":{\"required\":[\"reason\",\"recovery\"]},\"type\":\"object\"},\"ifMatch\":{\"type\":\"string\"},\"method\":{\"const\":\"POST\"},\"operation\":{\"const\":\"answer\"},\"path\":{\"type\":\"string\"}},\"required\":[\"method\",\"path\",\"accessProfile\",\"operation\",\"ifMatch\",\"availability\"],\"type\":\"object\"}},\"type\":\"object\"},\"state\":{\"enum\":[\"open\",\"answered\",\"expired\",\"closed\"]},\"text\":{\"maxLength\":2000,\"minLength\":1,\"type\":\"string\"},\"wants\":{\"items\":{\"additionalProperties\":false,\"properties\":{\"kind\":{\"enum\":[\"answer\",\"document\"]}},\"required\":[\"kind\"],\"type\":\"object\"},\"maxItems\":8,\"type\":\"array\",\"uniqueItems\":true}},\"required\":[\"id\",\"text\",\"wants\",\"askedAt\",\"state\",\"links\"],\"type\":\"object\"},\"maxItems\":50,\"type\":\"array\"},\"attachments\":{\"additionalProperties\":{\"additionalProperties\":false,\"properties\":{\"classification\":{\"enum\":[\"public\",\"internal\",\"restricted\"]},\"contentTypes\":{\"items\":{\"type\":\"string\"},\"maxItems\":16,\"minItems\":1,\"type\":\"array\",\"uniqueItems\":true},\"id\":{\"type\":\"string\"},\"links\":{\"additionalProperties\":{\"additionalProperties\":false,\"properties\":{\"accessProfile\":{\"type\":\"string\"},\"availability\":{\"additionalProperties\":false,\"if\":{\"properties\":{\"available\":{\"const\":false}}},\"properties\":{\"available\":{\"type\":\"boolean\"},\"observedRevision\":{\"minimum\":1,\"type\":\"integer\"},\"reason\":{\"enum\":[\"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\":{\"enum\":[\"refresh\",\"revise\",\"retry\",\"rebase\",\"correct-input\",\"receipt-only\"]}},\"required\":[\"available\",\"observedRevision\"],\"then\":{\"required\":[\"reason\",\"recovery\"]},\"type\":\"object\"},\"ifMatch\":{\"type\":\"string\"},\"method\":{\"enum\":[\"GET\",\"PATCH\",\"DELETE\"]},\"operation\":{\"enum\":[\"download\",\"upload\",\"remove\"]},\"path\":{\"type\":\"string\"}},\"required\":[\"method\",\"path\",\"accessProfile\",\"operation\"],\"type\":\"object\"},\"type\":\"object\"},\"maximumBytes\":{\"maximum\":16777216,\"minimum\":1,\"type\":\"integer\"},\"required\":{\"type\":\"boolean\"},\"value\":{\"additionalProperties\":false,\"properties\":{\"byteSize\":{\"minimum\":1,\"type\":\"integer\"},\"contentType\":{\"type\":\"string\"},\"sha256\":{\"pattern\":\"^[a-f0-9]{64}$\",\"type\":\"string\"},\"submissionVersion\":{\"minimum\":0,\"type\":\"integer\"},\"uploadedAt\":{\"type\":\"string\"},\"verificationStatus\":{\"enum\":[\"notRequired\",\"pending\",\"approved\",\"rejected\"]}},\"required\":[\"submissionVersion\",\"sha256\",\"contentType\",\"byteSize\",\"verificationStatus\"],\"type\":\"object\"}},\"required\":[\"id\",\"required\",\"maximumBytes\",\"contentTypes\",\"classification\",\"links\"],\"type\":\"object\"},\"maxProperties\":8,\"type\":\"object\"},\"blockedReason\":{\"enum\":[\"package-changed\"]},\"createdAt\":{\"type\":\"string\"},\"decision\":{\"additionalProperties\":false,\"properties\":{\"decidedAt\":{\"type\":\"string\"},\"publicReason\":{\"minLength\":1,\"pattern\":\"^[^\\\\u0000-\\\\u001F\\\\u007F-\\\\u009F]*[^\\\\u0000-\\\\u0020\\\\u007F-\\\\u00A0\\\\u1680\\\\u2000-\\\\u200A\\\\u2028\\\\u2029\\\\u202F\\\\u205F\\\\u3000][^\\\\u0000-\\\\u001F\\\\u007F-\\\\u009F]*$\",\"type\":\"string\"},\"status\":{\"enum\":[\"approved\",\"rejected\",\"changes-requested\",\"answered\"]}},\"required\":[\"status\",\"decidedAt\"],\"type\":\"object\"},\"effectDigest\":{\"type\":\"string\"},\"handoffRefusal\":{\"additionalProperties\":false,\"properties\":{\"code\":{\"enum\":[\"review.initiator-required\",\"review.initiator-excluded\",\"review.policy-mismatch\",\"review.refused\"]}},\"required\":[\"code\"],\"type\":\"object\"},\"id\":{\"type\":\"string\"},\"input\":{\"type\":\"object\"},\"links\":{\"additionalProperties\":{\"additionalProperties\":false,\"properties\":{\"accessProfile\":{\"type\":\"string\"},\"availability\":{\"additionalProperties\":false,\"if\":{\"properties\":{\"available\":{\"const\":false}}},\"properties\":{\"available\":{\"type\":\"boolean\"},\"observedRevision\":{\"minimum\":1,\"type\":\"integer\"},\"reason\":{\"enum\":[\"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\":{\"enum\":[\"refresh\",\"revise\",\"retry\",\"rebase\",\"correct-input\",\"receipt-only\"]}},\"required\":[\"available\",\"observedRevision\"],\"then\":{\"required\":[\"reason\",\"recovery\"]},\"type\":\"object\"},\"ifMatch\":{\"type\":\"string\"},\"method\":{\"enum\":[\"GET\",\"POST\"]},\"operation\":{\"type\":\"string\"},\"path\":{\"type\":\"string\"}},\"required\":[\"method\",\"path\",\"accessProfile\",\"operation\"],\"type\":\"object\"},\"type\":\"object\"},\"revision\":{\"minimum\":1,\"type\":\"integer\"},\"state\":{\"enum\":[\"draft\",\"submitted\",\"applied\",\"cancelled\",\"rejected\"]},\"status\":{\"enum\":[\"draft\",\"awaiting-party\",\"in-review\",\"approved\",\"processing\",\"applied\",\"rejected\",\"cancelled\"]},\"submissionVersion\":{\"minimum\":0,\"type\":\"integer\"},\"title\":{\"maxLength\":1024,\"type\":\"string\"},\"turn\":{\"enum\":[\"party\",\"official\",\"nobody\"]}},\"required\":[\"id\",\"actionId\",\"actionRevision\",\"submissionVersion\",\"revision\",\"state\",\"turn\",\"links\"],\"type\":\"object\"},\"maxItems\":100,\"type\":\"array\"},\"nextCursor\":{\"type\":\"string\"}},\"required\":[\"items\"],\"type\":\"object\"}")], + ["/paths/~1v1~1proposals/get/responses/200/content/application~1json/schema", JSON.parse("{\"additionalProperties\":false,\"properties\":{\"items\":{\"items\":{\"additionalProperties\":false,\"properties\":{\"actionId\":{\"type\":\"string\"},\"actionRevision\":{\"type\":\"string\"},\"application\":{\"additionalProperties\":false,\"properties\":{\"applicationId\":{\"type\":\"string\"},\"effectDigest\":{\"pattern\":\"^sha256:[0-9a-f]{64}$\",\"type\":\"string\"},\"resultLinks\":{\"items\":{\"additionalProperties\":false,\"properties\":{\"recordId\":{\"type\":\"string\"},\"recordType\":{\"type\":\"string\"},\"revision\":{\"minimum\":1,\"type\":\"integer\"}},\"required\":[\"recordType\",\"recordId\",\"revision\"],\"type\":\"object\"},\"maxItems\":16,\"type\":\"array\"},\"submissionVersion\":{\"minimum\":1,\"type\":\"integer\"}},\"required\":[\"applicationId\",\"submissionVersion\",\"effectDigest\",\"resultLinks\"],\"type\":\"object\"},\"applicationStatus\":{\"additionalProperties\":false,\"properties\":{\"automaticRetry\":{\"additionalProperties\":false,\"properties\":{\"attempts\":{\"maximum\":1000,\"minimum\":0,\"type\":\"integer\"},\"maximumAttempts\":{\"maximum\":1000,\"minimum\":1,\"type\":\"integer\"},\"scheduled\":{\"type\":\"boolean\"}},\"required\":[\"scheduled\",\"attempts\",\"maximumAttempts\"],\"type\":\"object\"},\"mode\":{\"enum\":[\"automatic\",\"manual\"]},\"reason\":{\"enum\":[\"package-changed\",\"dependency-outage\",\"lease-expired\",\"application-refused\",\"attempts-exhausted\"]},\"recovery\":{\"enum\":[\"retry\",\"rebase\",\"revise\",\"correct-input\"]},\"state\":{\"enum\":[\"awaiting-review\",\"pending\",\"applying\",\"blocked\",\"applied\",\"cancelled\",\"rejected\"]}},\"required\":[\"state\",\"mode\"],\"type\":\"object\"},\"asks\":{\"items\":{\"additionalProperties\":false,\"properties\":{\"answer\":{\"additionalProperties\":false,\"properties\":{\"additions\":{\"items\":{\"type\":\"string\"},\"maxItems\":32,\"type\":\"array\",\"uniqueItems\":true},\"answeredAt\":{\"type\":\"string\"},\"formEntries\":{\"items\":{\"type\":\"string\"},\"maxItems\":32,\"type\":\"array\",\"uniqueItems\":true},\"text\":{\"maxLength\":2000,\"minLength\":1,\"type\":\"string\"}},\"required\":[\"additions\",\"answeredAt\"],\"type\":\"object\"},\"askedAt\":{\"type\":\"string\"},\"dueAt\":{\"type\":\"string\"},\"id\":{\"type\":\"string\"},\"links\":{\"additionalProperties\":false,\"properties\":{\"answer\":{\"additionalProperties\":false,\"properties\":{\"accessProfile\":{\"type\":\"string\"},\"availability\":{\"additionalProperties\":false,\"if\":{\"properties\":{\"available\":{\"const\":false}}},\"properties\":{\"available\":{\"type\":\"boolean\"},\"observedRevision\":{\"minimum\":1,\"type\":\"integer\"},\"reason\":{\"enum\":[\"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\":{\"enum\":[\"refresh\",\"revise\",\"retry\",\"rebase\",\"correct-input\",\"receipt-only\"]}},\"required\":[\"available\",\"observedRevision\"],\"then\":{\"required\":[\"reason\",\"recovery\"]},\"type\":\"object\"},\"ifMatch\":{\"type\":\"string\"},\"method\":{\"const\":\"POST\"},\"operation\":{\"const\":\"answer\"},\"path\":{\"type\":\"string\"}},\"required\":[\"method\",\"path\",\"accessProfile\",\"operation\",\"ifMatch\",\"availability\"],\"type\":\"object\"}},\"type\":\"object\"},\"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\",\"links\"],\"type\":\"object\"},\"maxItems\":50,\"type\":\"array\"},\"attachments\":{\"additionalProperties\":{\"additionalProperties\":false,\"properties\":{\"classification\":{\"enum\":[\"public\",\"internal\",\"restricted\"]},\"contentTypes\":{\"items\":{\"type\":\"string\"},\"maxItems\":16,\"minItems\":1,\"type\":\"array\",\"uniqueItems\":true},\"id\":{\"type\":\"string\"},\"links\":{\"additionalProperties\":{\"additionalProperties\":false,\"properties\":{\"accessProfile\":{\"type\":\"string\"},\"availability\":{\"additionalProperties\":false,\"if\":{\"properties\":{\"available\":{\"const\":false}}},\"properties\":{\"available\":{\"type\":\"boolean\"},\"observedRevision\":{\"minimum\":1,\"type\":\"integer\"},\"reason\":{\"enum\":[\"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\":{\"enum\":[\"refresh\",\"revise\",\"retry\",\"rebase\",\"correct-input\",\"receipt-only\"]}},\"required\":[\"available\",\"observedRevision\"],\"then\":{\"required\":[\"reason\",\"recovery\"]},\"type\":\"object\"},\"ifMatch\":{\"type\":\"string\"},\"method\":{\"enum\":[\"GET\",\"PATCH\",\"DELETE\"]},\"operation\":{\"enum\":[\"download\",\"upload\",\"remove\"]},\"path\":{\"type\":\"string\"}},\"required\":[\"method\",\"path\",\"accessProfile\",\"operation\"],\"type\":\"object\"},\"type\":\"object\"},\"maximumBytes\":{\"maximum\":16777216,\"minimum\":1,\"type\":\"integer\"},\"required\":{\"type\":\"boolean\"},\"value\":{\"additionalProperties\":false,\"properties\":{\"byteSize\":{\"minimum\":1,\"type\":\"integer\"},\"contentType\":{\"type\":\"string\"},\"sha256\":{\"pattern\":\"^[a-f0-9]{64}$\",\"type\":\"string\"},\"submissionVersion\":{\"minimum\":0,\"type\":\"integer\"},\"uploadedAt\":{\"type\":\"string\"},\"verificationStatus\":{\"enum\":[\"notRequired\",\"pending\",\"approved\",\"rejected\"]}},\"required\":[\"submissionVersion\",\"sha256\",\"contentType\",\"byteSize\",\"verificationStatus\"],\"type\":\"object\"}},\"required\":[\"id\",\"required\",\"maximumBytes\",\"contentTypes\",\"classification\",\"links\"],\"type\":\"object\"},\"maxProperties\":8,\"type\":\"object\"},\"blockedReason\":{\"enum\":[\"package-changed\"]},\"createdAt\":{\"type\":\"string\"},\"decision\":{\"additionalProperties\":false,\"properties\":{\"decidedAt\":{\"type\":\"string\"},\"publicReason\":{\"minLength\":1,\"pattern\":\"^[^\\\\u0000-\\\\u001F\\\\u007F-\\\\u009F]*[^\\\\u0000-\\\\u0020\\\\u007F-\\\\u00A0\\\\u1680\\\\u2000-\\\\u200A\\\\u2028\\\\u2029\\\\u202F\\\\u205F\\\\u3000][^\\\\u0000-\\\\u001F\\\\u007F-\\\\u009F]*$\",\"type\":\"string\"},\"status\":{\"enum\":[\"approved\",\"rejected\",\"changes-requested\",\"answered\"]}},\"required\":[\"status\",\"decidedAt\"],\"type\":\"object\"},\"effectDigest\":{\"type\":\"string\"},\"handoffRefusal\":{\"additionalProperties\":false,\"properties\":{\"code\":{\"enum\":[\"review.initiator-required\",\"review.initiator-excluded\",\"review.policy-mismatch\",\"review.refused\"]}},\"required\":[\"code\"],\"type\":\"object\"},\"id\":{\"type\":\"string\"},\"input\":{\"type\":\"object\"},\"links\":{\"additionalProperties\":{\"additionalProperties\":false,\"properties\":{\"accessProfile\":{\"type\":\"string\"},\"availability\":{\"additionalProperties\":false,\"if\":{\"properties\":{\"available\":{\"const\":false}}},\"properties\":{\"available\":{\"type\":\"boolean\"},\"observedRevision\":{\"minimum\":1,\"type\":\"integer\"},\"reason\":{\"enum\":[\"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\":{\"enum\":[\"refresh\",\"revise\",\"retry\",\"rebase\",\"correct-input\",\"receipt-only\"]}},\"required\":[\"available\",\"observedRevision\"],\"then\":{\"required\":[\"reason\",\"recovery\"]},\"type\":\"object\"},\"ifMatch\":{\"type\":\"string\"},\"method\":{\"enum\":[\"GET\",\"POST\"]},\"operation\":{\"type\":\"string\"},\"path\":{\"type\":\"string\"}},\"required\":[\"method\",\"path\",\"accessProfile\",\"operation\"],\"type\":\"object\"},\"type\":\"object\"},\"partyRole\":{\"enum\":[\"owner\",\"subject\"]},\"revision\":{\"minimum\":1,\"type\":\"integer\"},\"state\":{\"enum\":[\"draft\",\"submitted\",\"applied\",\"cancelled\",\"rejected\"]},\"status\":{\"enum\":[\"draft\",\"awaiting-party\",\"in-review\",\"approved\",\"processing\",\"applied\",\"rejected\",\"cancelled\"]},\"submissionVersion\":{\"minimum\":0,\"type\":\"integer\"},\"title\":{\"maxLength\":1024,\"type\":\"string\"},\"turn\":{\"enum\":[\"party\",\"official\",\"nobody\"]}},\"required\":[\"id\",\"actionId\",\"actionRevision\",\"submissionVersion\",\"revision\",\"state\",\"turn\",\"links\"],\"type\":\"object\"},\"maxItems\":100,\"type\":\"array\"},\"nextCursor\":{\"type\":\"string\"}},\"required\":[\"items\"],\"type\":\"object\"}")], ["/paths/~1v1~1proposals/get/responses/400/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"access-profile.ambiguous\",\"query.invalid\"]}},\"type\":\"object\"}]}")], ["/paths/~1v1~1proposals/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/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/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~1{proposal_id}/get/responses/200/content/application~1json/schema", JSON.parse("{\"additionalProperties\":false,\"properties\":{\"actionId\":{\"type\":\"string\"},\"actionRevision\":{\"type\":\"string\"},\"application\":{\"additionalProperties\":false,\"dependentRequired\":{\"appliedAt\":[\"appliedBy\"],\"appliedBy\":[\"appliedAt\"]},\"properties\":{\"applicationId\":{\"type\":\"string\"},\"appliedAt\":{\"type\":\"string\"},\"appliedBy\":{\"pattern\":\"^hmac-sha256:[0-9a-f]{64}$\",\"type\":\"string\"},\"effectDigest\":{\"pattern\":\"^sha256:[0-9a-f]{64}$\",\"type\":\"string\"},\"resultLinks\":{\"items\":{\"additionalProperties\":false,\"properties\":{\"recordId\":{\"type\":\"string\"},\"recordType\":{\"type\":\"string\"},\"revision\":{\"minimum\":1,\"type\":\"integer\"}},\"required\":[\"recordType\",\"recordId\",\"revision\"],\"type\":\"object\"},\"maxItems\":16,\"type\":\"array\"},\"submissionVersion\":{\"minimum\":1,\"type\":\"integer\"}},\"required\":[\"applicationId\",\"submissionVersion\",\"effectDigest\",\"resultLinks\"],\"type\":\"object\"},\"applicationStatus\":{\"additionalProperties\":false,\"properties\":{\"automaticRetry\":{\"additionalProperties\":false,\"properties\":{\"attempts\":{\"maximum\":1000,\"minimum\":0,\"type\":\"integer\"},\"maximumAttempts\":{\"maximum\":1000,\"minimum\":1,\"type\":\"integer\"},\"scheduled\":{\"type\":\"boolean\"}},\"required\":[\"scheduled\",\"attempts\",\"maximumAttempts\"],\"type\":\"object\"},\"mode\":{\"enum\":[\"automatic\",\"manual\"]},\"reason\":{\"enum\":[\"package-changed\",\"dependency-outage\",\"lease-expired\",\"application-refused\",\"attempts-exhausted\"]},\"recovery\":{\"enum\":[\"retry\",\"rebase\",\"revise\",\"correct-input\"]},\"state\":{\"enum\":[\"awaiting-review\",\"pending\",\"applying\",\"blocked\",\"applied\",\"cancelled\",\"rejected\"]}},\"required\":[\"state\",\"mode\"],\"type\":\"object\"},\"asks\":{\"items\":{\"additionalProperties\":false,\"properties\":{\"answer\":{\"additionalProperties\":false,\"properties\":{\"additions\":{\"items\":{\"type\":\"string\"},\"maxItems\":32,\"type\":\"array\",\"uniqueItems\":true},\"answeredAt\":{\"type\":\"string\"},\"text\":{\"maxLength\":2000,\"minLength\":1,\"type\":\"string\"}},\"required\":[\"additions\",\"answeredAt\"],\"type\":\"object\"},\"askedAt\":{\"type\":\"string\"},\"dueAt\":{\"type\":\"string\"},\"id\":{\"type\":\"string\"},\"links\":{\"additionalProperties\":false,\"properties\":{\"answer\":{\"additionalProperties\":false,\"properties\":{\"accessProfile\":{\"type\":\"string\"},\"availability\":{\"additionalProperties\":false,\"if\":{\"properties\":{\"available\":{\"const\":false}}},\"properties\":{\"available\":{\"type\":\"boolean\"},\"observedRevision\":{\"minimum\":1,\"type\":\"integer\"},\"reason\":{\"enum\":[\"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\":{\"enum\":[\"refresh\",\"revise\",\"retry\",\"rebase\",\"correct-input\",\"receipt-only\"]}},\"required\":[\"available\",\"observedRevision\"],\"then\":{\"required\":[\"reason\",\"recovery\"]},\"type\":\"object\"},\"ifMatch\":{\"type\":\"string\"},\"method\":{\"const\":\"POST\"},\"operation\":{\"const\":\"answer\"},\"path\":{\"type\":\"string\"}},\"required\":[\"method\",\"path\",\"accessProfile\",\"operation\",\"ifMatch\",\"availability\"],\"type\":\"object\"}},\"type\":\"object\"},\"state\":{\"enum\":[\"open\",\"answered\",\"expired\",\"closed\"]},\"text\":{\"maxLength\":2000,\"minLength\":1,\"type\":\"string\"},\"wants\":{\"items\":{\"additionalProperties\":false,\"properties\":{\"kind\":{\"enum\":[\"answer\",\"document\"]}},\"required\":[\"kind\"],\"type\":\"object\"},\"maxItems\":8,\"type\":\"array\",\"uniqueItems\":true}},\"required\":[\"id\",\"text\",\"wants\",\"askedAt\",\"state\",\"links\"],\"type\":\"object\"},\"maxItems\":50,\"type\":\"array\"},\"attachments\":{\"additionalProperties\":{\"additionalProperties\":false,\"properties\":{\"classification\":{\"enum\":[\"public\",\"internal\",\"restricted\"]},\"contentTypes\":{\"items\":{\"type\":\"string\"},\"maxItems\":16,\"minItems\":1,\"type\":\"array\",\"uniqueItems\":true},\"id\":{\"type\":\"string\"},\"links\":{\"additionalProperties\":{\"additionalProperties\":false,\"properties\":{\"accessProfile\":{\"type\":\"string\"},\"availability\":{\"additionalProperties\":false,\"if\":{\"properties\":{\"available\":{\"const\":false}}},\"properties\":{\"available\":{\"type\":\"boolean\"},\"observedRevision\":{\"minimum\":1,\"type\":\"integer\"},\"reason\":{\"enum\":[\"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\":{\"enum\":[\"refresh\",\"revise\",\"retry\",\"rebase\",\"correct-input\",\"receipt-only\"]}},\"required\":[\"available\",\"observedRevision\"],\"then\":{\"required\":[\"reason\",\"recovery\"]},\"type\":\"object\"},\"ifMatch\":{\"type\":\"string\"},\"method\":{\"enum\":[\"GET\",\"PATCH\",\"DELETE\"]},\"operation\":{\"enum\":[\"download\",\"upload\",\"remove\"]},\"path\":{\"type\":\"string\"}},\"required\":[\"method\",\"path\",\"accessProfile\",\"operation\"],\"type\":\"object\"},\"type\":\"object\"},\"maximumBytes\":{\"maximum\":16777216,\"minimum\":1,\"type\":\"integer\"},\"required\":{\"type\":\"boolean\"},\"value\":{\"additionalProperties\":false,\"properties\":{\"byteSize\":{\"minimum\":1,\"type\":\"integer\"},\"contentType\":{\"type\":\"string\"},\"sha256\":{\"pattern\":\"^[a-f0-9]{64}$\",\"type\":\"string\"},\"submissionVersion\":{\"minimum\":0,\"type\":\"integer\"},\"uploadedAt\":{\"type\":\"string\"},\"verificationStatus\":{\"enum\":[\"notRequired\",\"pending\",\"approved\",\"rejected\"]}},\"required\":[\"submissionVersion\",\"sha256\",\"contentType\",\"byteSize\",\"verificationStatus\"],\"type\":\"object\"}},\"required\":[\"id\",\"required\",\"maximumBytes\",\"contentTypes\",\"classification\",\"links\"],\"type\":\"object\"},\"maxProperties\":8,\"type\":\"object\"},\"blockedReason\":{\"enum\":[\"package-changed\"]},\"createdAt\":{\"type\":\"string\"},\"decision\":{\"additionalProperties\":false,\"properties\":{\"decidedAt\":{\"type\":\"string\"},\"publicReason\":{\"minLength\":1,\"pattern\":\"^[^\\\\u0000-\\\\u001F\\\\u007F-\\\\u009F]*[^\\\\u0000-\\\\u0020\\\\u007F-\\\\u00A0\\\\u1680\\\\u2000-\\\\u200A\\\\u2028\\\\u2029\\\\u202F\\\\u205F\\\\u3000][^\\\\u0000-\\\\u001F\\\\u007F-\\\\u009F]*$\",\"type\":\"string\"},\"status\":{\"enum\":[\"approved\",\"rejected\",\"changes-requested\",\"answered\"]}},\"required\":[\"status\",\"decidedAt\"],\"type\":\"object\"},\"effectDigest\":{\"type\":\"string\"},\"handoffRefusal\":{\"additionalProperties\":false,\"properties\":{\"code\":{\"enum\":[\"review.initiator-required\",\"review.initiator-excluded\",\"review.policy-mismatch\",\"review.refused\"]}},\"required\":[\"code\"],\"type\":\"object\"},\"id\":{\"type\":\"string\"},\"input\":{\"type\":\"object\"},\"links\":{\"additionalProperties\":{\"additionalProperties\":false,\"properties\":{\"accessProfile\":{\"type\":\"string\"},\"availability\":{\"additionalProperties\":false,\"if\":{\"properties\":{\"available\":{\"const\":false}}},\"properties\":{\"available\":{\"type\":\"boolean\"},\"observedRevision\":{\"minimum\":1,\"type\":\"integer\"},\"reason\":{\"enum\":[\"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\":{\"enum\":[\"refresh\",\"revise\",\"retry\",\"rebase\",\"correct-input\",\"receipt-only\"]}},\"required\":[\"available\",\"observedRevision\"],\"then\":{\"required\":[\"reason\",\"recovery\"]},\"type\":\"object\"},\"ifMatch\":{\"type\":\"string\"},\"method\":{\"enum\":[\"GET\",\"POST\"]},\"operation\":{\"type\":\"string\"},\"path\":{\"type\":\"string\"}},\"required\":[\"method\",\"path\",\"accessProfile\",\"operation\"],\"type\":\"object\"},\"type\":\"object\"},\"revision\":{\"minimum\":1,\"type\":\"integer\"},\"state\":{\"enum\":[\"draft\",\"submitted\",\"applied\",\"cancelled\",\"rejected\"]},\"status\":{\"enum\":[\"draft\",\"awaiting-party\",\"in-review\",\"approved\",\"processing\",\"applied\",\"rejected\",\"cancelled\"]},\"submissionVersion\":{\"minimum\":0,\"type\":\"integer\"},\"title\":{\"maxLength\":1024,\"type\":\"string\"},\"turn\":{\"enum\":[\"party\",\"official\",\"nobody\"]}},\"required\":[\"id\",\"actionId\",\"actionRevision\",\"submissionVersion\",\"revision\",\"state\",\"turn\",\"links\"],\"type\":\"object\"}")], + ["/paths/~1v1~1proposals~1{proposal_id}/get/responses/200/content/application~1json/schema", JSON.parse("{\"additionalProperties\":false,\"properties\":{\"actionId\":{\"type\":\"string\"},\"actionRevision\":{\"type\":\"string\"},\"application\":{\"additionalProperties\":false,\"dependentRequired\":{\"appliedAt\":[\"appliedBy\"],\"appliedBy\":[\"appliedAt\"]},\"properties\":{\"applicationId\":{\"type\":\"string\"},\"appliedAt\":{\"type\":\"string\"},\"appliedBy\":{\"pattern\":\"^hmac-sha256:[0-9a-f]{64}$\",\"type\":\"string\"},\"effectDigest\":{\"pattern\":\"^sha256:[0-9a-f]{64}$\",\"type\":\"string\"},\"resultLinks\":{\"items\":{\"additionalProperties\":false,\"properties\":{\"recordId\":{\"type\":\"string\"},\"recordType\":{\"type\":\"string\"},\"revision\":{\"minimum\":1,\"type\":\"integer\"}},\"required\":[\"recordType\",\"recordId\",\"revision\"],\"type\":\"object\"},\"maxItems\":16,\"type\":\"array\"},\"submissionVersion\":{\"minimum\":1,\"type\":\"integer\"}},\"required\":[\"applicationId\",\"submissionVersion\",\"effectDigest\",\"resultLinks\"],\"type\":\"object\"},\"applicationStatus\":{\"additionalProperties\":false,\"properties\":{\"automaticRetry\":{\"additionalProperties\":false,\"properties\":{\"attempts\":{\"maximum\":1000,\"minimum\":0,\"type\":\"integer\"},\"maximumAttempts\":{\"maximum\":1000,\"minimum\":1,\"type\":\"integer\"},\"scheduled\":{\"type\":\"boolean\"}},\"required\":[\"scheduled\",\"attempts\",\"maximumAttempts\"],\"type\":\"object\"},\"mode\":{\"enum\":[\"automatic\",\"manual\"]},\"reason\":{\"enum\":[\"package-changed\",\"dependency-outage\",\"lease-expired\",\"application-refused\",\"attempts-exhausted\"]},\"recovery\":{\"enum\":[\"retry\",\"rebase\",\"revise\",\"correct-input\"]},\"state\":{\"enum\":[\"awaiting-review\",\"pending\",\"applying\",\"blocked\",\"applied\",\"cancelled\",\"rejected\"]}},\"required\":[\"state\",\"mode\"],\"type\":\"object\"},\"asks\":{\"items\":{\"additionalProperties\":false,\"properties\":{\"answer\":{\"additionalProperties\":false,\"properties\":{\"additions\":{\"items\":{\"type\":\"string\"},\"maxItems\":32,\"type\":\"array\",\"uniqueItems\":true},\"answeredAt\":{\"type\":\"string\"},\"formEntries\":{\"items\":{\"type\":\"string\"},\"maxItems\":32,\"type\":\"array\",\"uniqueItems\":true},\"text\":{\"maxLength\":2000,\"minLength\":1,\"type\":\"string\"}},\"required\":[\"additions\",\"answeredAt\"],\"type\":\"object\"},\"askedAt\":{\"type\":\"string\"},\"dueAt\":{\"type\":\"string\"},\"id\":{\"type\":\"string\"},\"links\":{\"additionalProperties\":false,\"properties\":{\"answer\":{\"additionalProperties\":false,\"properties\":{\"accessProfile\":{\"type\":\"string\"},\"availability\":{\"additionalProperties\":false,\"if\":{\"properties\":{\"available\":{\"const\":false}}},\"properties\":{\"available\":{\"type\":\"boolean\"},\"observedRevision\":{\"minimum\":1,\"type\":\"integer\"},\"reason\":{\"enum\":[\"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\":{\"enum\":[\"refresh\",\"revise\",\"retry\",\"rebase\",\"correct-input\",\"receipt-only\"]}},\"required\":[\"available\",\"observedRevision\"],\"then\":{\"required\":[\"reason\",\"recovery\"]},\"type\":\"object\"},\"ifMatch\":{\"type\":\"string\"},\"method\":{\"const\":\"POST\"},\"operation\":{\"const\":\"answer\"},\"path\":{\"type\":\"string\"}},\"required\":[\"method\",\"path\",\"accessProfile\",\"operation\",\"ifMatch\",\"availability\"],\"type\":\"object\"}},\"type\":\"object\"},\"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\",\"links\"],\"type\":\"object\"},\"maxItems\":50,\"type\":\"array\"},\"attachments\":{\"additionalProperties\":{\"additionalProperties\":false,\"properties\":{\"classification\":{\"enum\":[\"public\",\"internal\",\"restricted\"]},\"contentTypes\":{\"items\":{\"type\":\"string\"},\"maxItems\":16,\"minItems\":1,\"type\":\"array\",\"uniqueItems\":true},\"id\":{\"type\":\"string\"},\"links\":{\"additionalProperties\":{\"additionalProperties\":false,\"properties\":{\"accessProfile\":{\"type\":\"string\"},\"availability\":{\"additionalProperties\":false,\"if\":{\"properties\":{\"available\":{\"const\":false}}},\"properties\":{\"available\":{\"type\":\"boolean\"},\"observedRevision\":{\"minimum\":1,\"type\":\"integer\"},\"reason\":{\"enum\":[\"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\":{\"enum\":[\"refresh\",\"revise\",\"retry\",\"rebase\",\"correct-input\",\"receipt-only\"]}},\"required\":[\"available\",\"observedRevision\"],\"then\":{\"required\":[\"reason\",\"recovery\"]},\"type\":\"object\"},\"ifMatch\":{\"type\":\"string\"},\"method\":{\"enum\":[\"GET\",\"PATCH\",\"DELETE\"]},\"operation\":{\"enum\":[\"download\",\"upload\",\"remove\"]},\"path\":{\"type\":\"string\"}},\"required\":[\"method\",\"path\",\"accessProfile\",\"operation\"],\"type\":\"object\"},\"type\":\"object\"},\"maximumBytes\":{\"maximum\":16777216,\"minimum\":1,\"type\":\"integer\"},\"required\":{\"type\":\"boolean\"},\"value\":{\"additionalProperties\":false,\"properties\":{\"byteSize\":{\"minimum\":1,\"type\":\"integer\"},\"contentType\":{\"type\":\"string\"},\"sha256\":{\"pattern\":\"^[a-f0-9]{64}$\",\"type\":\"string\"},\"submissionVersion\":{\"minimum\":0,\"type\":\"integer\"},\"uploadedAt\":{\"type\":\"string\"},\"verificationStatus\":{\"enum\":[\"notRequired\",\"pending\",\"approved\",\"rejected\"]}},\"required\":[\"submissionVersion\",\"sha256\",\"contentType\",\"byteSize\",\"verificationStatus\"],\"type\":\"object\"}},\"required\":[\"id\",\"required\",\"maximumBytes\",\"contentTypes\",\"classification\",\"links\"],\"type\":\"object\"},\"maxProperties\":8,\"type\":\"object\"},\"blockedReason\":{\"enum\":[\"package-changed\"]},\"createdAt\":{\"type\":\"string\"},\"decision\":{\"additionalProperties\":false,\"properties\":{\"decidedAt\":{\"type\":\"string\"},\"publicReason\":{\"minLength\":1,\"pattern\":\"^[^\\\\u0000-\\\\u001F\\\\u007F-\\\\u009F]*[^\\\\u0000-\\\\u0020\\\\u007F-\\\\u00A0\\\\u1680\\\\u2000-\\\\u200A\\\\u2028\\\\u2029\\\\u202F\\\\u205F\\\\u3000][^\\\\u0000-\\\\u001F\\\\u007F-\\\\u009F]*$\",\"type\":\"string\"},\"status\":{\"enum\":[\"approved\",\"rejected\",\"changes-requested\",\"answered\"]}},\"required\":[\"status\",\"decidedAt\"],\"type\":\"object\"},\"effectDigest\":{\"type\":\"string\"},\"handoffRefusal\":{\"additionalProperties\":false,\"properties\":{\"code\":{\"enum\":[\"review.initiator-required\",\"review.initiator-excluded\",\"review.policy-mismatch\",\"review.refused\"]}},\"required\":[\"code\"],\"type\":\"object\"},\"id\":{\"type\":\"string\"},\"input\":{\"type\":\"object\"},\"links\":{\"additionalProperties\":{\"additionalProperties\":false,\"properties\":{\"accessProfile\":{\"type\":\"string\"},\"availability\":{\"additionalProperties\":false,\"if\":{\"properties\":{\"available\":{\"const\":false}}},\"properties\":{\"available\":{\"type\":\"boolean\"},\"observedRevision\":{\"minimum\":1,\"type\":\"integer\"},\"reason\":{\"enum\":[\"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\":{\"enum\":[\"refresh\",\"revise\",\"retry\",\"rebase\",\"correct-input\",\"receipt-only\"]}},\"required\":[\"available\",\"observedRevision\"],\"then\":{\"required\":[\"reason\",\"recovery\"]},\"type\":\"object\"},\"ifMatch\":{\"type\":\"string\"},\"method\":{\"enum\":[\"GET\",\"POST\"]},\"operation\":{\"type\":\"string\"},\"path\":{\"type\":\"string\"}},\"required\":[\"method\",\"path\",\"accessProfile\",\"operation\"],\"type\":\"object\"},\"type\":\"object\"},\"partyRole\":{\"enum\":[\"owner\",\"subject\"]},\"revision\":{\"minimum\":1,\"type\":\"integer\"},\"state\":{\"enum\":[\"draft\",\"submitted\",\"applied\",\"cancelled\",\"rejected\"]},\"status\":{\"enum\":[\"draft\",\"awaiting-party\",\"in-review\",\"approved\",\"processing\",\"applied\",\"rejected\",\"cancelled\"]},\"submissionVersion\":{\"minimum\":0,\"type\":\"integer\"},\"title\":{\"maxLength\":1024,\"type\":\"string\"},\"turn\":{\"enum\":[\"party\",\"official\",\"nobody\"]}},\"required\":[\"id\",\"actionId\",\"actionRevision\",\"submissionVersion\",\"revision\",\"state\",\"turn\",\"links\"],\"type\":\"object\"}")], ["/paths/~1v1~1proposals~1{proposal_id}/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}/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}/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}/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}/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}/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}~1cancel/post/responses/200/content/application~1json/schema", JSON.parse("{\"additionalProperties\":false,\"properties\":{\"actionId\":{\"type\":\"string\"},\"actionRevision\":{\"type\":\"string\"},\"application\":{\"additionalProperties\":false,\"properties\":{\"applicationId\":{\"type\":\"string\"},\"effectDigest\":{\"pattern\":\"^sha256:[0-9a-f]{64}$\",\"type\":\"string\"},\"resultLinks\":{\"items\":{\"additionalProperties\":false,\"properties\":{\"recordId\":{\"type\":\"string\"},\"recordType\":{\"type\":\"string\"},\"revision\":{\"minimum\":1,\"type\":\"integer\"}},\"required\":[\"recordType\",\"recordId\",\"revision\"],\"type\":\"object\"},\"maxItems\":16,\"type\":\"array\"},\"submissionVersion\":{\"minimum\":1,\"type\":\"integer\"}},\"required\":[\"applicationId\",\"submissionVersion\",\"effectDigest\",\"resultLinks\"],\"type\":\"object\"},\"applicationStatus\":{\"additionalProperties\":false,\"properties\":{\"automaticRetry\":{\"additionalProperties\":false,\"properties\":{\"attempts\":{\"maximum\":1000,\"minimum\":0,\"type\":\"integer\"},\"maximumAttempts\":{\"maximum\":1000,\"minimum\":1,\"type\":\"integer\"},\"scheduled\":{\"type\":\"boolean\"}},\"required\":[\"scheduled\",\"attempts\",\"maximumAttempts\"],\"type\":\"object\"},\"mode\":{\"enum\":[\"automatic\",\"manual\"]},\"reason\":{\"enum\":[\"package-changed\",\"dependency-outage\",\"lease-expired\",\"application-refused\",\"attempts-exhausted\"]},\"recovery\":{\"enum\":[\"retry\",\"rebase\",\"revise\",\"correct-input\"]},\"state\":{\"enum\":[\"awaiting-review\",\"pending\",\"applying\",\"blocked\",\"applied\",\"cancelled\",\"rejected\"]}},\"required\":[\"state\",\"mode\"],\"type\":\"object\"},\"asks\":{\"items\":{\"additionalProperties\":false,\"properties\":{\"answer\":{\"additionalProperties\":false,\"properties\":{\"additions\":{\"items\":{\"type\":\"string\"},\"maxItems\":32,\"type\":\"array\",\"uniqueItems\":true},\"answeredAt\":{\"type\":\"string\"},\"text\":{\"maxLength\":2000,\"minLength\":1,\"type\":\"string\"}},\"required\":[\"additions\",\"answeredAt\"],\"type\":\"object\"},\"askedAt\":{\"type\":\"string\"},\"dueAt\":{\"type\":\"string\"},\"id\":{\"type\":\"string\"},\"links\":{\"additionalProperties\":false,\"properties\":{\"answer\":{\"additionalProperties\":false,\"properties\":{\"accessProfile\":{\"type\":\"string\"},\"availability\":{\"additionalProperties\":false,\"if\":{\"properties\":{\"available\":{\"const\":false}}},\"properties\":{\"available\":{\"type\":\"boolean\"},\"observedRevision\":{\"minimum\":1,\"type\":\"integer\"},\"reason\":{\"enum\":[\"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\":{\"enum\":[\"refresh\",\"revise\",\"retry\",\"rebase\",\"correct-input\",\"receipt-only\"]}},\"required\":[\"available\",\"observedRevision\"],\"then\":{\"required\":[\"reason\",\"recovery\"]},\"type\":\"object\"},\"ifMatch\":{\"type\":\"string\"},\"method\":{\"const\":\"POST\"},\"operation\":{\"const\":\"answer\"},\"path\":{\"type\":\"string\"}},\"required\":[\"method\",\"path\",\"accessProfile\",\"operation\",\"ifMatch\",\"availability\"],\"type\":\"object\"}},\"type\":\"object\"},\"state\":{\"enum\":[\"open\",\"answered\",\"expired\",\"closed\"]},\"text\":{\"maxLength\":2000,\"minLength\":1,\"type\":\"string\"},\"wants\":{\"items\":{\"additionalProperties\":false,\"properties\":{\"kind\":{\"enum\":[\"answer\",\"document\"]}},\"required\":[\"kind\"],\"type\":\"object\"},\"maxItems\":8,\"type\":\"array\",\"uniqueItems\":true}},\"required\":[\"id\",\"text\",\"wants\",\"askedAt\",\"state\",\"links\"],\"type\":\"object\"},\"maxItems\":50,\"type\":\"array\"},\"attachments\":{\"additionalProperties\":{\"additionalProperties\":false,\"properties\":{\"classification\":{\"enum\":[\"public\",\"internal\",\"restricted\"]},\"contentTypes\":{\"items\":{\"type\":\"string\"},\"maxItems\":16,\"minItems\":1,\"type\":\"array\",\"uniqueItems\":true},\"id\":{\"type\":\"string\"},\"links\":{\"additionalProperties\":{\"additionalProperties\":false,\"properties\":{\"accessProfile\":{\"type\":\"string\"},\"availability\":{\"additionalProperties\":false,\"if\":{\"properties\":{\"available\":{\"const\":false}}},\"properties\":{\"available\":{\"type\":\"boolean\"},\"observedRevision\":{\"minimum\":1,\"type\":\"integer\"},\"reason\":{\"enum\":[\"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\":{\"enum\":[\"refresh\",\"revise\",\"retry\",\"rebase\",\"correct-input\",\"receipt-only\"]}},\"required\":[\"available\",\"observedRevision\"],\"then\":{\"required\":[\"reason\",\"recovery\"]},\"type\":\"object\"},\"ifMatch\":{\"type\":\"string\"},\"method\":{\"enum\":[\"GET\",\"PATCH\",\"DELETE\"]},\"operation\":{\"enum\":[\"download\",\"upload\",\"remove\"]},\"path\":{\"type\":\"string\"}},\"required\":[\"method\",\"path\",\"accessProfile\",\"operation\"],\"type\":\"object\"},\"type\":\"object\"},\"maximumBytes\":{\"maximum\":16777216,\"minimum\":1,\"type\":\"integer\"},\"required\":{\"type\":\"boolean\"},\"value\":{\"additionalProperties\":false,\"properties\":{\"byteSize\":{\"minimum\":1,\"type\":\"integer\"},\"contentType\":{\"type\":\"string\"},\"sha256\":{\"pattern\":\"^[a-f0-9]{64}$\",\"type\":\"string\"},\"submissionVersion\":{\"minimum\":0,\"type\":\"integer\"},\"uploadedAt\":{\"type\":\"string\"},\"verificationStatus\":{\"enum\":[\"notRequired\",\"pending\",\"approved\",\"rejected\"]}},\"required\":[\"submissionVersion\",\"sha256\",\"contentType\",\"byteSize\",\"verificationStatus\"],\"type\":\"object\"}},\"required\":[\"id\",\"required\",\"maximumBytes\",\"contentTypes\",\"classification\",\"links\"],\"type\":\"object\"},\"maxProperties\":8,\"type\":\"object\"},\"blockedReason\":{\"enum\":[\"package-changed\"]},\"createdAt\":{\"type\":\"string\"},\"decision\":{\"additionalProperties\":false,\"properties\":{\"decidedAt\":{\"type\":\"string\"},\"publicReason\":{\"minLength\":1,\"pattern\":\"^[^\\\\u0000-\\\\u001F\\\\u007F-\\\\u009F]*[^\\\\u0000-\\\\u0020\\\\u007F-\\\\u00A0\\\\u1680\\\\u2000-\\\\u200A\\\\u2028\\\\u2029\\\\u202F\\\\u205F\\\\u3000][^\\\\u0000-\\\\u001F\\\\u007F-\\\\u009F]*$\",\"type\":\"string\"},\"status\":{\"enum\":[\"approved\",\"rejected\",\"changes-requested\",\"answered\"]}},\"required\":[\"status\",\"decidedAt\"],\"type\":\"object\"},\"effectDigest\":{\"type\":\"string\"},\"handoffRefusal\":{\"additionalProperties\":false,\"properties\":{\"code\":{\"enum\":[\"review.initiator-required\",\"review.initiator-excluded\",\"review.policy-mismatch\",\"review.refused\"]}},\"required\":[\"code\"],\"type\":\"object\"},\"id\":{\"type\":\"string\"},\"input\":{\"type\":\"object\"},\"links\":{\"additionalProperties\":{\"additionalProperties\":false,\"properties\":{\"accessProfile\":{\"type\":\"string\"},\"availability\":{\"additionalProperties\":false,\"if\":{\"properties\":{\"available\":{\"const\":false}}},\"properties\":{\"available\":{\"type\":\"boolean\"},\"observedRevision\":{\"minimum\":1,\"type\":\"integer\"},\"reason\":{\"enum\":[\"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\":{\"enum\":[\"refresh\",\"revise\",\"retry\",\"rebase\",\"correct-input\",\"receipt-only\"]}},\"required\":[\"available\",\"observedRevision\"],\"then\":{\"required\":[\"reason\",\"recovery\"]},\"type\":\"object\"},\"ifMatch\":{\"type\":\"string\"},\"method\":{\"enum\":[\"GET\",\"POST\"]},\"operation\":{\"type\":\"string\"},\"path\":{\"type\":\"string\"}},\"required\":[\"method\",\"path\",\"accessProfile\",\"operation\"],\"type\":\"object\"},\"type\":\"object\"},\"revision\":{\"minimum\":1,\"type\":\"integer\"},\"state\":{\"enum\":[\"draft\",\"submitted\",\"applied\",\"cancelled\",\"rejected\"]},\"status\":{\"enum\":[\"draft\",\"awaiting-party\",\"in-review\",\"approved\",\"processing\",\"applied\",\"rejected\",\"cancelled\"]},\"submissionVersion\":{\"minimum\":0,\"type\":\"integer\"},\"title\":{\"maxLength\":1024,\"type\":\"string\"},\"turn\":{\"enum\":[\"party\",\"official\",\"nobody\"]}},\"required\":[\"id\",\"actionId\",\"actionRevision\",\"submissionVersion\",\"revision\",\"state\",\"turn\",\"links\"],\"type\":\"object\"}")], + ["/paths/~1v1~1proposals~1{proposal_id}~1cancel/post/responses/200/content/application~1json/schema", JSON.parse("{\"additionalProperties\":false,\"properties\":{\"actionId\":{\"type\":\"string\"},\"actionRevision\":{\"type\":\"string\"},\"application\":{\"additionalProperties\":false,\"properties\":{\"applicationId\":{\"type\":\"string\"},\"effectDigest\":{\"pattern\":\"^sha256:[0-9a-f]{64}$\",\"type\":\"string\"},\"resultLinks\":{\"items\":{\"additionalProperties\":false,\"properties\":{\"recordId\":{\"type\":\"string\"},\"recordType\":{\"type\":\"string\"},\"revision\":{\"minimum\":1,\"type\":\"integer\"}},\"required\":[\"recordType\",\"recordId\",\"revision\"],\"type\":\"object\"},\"maxItems\":16,\"type\":\"array\"},\"submissionVersion\":{\"minimum\":1,\"type\":\"integer\"}},\"required\":[\"applicationId\",\"submissionVersion\",\"effectDigest\",\"resultLinks\"],\"type\":\"object\"},\"applicationStatus\":{\"additionalProperties\":false,\"properties\":{\"automaticRetry\":{\"additionalProperties\":false,\"properties\":{\"attempts\":{\"maximum\":1000,\"minimum\":0,\"type\":\"integer\"},\"maximumAttempts\":{\"maximum\":1000,\"minimum\":1,\"type\":\"integer\"},\"scheduled\":{\"type\":\"boolean\"}},\"required\":[\"scheduled\",\"attempts\",\"maximumAttempts\"],\"type\":\"object\"},\"mode\":{\"enum\":[\"automatic\",\"manual\"]},\"reason\":{\"enum\":[\"package-changed\",\"dependency-outage\",\"lease-expired\",\"application-refused\",\"attempts-exhausted\"]},\"recovery\":{\"enum\":[\"retry\",\"rebase\",\"revise\",\"correct-input\"]},\"state\":{\"enum\":[\"awaiting-review\",\"pending\",\"applying\",\"blocked\",\"applied\",\"cancelled\",\"rejected\"]}},\"required\":[\"state\",\"mode\"],\"type\":\"object\"},\"asks\":{\"items\":{\"additionalProperties\":false,\"properties\":{\"answer\":{\"additionalProperties\":false,\"properties\":{\"additions\":{\"items\":{\"type\":\"string\"},\"maxItems\":32,\"type\":\"array\",\"uniqueItems\":true},\"answeredAt\":{\"type\":\"string\"},\"formEntries\":{\"items\":{\"type\":\"string\"},\"maxItems\":32,\"type\":\"array\",\"uniqueItems\":true},\"text\":{\"maxLength\":2000,\"minLength\":1,\"type\":\"string\"}},\"required\":[\"additions\",\"answeredAt\"],\"type\":\"object\"},\"askedAt\":{\"type\":\"string\"},\"dueAt\":{\"type\":\"string\"},\"id\":{\"type\":\"string\"},\"links\":{\"additionalProperties\":false,\"properties\":{\"answer\":{\"additionalProperties\":false,\"properties\":{\"accessProfile\":{\"type\":\"string\"},\"availability\":{\"additionalProperties\":false,\"if\":{\"properties\":{\"available\":{\"const\":false}}},\"properties\":{\"available\":{\"type\":\"boolean\"},\"observedRevision\":{\"minimum\":1,\"type\":\"integer\"},\"reason\":{\"enum\":[\"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\":{\"enum\":[\"refresh\",\"revise\",\"retry\",\"rebase\",\"correct-input\",\"receipt-only\"]}},\"required\":[\"available\",\"observedRevision\"],\"then\":{\"required\":[\"reason\",\"recovery\"]},\"type\":\"object\"},\"ifMatch\":{\"type\":\"string\"},\"method\":{\"const\":\"POST\"},\"operation\":{\"const\":\"answer\"},\"path\":{\"type\":\"string\"}},\"required\":[\"method\",\"path\",\"accessProfile\",\"operation\",\"ifMatch\",\"availability\"],\"type\":\"object\"}},\"type\":\"object\"},\"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\",\"links\"],\"type\":\"object\"},\"maxItems\":50,\"type\":\"array\"},\"attachments\":{\"additionalProperties\":{\"additionalProperties\":false,\"properties\":{\"classification\":{\"enum\":[\"public\",\"internal\",\"restricted\"]},\"contentTypes\":{\"items\":{\"type\":\"string\"},\"maxItems\":16,\"minItems\":1,\"type\":\"array\",\"uniqueItems\":true},\"id\":{\"type\":\"string\"},\"links\":{\"additionalProperties\":{\"additionalProperties\":false,\"properties\":{\"accessProfile\":{\"type\":\"string\"},\"availability\":{\"additionalProperties\":false,\"if\":{\"properties\":{\"available\":{\"const\":false}}},\"properties\":{\"available\":{\"type\":\"boolean\"},\"observedRevision\":{\"minimum\":1,\"type\":\"integer\"},\"reason\":{\"enum\":[\"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\":{\"enum\":[\"refresh\",\"revise\",\"retry\",\"rebase\",\"correct-input\",\"receipt-only\"]}},\"required\":[\"available\",\"observedRevision\"],\"then\":{\"required\":[\"reason\",\"recovery\"]},\"type\":\"object\"},\"ifMatch\":{\"type\":\"string\"},\"method\":{\"enum\":[\"GET\",\"PATCH\",\"DELETE\"]},\"operation\":{\"enum\":[\"download\",\"upload\",\"remove\"]},\"path\":{\"type\":\"string\"}},\"required\":[\"method\",\"path\",\"accessProfile\",\"operation\"],\"type\":\"object\"},\"type\":\"object\"},\"maximumBytes\":{\"maximum\":16777216,\"minimum\":1,\"type\":\"integer\"},\"required\":{\"type\":\"boolean\"},\"value\":{\"additionalProperties\":false,\"properties\":{\"byteSize\":{\"minimum\":1,\"type\":\"integer\"},\"contentType\":{\"type\":\"string\"},\"sha256\":{\"pattern\":\"^[a-f0-9]{64}$\",\"type\":\"string\"},\"submissionVersion\":{\"minimum\":0,\"type\":\"integer\"},\"uploadedAt\":{\"type\":\"string\"},\"verificationStatus\":{\"enum\":[\"notRequired\",\"pending\",\"approved\",\"rejected\"]}},\"required\":[\"submissionVersion\",\"sha256\",\"contentType\",\"byteSize\",\"verificationStatus\"],\"type\":\"object\"}},\"required\":[\"id\",\"required\",\"maximumBytes\",\"contentTypes\",\"classification\",\"links\"],\"type\":\"object\"},\"maxProperties\":8,\"type\":\"object\"},\"blockedReason\":{\"enum\":[\"package-changed\"]},\"createdAt\":{\"type\":\"string\"},\"decision\":{\"additionalProperties\":false,\"properties\":{\"decidedAt\":{\"type\":\"string\"},\"publicReason\":{\"minLength\":1,\"pattern\":\"^[^\\\\u0000-\\\\u001F\\\\u007F-\\\\u009F]*[^\\\\u0000-\\\\u0020\\\\u007F-\\\\u00A0\\\\u1680\\\\u2000-\\\\u200A\\\\u2028\\\\u2029\\\\u202F\\\\u205F\\\\u3000][^\\\\u0000-\\\\u001F\\\\u007F-\\\\u009F]*$\",\"type\":\"string\"},\"status\":{\"enum\":[\"approved\",\"rejected\",\"changes-requested\",\"answered\"]}},\"required\":[\"status\",\"decidedAt\"],\"type\":\"object\"},\"effectDigest\":{\"type\":\"string\"},\"handoffRefusal\":{\"additionalProperties\":false,\"properties\":{\"code\":{\"enum\":[\"review.initiator-required\",\"review.initiator-excluded\",\"review.policy-mismatch\",\"review.refused\"]}},\"required\":[\"code\"],\"type\":\"object\"},\"id\":{\"type\":\"string\"},\"input\":{\"type\":\"object\"},\"links\":{\"additionalProperties\":{\"additionalProperties\":false,\"properties\":{\"accessProfile\":{\"type\":\"string\"},\"availability\":{\"additionalProperties\":false,\"if\":{\"properties\":{\"available\":{\"const\":false}}},\"properties\":{\"available\":{\"type\":\"boolean\"},\"observedRevision\":{\"minimum\":1,\"type\":\"integer\"},\"reason\":{\"enum\":[\"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\":{\"enum\":[\"refresh\",\"revise\",\"retry\",\"rebase\",\"correct-input\",\"receipt-only\"]}},\"required\":[\"available\",\"observedRevision\"],\"then\":{\"required\":[\"reason\",\"recovery\"]},\"type\":\"object\"},\"ifMatch\":{\"type\":\"string\"},\"method\":{\"enum\":[\"GET\",\"POST\"]},\"operation\":{\"type\":\"string\"},\"path\":{\"type\":\"string\"}},\"required\":[\"method\",\"path\",\"accessProfile\",\"operation\"],\"type\":\"object\"},\"type\":\"object\"},\"partyRole\":{\"enum\":[\"owner\",\"subject\"]},\"revision\":{\"minimum\":1,\"type\":\"integer\"},\"state\":{\"enum\":[\"draft\",\"submitted\",\"applied\",\"cancelled\",\"rejected\"]},\"status\":{\"enum\":[\"draft\",\"awaiting-party\",\"in-review\",\"approved\",\"processing\",\"applied\",\"rejected\",\"cancelled\"]},\"submissionVersion\":{\"minimum\":0,\"type\":\"integer\"},\"title\":{\"maxLength\":1024,\"type\":\"string\"},\"turn\":{\"enum\":[\"party\",\"official\",\"nobody\"]}},\"required\":[\"id\",\"actionId\",\"actionRevision\",\"submissionVersion\",\"revision\",\"state\",\"turn\",\"links\"],\"type\":\"object\"}")], ["/paths/~1v1~1proposals~1{proposal_id}~1cancel/post/responses/400/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"access-profile.ambiguous\",\"request.invalid\"]}},\"type\":\"object\"}]}")], ["/paths/~1v1~1proposals~1{proposal_id}~1cancel/post/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}~1cancel/post/responses/403/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"profile.not-authorized\"]}},\"type\":\"object\"}]}")], @@ -144,7 +146,7 @@ const rules: Record = Object.fromEntries([ ["/paths/~1v1~1proposals~1{proposal_id}~1cancel/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}~1cancel/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}~1cancel/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}~1edit/post/responses/200/content/application~1json/schema", JSON.parse("{\"additionalProperties\":false,\"properties\":{\"actionId\":{\"type\":\"string\"},\"actionRevision\":{\"type\":\"string\"},\"application\":{\"additionalProperties\":false,\"properties\":{\"applicationId\":{\"type\":\"string\"},\"effectDigest\":{\"pattern\":\"^sha256:[0-9a-f]{64}$\",\"type\":\"string\"},\"resultLinks\":{\"items\":{\"additionalProperties\":false,\"properties\":{\"recordId\":{\"type\":\"string\"},\"recordType\":{\"type\":\"string\"},\"revision\":{\"minimum\":1,\"type\":\"integer\"}},\"required\":[\"recordType\",\"recordId\",\"revision\"],\"type\":\"object\"},\"maxItems\":16,\"type\":\"array\"},\"submissionVersion\":{\"minimum\":1,\"type\":\"integer\"}},\"required\":[\"applicationId\",\"submissionVersion\",\"effectDigest\",\"resultLinks\"],\"type\":\"object\"},\"applicationStatus\":{\"additionalProperties\":false,\"properties\":{\"automaticRetry\":{\"additionalProperties\":false,\"properties\":{\"attempts\":{\"maximum\":1000,\"minimum\":0,\"type\":\"integer\"},\"maximumAttempts\":{\"maximum\":1000,\"minimum\":1,\"type\":\"integer\"},\"scheduled\":{\"type\":\"boolean\"}},\"required\":[\"scheduled\",\"attempts\",\"maximumAttempts\"],\"type\":\"object\"},\"mode\":{\"enum\":[\"automatic\",\"manual\"]},\"reason\":{\"enum\":[\"package-changed\",\"dependency-outage\",\"lease-expired\",\"application-refused\",\"attempts-exhausted\"]},\"recovery\":{\"enum\":[\"retry\",\"rebase\",\"revise\",\"correct-input\"]},\"state\":{\"enum\":[\"awaiting-review\",\"pending\",\"applying\",\"blocked\",\"applied\",\"cancelled\",\"rejected\"]}},\"required\":[\"state\",\"mode\"],\"type\":\"object\"},\"asks\":{\"items\":{\"additionalProperties\":false,\"properties\":{\"answer\":{\"additionalProperties\":false,\"properties\":{\"additions\":{\"items\":{\"type\":\"string\"},\"maxItems\":32,\"type\":\"array\",\"uniqueItems\":true},\"answeredAt\":{\"type\":\"string\"},\"text\":{\"maxLength\":2000,\"minLength\":1,\"type\":\"string\"}},\"required\":[\"additions\",\"answeredAt\"],\"type\":\"object\"},\"askedAt\":{\"type\":\"string\"},\"dueAt\":{\"type\":\"string\"},\"id\":{\"type\":\"string\"},\"links\":{\"additionalProperties\":false,\"properties\":{\"answer\":{\"additionalProperties\":false,\"properties\":{\"accessProfile\":{\"type\":\"string\"},\"availability\":{\"additionalProperties\":false,\"if\":{\"properties\":{\"available\":{\"const\":false}}},\"properties\":{\"available\":{\"type\":\"boolean\"},\"observedRevision\":{\"minimum\":1,\"type\":\"integer\"},\"reason\":{\"enum\":[\"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\":{\"enum\":[\"refresh\",\"revise\",\"retry\",\"rebase\",\"correct-input\",\"receipt-only\"]}},\"required\":[\"available\",\"observedRevision\"],\"then\":{\"required\":[\"reason\",\"recovery\"]},\"type\":\"object\"},\"ifMatch\":{\"type\":\"string\"},\"method\":{\"const\":\"POST\"},\"operation\":{\"const\":\"answer\"},\"path\":{\"type\":\"string\"}},\"required\":[\"method\",\"path\",\"accessProfile\",\"operation\",\"ifMatch\",\"availability\"],\"type\":\"object\"}},\"type\":\"object\"},\"state\":{\"enum\":[\"open\",\"answered\",\"expired\",\"closed\"]},\"text\":{\"maxLength\":2000,\"minLength\":1,\"type\":\"string\"},\"wants\":{\"items\":{\"additionalProperties\":false,\"properties\":{\"kind\":{\"enum\":[\"answer\",\"document\"]}},\"required\":[\"kind\"],\"type\":\"object\"},\"maxItems\":8,\"type\":\"array\",\"uniqueItems\":true}},\"required\":[\"id\",\"text\",\"wants\",\"askedAt\",\"state\",\"links\"],\"type\":\"object\"},\"maxItems\":50,\"type\":\"array\"},\"attachments\":{\"additionalProperties\":{\"additionalProperties\":false,\"properties\":{\"classification\":{\"enum\":[\"public\",\"internal\",\"restricted\"]},\"contentTypes\":{\"items\":{\"type\":\"string\"},\"maxItems\":16,\"minItems\":1,\"type\":\"array\",\"uniqueItems\":true},\"id\":{\"type\":\"string\"},\"links\":{\"additionalProperties\":{\"additionalProperties\":false,\"properties\":{\"accessProfile\":{\"type\":\"string\"},\"availability\":{\"additionalProperties\":false,\"if\":{\"properties\":{\"available\":{\"const\":false}}},\"properties\":{\"available\":{\"type\":\"boolean\"},\"observedRevision\":{\"minimum\":1,\"type\":\"integer\"},\"reason\":{\"enum\":[\"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\":{\"enum\":[\"refresh\",\"revise\",\"retry\",\"rebase\",\"correct-input\",\"receipt-only\"]}},\"required\":[\"available\",\"observedRevision\"],\"then\":{\"required\":[\"reason\",\"recovery\"]},\"type\":\"object\"},\"ifMatch\":{\"type\":\"string\"},\"method\":{\"enum\":[\"GET\",\"PATCH\",\"DELETE\"]},\"operation\":{\"enum\":[\"download\",\"upload\",\"remove\"]},\"path\":{\"type\":\"string\"}},\"required\":[\"method\",\"path\",\"accessProfile\",\"operation\"],\"type\":\"object\"},\"type\":\"object\"},\"maximumBytes\":{\"maximum\":16777216,\"minimum\":1,\"type\":\"integer\"},\"required\":{\"type\":\"boolean\"},\"value\":{\"additionalProperties\":false,\"properties\":{\"byteSize\":{\"minimum\":1,\"type\":\"integer\"},\"contentType\":{\"type\":\"string\"},\"sha256\":{\"pattern\":\"^[a-f0-9]{64}$\",\"type\":\"string\"},\"submissionVersion\":{\"minimum\":0,\"type\":\"integer\"},\"uploadedAt\":{\"type\":\"string\"},\"verificationStatus\":{\"enum\":[\"notRequired\",\"pending\",\"approved\",\"rejected\"]}},\"required\":[\"submissionVersion\",\"sha256\",\"contentType\",\"byteSize\",\"verificationStatus\"],\"type\":\"object\"}},\"required\":[\"id\",\"required\",\"maximumBytes\",\"contentTypes\",\"classification\",\"links\"],\"type\":\"object\"},\"maxProperties\":8,\"type\":\"object\"},\"blockedReason\":{\"enum\":[\"package-changed\"]},\"createdAt\":{\"type\":\"string\"},\"decision\":{\"additionalProperties\":false,\"properties\":{\"decidedAt\":{\"type\":\"string\"},\"publicReason\":{\"minLength\":1,\"pattern\":\"^[^\\\\u0000-\\\\u001F\\\\u007F-\\\\u009F]*[^\\\\u0000-\\\\u0020\\\\u007F-\\\\u00A0\\\\u1680\\\\u2000-\\\\u200A\\\\u2028\\\\u2029\\\\u202F\\\\u205F\\\\u3000][^\\\\u0000-\\\\u001F\\\\u007F-\\\\u009F]*$\",\"type\":\"string\"},\"status\":{\"enum\":[\"approved\",\"rejected\",\"changes-requested\",\"answered\"]}},\"required\":[\"status\",\"decidedAt\"],\"type\":\"object\"},\"effectDigest\":{\"type\":\"string\"},\"handoffRefusal\":{\"additionalProperties\":false,\"properties\":{\"code\":{\"enum\":[\"review.initiator-required\",\"review.initiator-excluded\",\"review.policy-mismatch\",\"review.refused\"]}},\"required\":[\"code\"],\"type\":\"object\"},\"id\":{\"type\":\"string\"},\"input\":{\"type\":\"object\"},\"links\":{\"additionalProperties\":{\"additionalProperties\":false,\"properties\":{\"accessProfile\":{\"type\":\"string\"},\"availability\":{\"additionalProperties\":false,\"if\":{\"properties\":{\"available\":{\"const\":false}}},\"properties\":{\"available\":{\"type\":\"boolean\"},\"observedRevision\":{\"minimum\":1,\"type\":\"integer\"},\"reason\":{\"enum\":[\"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\":{\"enum\":[\"refresh\",\"revise\",\"retry\",\"rebase\",\"correct-input\",\"receipt-only\"]}},\"required\":[\"available\",\"observedRevision\"],\"then\":{\"required\":[\"reason\",\"recovery\"]},\"type\":\"object\"},\"ifMatch\":{\"type\":\"string\"},\"method\":{\"enum\":[\"GET\",\"POST\"]},\"operation\":{\"type\":\"string\"},\"path\":{\"type\":\"string\"}},\"required\":[\"method\",\"path\",\"accessProfile\",\"operation\"],\"type\":\"object\"},\"type\":\"object\"},\"revision\":{\"minimum\":1,\"type\":\"integer\"},\"state\":{\"enum\":[\"draft\",\"submitted\",\"applied\",\"cancelled\",\"rejected\"]},\"status\":{\"enum\":[\"draft\",\"awaiting-party\",\"in-review\",\"approved\",\"processing\",\"applied\",\"rejected\",\"cancelled\"]},\"submissionVersion\":{\"minimum\":0,\"type\":\"integer\"},\"title\":{\"maxLength\":1024,\"type\":\"string\"},\"turn\":{\"enum\":[\"party\",\"official\",\"nobody\"]}},\"required\":[\"id\",\"actionId\",\"actionRevision\",\"submissionVersion\",\"revision\",\"state\",\"turn\",\"links\"],\"type\":\"object\"}")], + ["/paths/~1v1~1proposals~1{proposal_id}~1edit/post/responses/200/content/application~1json/schema", JSON.parse("{\"additionalProperties\":false,\"properties\":{\"actionId\":{\"type\":\"string\"},\"actionRevision\":{\"type\":\"string\"},\"application\":{\"additionalProperties\":false,\"properties\":{\"applicationId\":{\"type\":\"string\"},\"effectDigest\":{\"pattern\":\"^sha256:[0-9a-f]{64}$\",\"type\":\"string\"},\"resultLinks\":{\"items\":{\"additionalProperties\":false,\"properties\":{\"recordId\":{\"type\":\"string\"},\"recordType\":{\"type\":\"string\"},\"revision\":{\"minimum\":1,\"type\":\"integer\"}},\"required\":[\"recordType\",\"recordId\",\"revision\"],\"type\":\"object\"},\"maxItems\":16,\"type\":\"array\"},\"submissionVersion\":{\"minimum\":1,\"type\":\"integer\"}},\"required\":[\"applicationId\",\"submissionVersion\",\"effectDigest\",\"resultLinks\"],\"type\":\"object\"},\"applicationStatus\":{\"additionalProperties\":false,\"properties\":{\"automaticRetry\":{\"additionalProperties\":false,\"properties\":{\"attempts\":{\"maximum\":1000,\"minimum\":0,\"type\":\"integer\"},\"maximumAttempts\":{\"maximum\":1000,\"minimum\":1,\"type\":\"integer\"},\"scheduled\":{\"type\":\"boolean\"}},\"required\":[\"scheduled\",\"attempts\",\"maximumAttempts\"],\"type\":\"object\"},\"mode\":{\"enum\":[\"automatic\",\"manual\"]},\"reason\":{\"enum\":[\"package-changed\",\"dependency-outage\",\"lease-expired\",\"application-refused\",\"attempts-exhausted\"]},\"recovery\":{\"enum\":[\"retry\",\"rebase\",\"revise\",\"correct-input\"]},\"state\":{\"enum\":[\"awaiting-review\",\"pending\",\"applying\",\"blocked\",\"applied\",\"cancelled\",\"rejected\"]}},\"required\":[\"state\",\"mode\"],\"type\":\"object\"},\"asks\":{\"items\":{\"additionalProperties\":false,\"properties\":{\"answer\":{\"additionalProperties\":false,\"properties\":{\"additions\":{\"items\":{\"type\":\"string\"},\"maxItems\":32,\"type\":\"array\",\"uniqueItems\":true},\"answeredAt\":{\"type\":\"string\"},\"formEntries\":{\"items\":{\"type\":\"string\"},\"maxItems\":32,\"type\":\"array\",\"uniqueItems\":true},\"text\":{\"maxLength\":2000,\"minLength\":1,\"type\":\"string\"}},\"required\":[\"additions\",\"answeredAt\"],\"type\":\"object\"},\"askedAt\":{\"type\":\"string\"},\"dueAt\":{\"type\":\"string\"},\"id\":{\"type\":\"string\"},\"links\":{\"additionalProperties\":false,\"properties\":{\"answer\":{\"additionalProperties\":false,\"properties\":{\"accessProfile\":{\"type\":\"string\"},\"availability\":{\"additionalProperties\":false,\"if\":{\"properties\":{\"available\":{\"const\":false}}},\"properties\":{\"available\":{\"type\":\"boolean\"},\"observedRevision\":{\"minimum\":1,\"type\":\"integer\"},\"reason\":{\"enum\":[\"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\":{\"enum\":[\"refresh\",\"revise\",\"retry\",\"rebase\",\"correct-input\",\"receipt-only\"]}},\"required\":[\"available\",\"observedRevision\"],\"then\":{\"required\":[\"reason\",\"recovery\"]},\"type\":\"object\"},\"ifMatch\":{\"type\":\"string\"},\"method\":{\"const\":\"POST\"},\"operation\":{\"const\":\"answer\"},\"path\":{\"type\":\"string\"}},\"required\":[\"method\",\"path\",\"accessProfile\",\"operation\",\"ifMatch\",\"availability\"],\"type\":\"object\"}},\"type\":\"object\"},\"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\",\"links\"],\"type\":\"object\"},\"maxItems\":50,\"type\":\"array\"},\"attachments\":{\"additionalProperties\":{\"additionalProperties\":false,\"properties\":{\"classification\":{\"enum\":[\"public\",\"internal\",\"restricted\"]},\"contentTypes\":{\"items\":{\"type\":\"string\"},\"maxItems\":16,\"minItems\":1,\"type\":\"array\",\"uniqueItems\":true},\"id\":{\"type\":\"string\"},\"links\":{\"additionalProperties\":{\"additionalProperties\":false,\"properties\":{\"accessProfile\":{\"type\":\"string\"},\"availability\":{\"additionalProperties\":false,\"if\":{\"properties\":{\"available\":{\"const\":false}}},\"properties\":{\"available\":{\"type\":\"boolean\"},\"observedRevision\":{\"minimum\":1,\"type\":\"integer\"},\"reason\":{\"enum\":[\"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\":{\"enum\":[\"refresh\",\"revise\",\"retry\",\"rebase\",\"correct-input\",\"receipt-only\"]}},\"required\":[\"available\",\"observedRevision\"],\"then\":{\"required\":[\"reason\",\"recovery\"]},\"type\":\"object\"},\"ifMatch\":{\"type\":\"string\"},\"method\":{\"enum\":[\"GET\",\"PATCH\",\"DELETE\"]},\"operation\":{\"enum\":[\"download\",\"upload\",\"remove\"]},\"path\":{\"type\":\"string\"}},\"required\":[\"method\",\"path\",\"accessProfile\",\"operation\"],\"type\":\"object\"},\"type\":\"object\"},\"maximumBytes\":{\"maximum\":16777216,\"minimum\":1,\"type\":\"integer\"},\"required\":{\"type\":\"boolean\"},\"value\":{\"additionalProperties\":false,\"properties\":{\"byteSize\":{\"minimum\":1,\"type\":\"integer\"},\"contentType\":{\"type\":\"string\"},\"sha256\":{\"pattern\":\"^[a-f0-9]{64}$\",\"type\":\"string\"},\"submissionVersion\":{\"minimum\":0,\"type\":\"integer\"},\"uploadedAt\":{\"type\":\"string\"},\"verificationStatus\":{\"enum\":[\"notRequired\",\"pending\",\"approved\",\"rejected\"]}},\"required\":[\"submissionVersion\",\"sha256\",\"contentType\",\"byteSize\",\"verificationStatus\"],\"type\":\"object\"}},\"required\":[\"id\",\"required\",\"maximumBytes\",\"contentTypes\",\"classification\",\"links\"],\"type\":\"object\"},\"maxProperties\":8,\"type\":\"object\"},\"blockedReason\":{\"enum\":[\"package-changed\"]},\"createdAt\":{\"type\":\"string\"},\"decision\":{\"additionalProperties\":false,\"properties\":{\"decidedAt\":{\"type\":\"string\"},\"publicReason\":{\"minLength\":1,\"pattern\":\"^[^\\\\u0000-\\\\u001F\\\\u007F-\\\\u009F]*[^\\\\u0000-\\\\u0020\\\\u007F-\\\\u00A0\\\\u1680\\\\u2000-\\\\u200A\\\\u2028\\\\u2029\\\\u202F\\\\u205F\\\\u3000][^\\\\u0000-\\\\u001F\\\\u007F-\\\\u009F]*$\",\"type\":\"string\"},\"status\":{\"enum\":[\"approved\",\"rejected\",\"changes-requested\",\"answered\"]}},\"required\":[\"status\",\"decidedAt\"],\"type\":\"object\"},\"effectDigest\":{\"type\":\"string\"},\"handoffRefusal\":{\"additionalProperties\":false,\"properties\":{\"code\":{\"enum\":[\"review.initiator-required\",\"review.initiator-excluded\",\"review.policy-mismatch\",\"review.refused\"]}},\"required\":[\"code\"],\"type\":\"object\"},\"id\":{\"type\":\"string\"},\"input\":{\"type\":\"object\"},\"links\":{\"additionalProperties\":{\"additionalProperties\":false,\"properties\":{\"accessProfile\":{\"type\":\"string\"},\"availability\":{\"additionalProperties\":false,\"if\":{\"properties\":{\"available\":{\"const\":false}}},\"properties\":{\"available\":{\"type\":\"boolean\"},\"observedRevision\":{\"minimum\":1,\"type\":\"integer\"},\"reason\":{\"enum\":[\"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\":{\"enum\":[\"refresh\",\"revise\",\"retry\",\"rebase\",\"correct-input\",\"receipt-only\"]}},\"required\":[\"available\",\"observedRevision\"],\"then\":{\"required\":[\"reason\",\"recovery\"]},\"type\":\"object\"},\"ifMatch\":{\"type\":\"string\"},\"method\":{\"enum\":[\"GET\",\"POST\"]},\"operation\":{\"type\":\"string\"},\"path\":{\"type\":\"string\"}},\"required\":[\"method\",\"path\",\"accessProfile\",\"operation\"],\"type\":\"object\"},\"type\":\"object\"},\"partyRole\":{\"enum\":[\"owner\",\"subject\"]},\"revision\":{\"minimum\":1,\"type\":\"integer\"},\"state\":{\"enum\":[\"draft\",\"submitted\",\"applied\",\"cancelled\",\"rejected\"]},\"status\":{\"enum\":[\"draft\",\"awaiting-party\",\"in-review\",\"approved\",\"processing\",\"applied\",\"rejected\",\"cancelled\"]},\"submissionVersion\":{\"minimum\":0,\"type\":\"integer\"},\"title\":{\"maxLength\":1024,\"type\":\"string\"},\"turn\":{\"enum\":[\"party\",\"official\",\"nobody\"]}},\"required\":[\"id\",\"actionId\",\"actionRevision\",\"submissionVersion\",\"revision\",\"state\",\"turn\",\"links\"],\"type\":\"object\"}")], ["/paths/~1v1~1proposals~1{proposal_id}~1edit/post/responses/400/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"access-profile.ambiguous\",\"request.invalid\"]}},\"type\":\"object\"}]}")], ["/paths/~1v1~1proposals~1{proposal_id}~1edit/post/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}~1edit/post/responses/403/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"profile.not-authorized\"]}},\"type\":\"object\"}]}")], @@ -164,12 +166,12 @@ const rules: Record = Object.fromEntries([ ["/paths/~1v1~1proposals~1{proposal_id}~1submissions~1{submission_version}/get/responses/410/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"proposal.submission-expired\"]}},\"type\":\"object\"}]}")], ["/paths/~1v1~1proposals~1{proposal_id}~1submissions~1{submission_version}/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}~1submissions~1{submission_version}/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}~1submit/post/responses/200/content/application~1json/schema", JSON.parse("{\"additionalProperties\":false,\"properties\":{\"actionId\":{\"type\":\"string\"},\"actionRevision\":{\"type\":\"string\"},\"application\":{\"additionalProperties\":false,\"properties\":{\"applicationId\":{\"type\":\"string\"},\"effectDigest\":{\"pattern\":\"^sha256:[0-9a-f]{64}$\",\"type\":\"string\"},\"resultLinks\":{\"items\":{\"additionalProperties\":false,\"properties\":{\"recordId\":{\"type\":\"string\"},\"recordType\":{\"type\":\"string\"},\"revision\":{\"minimum\":1,\"type\":\"integer\"}},\"required\":[\"recordType\",\"recordId\",\"revision\"],\"type\":\"object\"},\"maxItems\":16,\"type\":\"array\"},\"submissionVersion\":{\"minimum\":1,\"type\":\"integer\"}},\"required\":[\"applicationId\",\"submissionVersion\",\"effectDigest\",\"resultLinks\"],\"type\":\"object\"},\"applicationStatus\":{\"additionalProperties\":false,\"properties\":{\"automaticRetry\":{\"additionalProperties\":false,\"properties\":{\"attempts\":{\"maximum\":1000,\"minimum\":0,\"type\":\"integer\"},\"maximumAttempts\":{\"maximum\":1000,\"minimum\":1,\"type\":\"integer\"},\"scheduled\":{\"type\":\"boolean\"}},\"required\":[\"scheduled\",\"attempts\",\"maximumAttempts\"],\"type\":\"object\"},\"mode\":{\"enum\":[\"automatic\",\"manual\"]},\"reason\":{\"enum\":[\"package-changed\",\"dependency-outage\",\"lease-expired\",\"application-refused\",\"attempts-exhausted\"]},\"recovery\":{\"enum\":[\"retry\",\"rebase\",\"revise\",\"correct-input\"]},\"state\":{\"enum\":[\"awaiting-review\",\"pending\",\"applying\",\"blocked\",\"applied\",\"cancelled\",\"rejected\"]}},\"required\":[\"state\",\"mode\"],\"type\":\"object\"},\"asks\":{\"items\":{\"additionalProperties\":false,\"properties\":{\"answer\":{\"additionalProperties\":false,\"properties\":{\"additions\":{\"items\":{\"type\":\"string\"},\"maxItems\":32,\"type\":\"array\",\"uniqueItems\":true},\"answeredAt\":{\"type\":\"string\"},\"text\":{\"maxLength\":2000,\"minLength\":1,\"type\":\"string\"}},\"required\":[\"additions\",\"answeredAt\"],\"type\":\"object\"},\"askedAt\":{\"type\":\"string\"},\"dueAt\":{\"type\":\"string\"},\"id\":{\"type\":\"string\"},\"links\":{\"additionalProperties\":false,\"properties\":{\"answer\":{\"additionalProperties\":false,\"properties\":{\"accessProfile\":{\"type\":\"string\"},\"availability\":{\"additionalProperties\":false,\"if\":{\"properties\":{\"available\":{\"const\":false}}},\"properties\":{\"available\":{\"type\":\"boolean\"},\"observedRevision\":{\"minimum\":1,\"type\":\"integer\"},\"reason\":{\"enum\":[\"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\":{\"enum\":[\"refresh\",\"revise\",\"retry\",\"rebase\",\"correct-input\",\"receipt-only\"]}},\"required\":[\"available\",\"observedRevision\"],\"then\":{\"required\":[\"reason\",\"recovery\"]},\"type\":\"object\"},\"ifMatch\":{\"type\":\"string\"},\"method\":{\"const\":\"POST\"},\"operation\":{\"const\":\"answer\"},\"path\":{\"type\":\"string\"}},\"required\":[\"method\",\"path\",\"accessProfile\",\"operation\",\"ifMatch\",\"availability\"],\"type\":\"object\"}},\"type\":\"object\"},\"state\":{\"enum\":[\"open\",\"answered\",\"expired\",\"closed\"]},\"text\":{\"maxLength\":2000,\"minLength\":1,\"type\":\"string\"},\"wants\":{\"items\":{\"additionalProperties\":false,\"properties\":{\"kind\":{\"enum\":[\"answer\",\"document\"]}},\"required\":[\"kind\"],\"type\":\"object\"},\"maxItems\":8,\"type\":\"array\",\"uniqueItems\":true}},\"required\":[\"id\",\"text\",\"wants\",\"askedAt\",\"state\",\"links\"],\"type\":\"object\"},\"maxItems\":50,\"type\":\"array\"},\"attachments\":{\"additionalProperties\":{\"additionalProperties\":false,\"properties\":{\"classification\":{\"enum\":[\"public\",\"internal\",\"restricted\"]},\"contentTypes\":{\"items\":{\"type\":\"string\"},\"maxItems\":16,\"minItems\":1,\"type\":\"array\",\"uniqueItems\":true},\"id\":{\"type\":\"string\"},\"links\":{\"additionalProperties\":{\"additionalProperties\":false,\"properties\":{\"accessProfile\":{\"type\":\"string\"},\"availability\":{\"additionalProperties\":false,\"if\":{\"properties\":{\"available\":{\"const\":false}}},\"properties\":{\"available\":{\"type\":\"boolean\"},\"observedRevision\":{\"minimum\":1,\"type\":\"integer\"},\"reason\":{\"enum\":[\"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\":{\"enum\":[\"refresh\",\"revise\",\"retry\",\"rebase\",\"correct-input\",\"receipt-only\"]}},\"required\":[\"available\",\"observedRevision\"],\"then\":{\"required\":[\"reason\",\"recovery\"]},\"type\":\"object\"},\"ifMatch\":{\"type\":\"string\"},\"method\":{\"enum\":[\"GET\",\"PATCH\",\"DELETE\"]},\"operation\":{\"enum\":[\"download\",\"upload\",\"remove\"]},\"path\":{\"type\":\"string\"}},\"required\":[\"method\",\"path\",\"accessProfile\",\"operation\"],\"type\":\"object\"},\"type\":\"object\"},\"maximumBytes\":{\"maximum\":16777216,\"minimum\":1,\"type\":\"integer\"},\"required\":{\"type\":\"boolean\"},\"value\":{\"additionalProperties\":false,\"properties\":{\"byteSize\":{\"minimum\":1,\"type\":\"integer\"},\"contentType\":{\"type\":\"string\"},\"sha256\":{\"pattern\":\"^[a-f0-9]{64}$\",\"type\":\"string\"},\"submissionVersion\":{\"minimum\":0,\"type\":\"integer\"},\"uploadedAt\":{\"type\":\"string\"},\"verificationStatus\":{\"enum\":[\"notRequired\",\"pending\",\"approved\",\"rejected\"]}},\"required\":[\"submissionVersion\",\"sha256\",\"contentType\",\"byteSize\",\"verificationStatus\"],\"type\":\"object\"}},\"required\":[\"id\",\"required\",\"maximumBytes\",\"contentTypes\",\"classification\",\"links\"],\"type\":\"object\"},\"maxProperties\":8,\"type\":\"object\"},\"blockedReason\":{\"enum\":[\"package-changed\"]},\"createdAt\":{\"type\":\"string\"},\"decision\":{\"additionalProperties\":false,\"properties\":{\"decidedAt\":{\"type\":\"string\"},\"publicReason\":{\"minLength\":1,\"pattern\":\"^[^\\\\u0000-\\\\u001F\\\\u007F-\\\\u009F]*[^\\\\u0000-\\\\u0020\\\\u007F-\\\\u00A0\\\\u1680\\\\u2000-\\\\u200A\\\\u2028\\\\u2029\\\\u202F\\\\u205F\\\\u3000][^\\\\u0000-\\\\u001F\\\\u007F-\\\\u009F]*$\",\"type\":\"string\"},\"status\":{\"enum\":[\"approved\",\"rejected\",\"changes-requested\",\"answered\"]}},\"required\":[\"status\",\"decidedAt\"],\"type\":\"object\"},\"effectDigest\":{\"type\":\"string\"},\"handoffRefusal\":{\"additionalProperties\":false,\"properties\":{\"code\":{\"enum\":[\"review.initiator-required\",\"review.initiator-excluded\",\"review.policy-mismatch\",\"review.refused\"]}},\"required\":[\"code\"],\"type\":\"object\"},\"id\":{\"type\":\"string\"},\"input\":{\"type\":\"object\"},\"links\":{\"additionalProperties\":{\"additionalProperties\":false,\"properties\":{\"accessProfile\":{\"type\":\"string\"},\"availability\":{\"additionalProperties\":false,\"if\":{\"properties\":{\"available\":{\"const\":false}}},\"properties\":{\"available\":{\"type\":\"boolean\"},\"observedRevision\":{\"minimum\":1,\"type\":\"integer\"},\"reason\":{\"enum\":[\"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\":{\"enum\":[\"refresh\",\"revise\",\"retry\",\"rebase\",\"correct-input\",\"receipt-only\"]}},\"required\":[\"available\",\"observedRevision\"],\"then\":{\"required\":[\"reason\",\"recovery\"]},\"type\":\"object\"},\"ifMatch\":{\"type\":\"string\"},\"method\":{\"enum\":[\"GET\",\"POST\"]},\"operation\":{\"type\":\"string\"},\"path\":{\"type\":\"string\"}},\"required\":[\"method\",\"path\",\"accessProfile\",\"operation\"],\"type\":\"object\"},\"type\":\"object\"},\"revision\":{\"minimum\":1,\"type\":\"integer\"},\"state\":{\"enum\":[\"draft\",\"submitted\",\"applied\",\"cancelled\",\"rejected\"]},\"status\":{\"enum\":[\"draft\",\"awaiting-party\",\"in-review\",\"approved\",\"processing\",\"applied\",\"rejected\",\"cancelled\"]},\"submissionVersion\":{\"minimum\":0,\"type\":\"integer\"},\"title\":{\"maxLength\":1024,\"type\":\"string\"},\"turn\":{\"enum\":[\"party\",\"official\",\"nobody\"]}},\"required\":[\"id\",\"actionId\",\"actionRevision\",\"submissionVersion\",\"revision\",\"state\",\"turn\",\"links\"],\"type\":\"object\"}")], + ["/paths/~1v1~1proposals~1{proposal_id}~1submit/post/responses/200/content/application~1json/schema", JSON.parse("{\"additionalProperties\":false,\"properties\":{\"actionId\":{\"type\":\"string\"},\"actionRevision\":{\"type\":\"string\"},\"application\":{\"additionalProperties\":false,\"properties\":{\"applicationId\":{\"type\":\"string\"},\"effectDigest\":{\"pattern\":\"^sha256:[0-9a-f]{64}$\",\"type\":\"string\"},\"resultLinks\":{\"items\":{\"additionalProperties\":false,\"properties\":{\"recordId\":{\"type\":\"string\"},\"recordType\":{\"type\":\"string\"},\"revision\":{\"minimum\":1,\"type\":\"integer\"}},\"required\":[\"recordType\",\"recordId\",\"revision\"],\"type\":\"object\"},\"maxItems\":16,\"type\":\"array\"},\"submissionVersion\":{\"minimum\":1,\"type\":\"integer\"}},\"required\":[\"applicationId\",\"submissionVersion\",\"effectDigest\",\"resultLinks\"],\"type\":\"object\"},\"applicationStatus\":{\"additionalProperties\":false,\"properties\":{\"automaticRetry\":{\"additionalProperties\":false,\"properties\":{\"attempts\":{\"maximum\":1000,\"minimum\":0,\"type\":\"integer\"},\"maximumAttempts\":{\"maximum\":1000,\"minimum\":1,\"type\":\"integer\"},\"scheduled\":{\"type\":\"boolean\"}},\"required\":[\"scheduled\",\"attempts\",\"maximumAttempts\"],\"type\":\"object\"},\"mode\":{\"enum\":[\"automatic\",\"manual\"]},\"reason\":{\"enum\":[\"package-changed\",\"dependency-outage\",\"lease-expired\",\"application-refused\",\"attempts-exhausted\"]},\"recovery\":{\"enum\":[\"retry\",\"rebase\",\"revise\",\"correct-input\"]},\"state\":{\"enum\":[\"awaiting-review\",\"pending\",\"applying\",\"blocked\",\"applied\",\"cancelled\",\"rejected\"]}},\"required\":[\"state\",\"mode\"],\"type\":\"object\"},\"asks\":{\"items\":{\"additionalProperties\":false,\"properties\":{\"answer\":{\"additionalProperties\":false,\"properties\":{\"additions\":{\"items\":{\"type\":\"string\"},\"maxItems\":32,\"type\":\"array\",\"uniqueItems\":true},\"answeredAt\":{\"type\":\"string\"},\"formEntries\":{\"items\":{\"type\":\"string\"},\"maxItems\":32,\"type\":\"array\",\"uniqueItems\":true},\"text\":{\"maxLength\":2000,\"minLength\":1,\"type\":\"string\"}},\"required\":[\"additions\",\"answeredAt\"],\"type\":\"object\"},\"askedAt\":{\"type\":\"string\"},\"dueAt\":{\"type\":\"string\"},\"id\":{\"type\":\"string\"},\"links\":{\"additionalProperties\":false,\"properties\":{\"answer\":{\"additionalProperties\":false,\"properties\":{\"accessProfile\":{\"type\":\"string\"},\"availability\":{\"additionalProperties\":false,\"if\":{\"properties\":{\"available\":{\"const\":false}}},\"properties\":{\"available\":{\"type\":\"boolean\"},\"observedRevision\":{\"minimum\":1,\"type\":\"integer\"},\"reason\":{\"enum\":[\"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\":{\"enum\":[\"refresh\",\"revise\",\"retry\",\"rebase\",\"correct-input\",\"receipt-only\"]}},\"required\":[\"available\",\"observedRevision\"],\"then\":{\"required\":[\"reason\",\"recovery\"]},\"type\":\"object\"},\"ifMatch\":{\"type\":\"string\"},\"method\":{\"const\":\"POST\"},\"operation\":{\"const\":\"answer\"},\"path\":{\"type\":\"string\"}},\"required\":[\"method\",\"path\",\"accessProfile\",\"operation\",\"ifMatch\",\"availability\"],\"type\":\"object\"}},\"type\":\"object\"},\"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\",\"links\"],\"type\":\"object\"},\"maxItems\":50,\"type\":\"array\"},\"attachments\":{\"additionalProperties\":{\"additionalProperties\":false,\"properties\":{\"classification\":{\"enum\":[\"public\",\"internal\",\"restricted\"]},\"contentTypes\":{\"items\":{\"type\":\"string\"},\"maxItems\":16,\"minItems\":1,\"type\":\"array\",\"uniqueItems\":true},\"id\":{\"type\":\"string\"},\"links\":{\"additionalProperties\":{\"additionalProperties\":false,\"properties\":{\"accessProfile\":{\"type\":\"string\"},\"availability\":{\"additionalProperties\":false,\"if\":{\"properties\":{\"available\":{\"const\":false}}},\"properties\":{\"available\":{\"type\":\"boolean\"},\"observedRevision\":{\"minimum\":1,\"type\":\"integer\"},\"reason\":{\"enum\":[\"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\":{\"enum\":[\"refresh\",\"revise\",\"retry\",\"rebase\",\"correct-input\",\"receipt-only\"]}},\"required\":[\"available\",\"observedRevision\"],\"then\":{\"required\":[\"reason\",\"recovery\"]},\"type\":\"object\"},\"ifMatch\":{\"type\":\"string\"},\"method\":{\"enum\":[\"GET\",\"PATCH\",\"DELETE\"]},\"operation\":{\"enum\":[\"download\",\"upload\",\"remove\"]},\"path\":{\"type\":\"string\"}},\"required\":[\"method\",\"path\",\"accessProfile\",\"operation\"],\"type\":\"object\"},\"type\":\"object\"},\"maximumBytes\":{\"maximum\":16777216,\"minimum\":1,\"type\":\"integer\"},\"required\":{\"type\":\"boolean\"},\"value\":{\"additionalProperties\":false,\"properties\":{\"byteSize\":{\"minimum\":1,\"type\":\"integer\"},\"contentType\":{\"type\":\"string\"},\"sha256\":{\"pattern\":\"^[a-f0-9]{64}$\",\"type\":\"string\"},\"submissionVersion\":{\"minimum\":0,\"type\":\"integer\"},\"uploadedAt\":{\"type\":\"string\"},\"verificationStatus\":{\"enum\":[\"notRequired\",\"pending\",\"approved\",\"rejected\"]}},\"required\":[\"submissionVersion\",\"sha256\",\"contentType\",\"byteSize\",\"verificationStatus\"],\"type\":\"object\"}},\"required\":[\"id\",\"required\",\"maximumBytes\",\"contentTypes\",\"classification\",\"links\"],\"type\":\"object\"},\"maxProperties\":8,\"type\":\"object\"},\"blockedReason\":{\"enum\":[\"package-changed\"]},\"createdAt\":{\"type\":\"string\"},\"decision\":{\"additionalProperties\":false,\"properties\":{\"decidedAt\":{\"type\":\"string\"},\"publicReason\":{\"minLength\":1,\"pattern\":\"^[^\\\\u0000-\\\\u001F\\\\u007F-\\\\u009F]*[^\\\\u0000-\\\\u0020\\\\u007F-\\\\u00A0\\\\u1680\\\\u2000-\\\\u200A\\\\u2028\\\\u2029\\\\u202F\\\\u205F\\\\u3000][^\\\\u0000-\\\\u001F\\\\u007F-\\\\u009F]*$\",\"type\":\"string\"},\"status\":{\"enum\":[\"approved\",\"rejected\",\"changes-requested\",\"answered\"]}},\"required\":[\"status\",\"decidedAt\"],\"type\":\"object\"},\"effectDigest\":{\"type\":\"string\"},\"handoffRefusal\":{\"additionalProperties\":false,\"properties\":{\"code\":{\"enum\":[\"review.initiator-required\",\"review.initiator-excluded\",\"review.policy-mismatch\",\"review.refused\"]}},\"required\":[\"code\"],\"type\":\"object\"},\"id\":{\"type\":\"string\"},\"input\":{\"type\":\"object\"},\"links\":{\"additionalProperties\":{\"additionalProperties\":false,\"properties\":{\"accessProfile\":{\"type\":\"string\"},\"availability\":{\"additionalProperties\":false,\"if\":{\"properties\":{\"available\":{\"const\":false}}},\"properties\":{\"available\":{\"type\":\"boolean\"},\"observedRevision\":{\"minimum\":1,\"type\":\"integer\"},\"reason\":{\"enum\":[\"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\":{\"enum\":[\"refresh\",\"revise\",\"retry\",\"rebase\",\"correct-input\",\"receipt-only\"]}},\"required\":[\"available\",\"observedRevision\"],\"then\":{\"required\":[\"reason\",\"recovery\"]},\"type\":\"object\"},\"ifMatch\":{\"type\":\"string\"},\"method\":{\"enum\":[\"GET\",\"POST\"]},\"operation\":{\"type\":\"string\"},\"path\":{\"type\":\"string\"}},\"required\":[\"method\",\"path\",\"accessProfile\",\"operation\"],\"type\":\"object\"},\"type\":\"object\"},\"partyRole\":{\"enum\":[\"owner\",\"subject\"]},\"revision\":{\"minimum\":1,\"type\":\"integer\"},\"state\":{\"enum\":[\"draft\",\"submitted\",\"applied\",\"cancelled\",\"rejected\"]},\"status\":{\"enum\":[\"draft\",\"awaiting-party\",\"in-review\",\"approved\",\"processing\",\"applied\",\"rejected\",\"cancelled\"]},\"submissionVersion\":{\"minimum\":0,\"type\":\"integer\"},\"title\":{\"maxLength\":1024,\"type\":\"string\"},\"turn\":{\"enum\":[\"party\",\"official\",\"nobody\"]}},\"required\":[\"id\",\"actionId\",\"actionRevision\",\"submissionVersion\",\"revision\",\"state\",\"turn\",\"links\"],\"type\":\"object\"}")], ["/paths/~1v1~1proposals~1{proposal_id}~1submit/post/responses/400/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"access-profile.ambiguous\",\"request.invalid\"]}},\"type\":\"object\"}]}")], ["/paths/~1v1~1proposals~1{proposal_id}~1submit/post/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}~1submit/post/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}~1submit/post/responses/403/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"profile.not-authorized\",\"proposal.subject-not-caller\"]}},\"type\":\"object\"}]}")], ["/paths/~1v1~1proposals~1{proposal_id}~1submit/post/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}~1submit/post/responses/409/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"idempotency.key-reused\",\"mutation.conflict\",\"proposal.rejected\"]}},\"type\":\"object\"}]}")], + ["/paths/~1v1~1proposals~1{proposal_id}~1submit/post/responses/409/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"idempotency.key-reused\",\"mutation.conflict\",\"proposal.rejected\",\"proposal.subject-changed\"]}},\"type\":\"object\"}]}")], ["/paths/~1v1~1proposals~1{proposal_id}~1submit/post/responses/410/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"idempotency.expired\"]}},\"type\":\"object\"}]}")], ["/paths/~1v1~1proposals~1{proposal_id}~1submit/post/responses/412/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"precondition.failed\"]}},\"type\":\"object\"}]}")], ["/paths/~1v1~1proposals~1{proposal_id}~1submit/post/responses/415/content/application~1problem+json/schema", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"enum\":[\"unsupported.media-type\"]}},\"type\":\"object\"}]}")], @@ -258,7 +260,7 @@ export class Client { if (!route) throw new TypeError("Unknown operation") return this.#transport.call(route, options) } - async proposals_listPage(options: Operations["proposals.list"]["input"] = {}, cursor?: string): Promise); "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); "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") })>) })>); "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); "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") })>> { + async proposals_listPage(options: Operations["proposals.list"]["input"] = {}, cursor?: string): Promise); "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") })>> { const { data } = await this.call("proposals.list", { ...options, query: cursor === undefined ? options.query : { ...options.query, cursor } }) return { items: data.items, nextCursor: data.nextCursor ?? null } } diff --git a/clients/typescript/generated/casework.ts b/clients/typescript/generated/casework.ts index e4831c55c0..89d00fe88b 100644 --- a/clients/typescript/generated/casework.ts +++ b/clients/typescript/generated/casework.ts @@ -1,5 +1,5 @@ // Generated for Stack version 0.52.0, client version 0.52.0. -// Source SHA-256 095bdd1b45a0e8031bb3d6cff6b2223514c250f14c985ca177abe6f8d18d9277 +// Source SHA-256 195bfdca62f16e84447145617876a65a104e70f4d96b3b3aa1c6a682be591041 // Unconstrained JSON /components/schemas/ReviewHistoryEntry/properties/detail // Unconstrained JSON /components/schemas/ReviewPolicy/properties/displaySchema // Unconstrained JSON /components/schemas/ReviewPolicy/properties/resultSchema @@ -56,7 +56,7 @@ export type Schema_InputHolidaySetDocument = ({ "dates": (Array<(string)>); "hol export type Schema_InputHumanIdentity = ({ "issuer": (string); "subject": (string) }) export type Schema_InputIssuerPrincipal = ({ "issuer": (string); "subject": (string) }) export type Schema_InputPolicySelection = ({ "digest"?: Schema_InputContentDigest; "id": (string); "version"?: (string) }) -export type Schema_InputReviewAskWant = (({ "kind": "answer" & (string) }) | ({ "kind": "document" & (string) })) +export type Schema_InputReviewAskWant = (({ "kind": "answer" & (string) }) | ({ "kind": "document" & (string) }) | ({ "form": (string); "kind": "form" & (string) })) export type Schema_InputReviewContext = (({ "mode": "submitted" & (string); "snapshot": (Record) }) | ({ "binding": Schema_InputSourceContextBinding; "mode": "current-source" & (string) })) export type Schema_InputReviewHistoryAudience = ("reviewers" | "requester") & (string) export type Schema_InputReviewRequestInclude = ("progress") & (string) @@ -98,6 +98,7 @@ export type Schema_ProblemRequestUnprocessable = (Schema_Problem & ({ "code"?: " export type Schema_ProblemRequestUnsupportedMediaType = (Schema_Problem & ({ "code"?: "request.unsupported-media-type"; "detail"?: "Send a JSON request body with Content-Type application/json."; "status"?: 415; "title"?: "Unsupported media type"; "type"?: "https://id.registrystack.org/problems/registry-casework/request/unsupported-media-type" })) export type Schema_ProblemReviewAskAlreadyOpen = (Schema_Problem & ({ "code"?: "review.ask-already-open"; "detail"?: "Wait for the open ask on this request to be answered or closed before asking again."; "status"?: 409; "title"?: "Review ask already open"; "type"?: "https://id.registrystack.org/problems/registry-casework/review/ask-already-open" })) export type Schema_ProblemReviewAskAnswerTimeInvalid = (Schema_Problem & ({ "code"?: "review.ask-answer-time-invalid"; "detail"?: "Report the time the applicant's answer was committed: not before the ask was made and no more than five minutes ahead of Casework's clock."; "status"?: 422; "title"?: "Review ask answer time invalid"; "type"?: "https://id.registrystack.org/problems/registry-casework/review/ask-answer-time-invalid" })) +export type Schema_ProblemReviewAskFormUnknown = (Schema_Problem & ({ "code"?: "review.ask-form-unknown"; "detail"?: "The review source does not declare the requested form."; "status"?: 422; "title"?: "Unknown review ask form"; "type"?: "https://id.registrystack.org/problems/registry-casework/review/ask-form-unknown" })) export type Schema_ProblemReviewAskLimitReached = (Schema_Problem & ({ "code"?: "review.ask-limit-reached"; "detail"?: "This review request has reached its limit of 50 asks. Continue the review without opening another ask."; "status"?: 409; "title"?: "Review ask limit reached"; "type"?: "https://id.registrystack.org/problems/registry-casework/review/ask-limit-reached" })) export type Schema_ProblemReviewAskNotOffered = (Schema_Problem & ({ "code"?: "review.ask-not-offered"; "detail"?: "The active stage of this review policy does not let a reviewer ask the applicant."; "status"?: 409; "title"?: "Review ask not offered"; "type"?: "https://id.registrystack.org/problems/registry-casework/review/ask-not-offered" })) export type Schema_ProblemReviewAskNotOpen = (Schema_Problem & ({ "code"?: "review.ask-not-open"; "detail"?: "This ask was already answered or closed, or the applicant answered after its due date."; "status"?: 409; "title"?: "Review ask not open"; "type"?: "https://id.registrystack.org/problems/registry-casework/review/ask-not-open" })) @@ -126,13 +127,14 @@ export type Schema_ReadyStatus = ({ "developmentSettings": (Array<({ "code": (st export type Schema_ReviewAccountabilityRecord = ({ "actor": Schema_IssuerPrincipal; "actorRef": (string); "decision": (string); "decisionReceipt"?: (Schema_ReviewDecisionReceipt | (null)); "eventId": (string); "occurredAt": (string); "privateReason"?: (string | null); "profileId": (string); "requestId": (string); "resultDigest"?: (string | null); "retainedUntil": (string); "taskId": (string) }) export type Schema_ReviewAnswerDocument = ({ "byteSize": (number); "contentType": (string); "download"?: (Schema_ReviewAnswerDownload | (null)); "id": (string); "sha256": (string); "verificationStatus"?: (string | null) }) export type Schema_ReviewAnswerDownload = ({ "accessProfile": (string); "method": (string); "operation": (string); "path": (string) }) +export type Schema_ReviewAnswerFormEntry = ({ "addedAt": (string); "contractChanged"?: (boolean); "id": (string); "input"?: (Record | null) }) export type Schema_ReviewAsk = ({ "answeredAt"?: (string | null); "askId": (string); "askedAt": (string); "closedAt"?: (string | null); "dueAt"?: (string | null); "requestId": (string); "state": Schema_ReviewAskState; "subject": Schema_SubjectBinding; "text": (string); "wants": (Array) }) export type Schema_ReviewAskAnswer = ({ "answeredAt": (string); "subject": Schema_InputSubjectBinding }) export type Schema_ReviewAskFeedEntry = ({ "askId": (string); "changedAt": (string); "eventId": (string); "requestId": (string) }) export type Schema_ReviewAskFeedPage = ({ "items": (Array); "nextCursor"?: (string | null) }) export type Schema_ReviewAskOnDue = ("return-to-reviewer") & (string) export type Schema_ReviewAskState = ("open" | "answered" | "expired" | "closed") & (string) -export type Schema_ReviewAskWant = (({ "kind": "answer" & (string) }) | ({ "kind": "document" & (string) })) +export type Schema_ReviewAskWant = (({ "kind": "answer" & (string) }) | ({ "kind": "document" & (string) }) | ({ "form": (string); "kind": "form" & (string) })) export type Schema_ReviewCancelRequest = ({ "reason": (string); "subject": Schema_InputSubjectBinding }) export type Schema_ReviewCancelResponse = (({ "outcome": "cancelled" & (string); "result": Schema_ReviewResult }) | ({ "outcome": "already-terminal" & (string); "result": Schema_ReviewResult })) export type Schema_ReviewCaseloadApplyRequest = ({ "previewId": (string) }) @@ -152,7 +154,7 @@ export type Schema_ReviewClockState = ("running" | "paused" | "completed" | "can export type Schema_ReviewCompletion = ({ "completedAt": (string); "eventId": (string); "requestId": (string); "resultId": (string); "type": Schema_ReviewCompletionType }) export type Schema_ReviewCompletionDestinationPolicy = ({ "destinationId": Schema_LocalId; "recipientBinding": (string) }) export type Schema_ReviewCompletionType = ("review.completed") & (string) -export type Schema_ReviewContextAnswer = ({ "answeredAt": (string); "documents": (Array); "text"?: (string | null) }) +export type Schema_ReviewContextAnswer = ({ "answeredAt": (string); "documents": (Array); "formEntries"?: (Array); "text"?: (string | null) }) export type Schema_ReviewContextAsk = ({ "answer"?: (Schema_ReviewContextAnswer | (null)); "answeredAt"?: (string | null); "askId": (string); "askedAt": (string); "dueAt"?: (string | null); "state": Schema_ReviewAskState; "taskId": (string); "text": (string); "wants": (Array) }) export type Schema_ReviewContextCapability = ("human-display" | "service-status" | "task-grant-context" | "routing-context") & (string) export type Schema_ReviewContextContract = ({ "id": Schema_ExternalId; "revision": Schema_ContentDigest; "schemaDigest": Schema_Digest }) @@ -191,10 +193,10 @@ export type Schema_ReviewSourceProjection = ({ "binding": Schema_SubjectBinding; export type Schema_ReviewStaffingQuery = ({ "cursor"?: (string | null); "limit"?: (number | null); "marker"?: (Schema_InputReviewTaskMarker | (null)); "ownership"?: (Schema_InputReviewTaskOwnership | (null)); "queue"?: (string | null); "reference"?: (string | null); "sort"?: Schema_InputReviewTaskSort; "subjectDigest"?: (Schema_InputContentDigest | (null)); "subjectId"?: (string | null); "subjectSource"?: (string | null); "subjectType"?: (string | null); "subjectVersion"?: (string | null) }) export type Schema_ReviewStageAsksPolicy = ({ "answerWithin"?: (Schema_ElapsedDuration | (null)); "onDue"?: Schema_ReviewAskOnDue; "pauseClocks"?: (boolean) }) export type Schema_ReviewStagePolicy = ({ "asks"?: (Schema_ReviewStageAsksPolicy | (null)); "decidingProfiles": (Array<(string)>); "excludeInitiator": (boolean); "excludePreviousStageReviewers": (boolean); "id": Schema_LocalId; "label"?: (Schema_DisplayText | (null)); "negativeDecisions"?: Schema_ReviewNegativeDecisionMode; "outcomes"?: (Array | null); "publicProgressCode"?: (Schema_ReviewProgressCode | (null)); "queue": (string); "requiredApprovals": (number) }) -export type Schema_ReviewTask = ({ "createdAt": (string); "deadlineAt": (string | null); "decidedByCaller"?: (boolean | null); "decisionReceipt"?: (Schema_ReviewDecisionReceipt | (null)); "displayReference"?: (string | null); "eligibleProfiles": (Array<(string)>); "marker"?: (Schema_ReviewTaskMarker | (null)); "queue": (string); "requestId": (string); "requesterReference": (string); "revision": (number); "staffingDiagnostic"?: Schema_StaffingDiagnostic; "stageId": (string); "stageIndex": (number); "state": Schema_ReviewTaskState; "subject": Schema_SubjectBinding; "taskId": (string) }) +export type Schema_ReviewTask = ({ "createdAt": (string); "deadlineAt": (string | null); "decidedByCaller"?: (boolean | null); "decisionReceipt"?: (Schema_ReviewDecisionReceipt | (null)); "displayReference"?: (string | null); "eligibleProfiles": (Array<(string)>); "marker"?: (Schema_ReviewTaskMarker | (null)); "queue": (string); "requestId": (string); "requesterReference": (string); "revision": (number); "staffingDiagnostic"?: Schema_StaffingDiagnostic; "stageId": (string); "stageIndex": (number); "state": Schema_ReviewTaskState; "subject": Schema_SubjectBinding; "taskId": (string); "unreadMessages"?: (number | null) }) export type Schema_ReviewTaskAskRequest = ({ "text": (string); "wants": (Array) }) export type Schema_ReviewTaskAsked = ({ "ask": Schema_ReviewAsk; "task": Schema_ReviewTask }) -export type Schema_ReviewTaskContext = ({ "asks"?: (Array); "context": Schema_ReviewTaskContextData; "policy": Schema_PolicyBinding; "policyClosure": Schema_ReviewPolicyClosure; "requestId": (string); "requesterReference": (string); "resultConstraints"?: JsonValue; "subject": Schema_SubjectBinding; "taskId": (string) }) +export type Schema_ReviewTaskContext = ({ "additionalForms"?: (Record); "asks"?: (Array); "context": Schema_ReviewTaskContextData; "messages"?: (Schema_SourceMessageThread | (null)); "policy": Schema_PolicyBinding; "policyClosure": Schema_ReviewPolicyClosure; "requestId": (string); "requesterReference": (string); "resultConstraints"?: JsonValue; "subject": Schema_SubjectBinding; "taskId": (string) }) export type Schema_ReviewTaskContextData = (({ "mode": "submitted" & (string); "snapshot": JsonValue }) | ({ "bindingStatus": Schema_ReviewSourceBindingStatus; "mode": "current-source" & (string); "projection"?: (Schema_ReviewSourceProjection | (null)); "reference": (string) })) export type Schema_ReviewTaskDecisionRequest = ({ "decision": Schema_InputDecisionKind }) export type Schema_ReviewTaskDraft = ({ "author": Schema_IssuerPrincipal; "body": JsonValue; "revision": (number); "taskId": (string); "updatedAt": (string) }) @@ -207,6 +209,12 @@ export type Schema_RoutingCondition = ({ "fields"?: (Record) })) export type Schema_RoutingRule = ({ "because": Schema_DisplayText; "id": Schema_LocalId; "label"?: (Schema_DisplayText | (null)); "queue": (string); "when": Schema_RoutingCondition }) export type Schema_SchedulingTaskPermission = ({ "actions": (Array<(string)>); "location": (string); "service": (string) }) +export type Schema_SourceMessage = ({ "from": Schema_SourceMessageSide; "id": (string); "mine": (boolean); "partyRole"?: (Schema_SourceMessagePartyRole | (null)); "sentAt": (string); "text"?: (string | null) }) +export type Schema_SourceMessageAvailability = ({ "available": (boolean); "observedRevision": (number); "reason"?: (string | null); "recovery"?: (string | null) }) +export type Schema_SourceMessageLink = ({ "accessProfile": (string); "availability": (Schema_SourceMessageAvailability | (null)); "ifMatch"?: (string | null); "method": (string); "operation": (string); "path": (string) }) +export type Schema_SourceMessagePartyRole = ("owner" | "subject") & (string) +export type Schema_SourceMessageSide = ("party" | "official") & (string) +export type Schema_SourceMessageThread = ({ "count": (number); "items"?: (Array | null); "lastSentAt"?: (string | null); "links"?: (Record | null); "unread": (number) }) export type Schema_StaffingDiagnostic = ("no-cover-available" | "insufficient-distinct-approvers") & (string) export type Schema_StageClockAnchor = ({ "type": Schema_StageClockAnchorType }) export type Schema_StageClockAnchorType = ("stage-entered") & (string) @@ -337,7 +345,7 @@ const rules: Record = Object.fromEntries([ ["/components/schemas/InputHumanIdentity", JSON.parse("{\"additionalProperties\":false,\"properties\":{\"issuer\":{\"type\":\"string\"},\"subject\":{\"type\":\"string\"}},\"required\":[\"issuer\",\"subject\"],\"type\":\"object\"}")], ["/components/schemas/InputIssuerPrincipal", JSON.parse("{\"additionalProperties\":false,\"properties\":{\"issuer\":{\"type\":\"string\"},\"subject\":{\"type\":\"string\"}},\"required\":[\"issuer\",\"subject\"],\"type\":\"object\"}")], ["/components/schemas/InputPolicySelection", JSON.parse("{\"additionalProperties\":false,\"dependentRequired\":{\"digest\":[\"version\"],\"version\":[\"digest\"]},\"properties\":{\"digest\":{\"$ref\":\"/components/schemas/InputContentDigest\"},\"id\":{\"type\":\"string\"},\"version\":{\"type\":\"string\"}},\"required\":[\"id\"],\"type\":\"object\"}")], - ["/components/schemas/InputReviewAskWant", JSON.parse("{\"oneOf\":[{\"additionalProperties\":false,\"properties\":{\"kind\":{\"const\":\"answer\",\"type\":\"string\"}},\"required\":[\"kind\"],\"type\":\"object\"},{\"additionalProperties\":false,\"properties\":{\"kind\":{\"const\":\"document\",\"type\":\"string\"}},\"required\":[\"kind\"],\"type\":\"object\"}]}")], + ["/components/schemas/InputReviewAskWant", JSON.parse("{\"oneOf\":[{\"additionalProperties\":false,\"properties\":{\"kind\":{\"const\":\"answer\",\"type\":\"string\"}},\"required\":[\"kind\"],\"type\":\"object\"},{\"additionalProperties\":false,\"properties\":{\"kind\":{\"const\":\"document\",\"type\":\"string\"}},\"required\":[\"kind\"],\"type\":\"object\"},{\"additionalProperties\":false,\"properties\":{\"form\":{\"pattern\":\"^[a-z][a-z0-9_-]{0,63}$\",\"type\":\"string\"},\"kind\":{\"const\":\"form\",\"type\":\"string\"}},\"required\":[\"kind\",\"form\"],\"type\":\"object\"}]}")], ["/components/schemas/InputReviewContext", JSON.parse("{\"oneOf\":[{\"additionalProperties\":false,\"properties\":{\"mode\":{\"const\":\"submitted\",\"type\":\"string\"},\"snapshot\":{\"additionalProperties\":true,\"type\":\"object\"}},\"required\":[\"mode\",\"snapshot\"],\"type\":\"object\"},{\"additionalProperties\":false,\"properties\":{\"binding\":{\"$ref\":\"/components/schemas/InputSourceContextBinding\"},\"mode\":{\"const\":\"current-source\",\"type\":\"string\"}},\"required\":[\"mode\",\"binding\"],\"type\":\"object\"}]}")], ["/components/schemas/InputReviewHistoryAudience", JSON.parse("{\"enum\":[\"reviewers\",\"requester\"],\"type\":\"string\"}")], ["/components/schemas/InputReviewRequestInclude", JSON.parse("{\"enum\":[\"progress\"],\"type\":\"string\"}")], @@ -377,6 +385,7 @@ const rules: Record = Object.fromEntries([ ["/components/schemas/ProblemRequestUnsupportedMediaType", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"const\":\"request.unsupported-media-type\"},\"detail\":{\"const\":\"Send a JSON request body with Content-Type application/json.\"},\"status\":{\"const\":415},\"title\":{\"const\":\"Unsupported media type\"},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-casework/request/unsupported-media-type\"}}}]}")], ["/components/schemas/ProblemReviewAskAlreadyOpen", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"const\":\"review.ask-already-open\"},\"detail\":{\"const\":\"Wait for the open ask on this request to be answered or closed before asking again.\"},\"status\":{\"const\":409},\"title\":{\"const\":\"Review ask already open\"},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-casework/review/ask-already-open\"}}}]}")], ["/components/schemas/ProblemReviewAskAnswerTimeInvalid", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"const\":\"review.ask-answer-time-invalid\"},\"detail\":{\"const\":\"Report the time the applicant's answer was committed: not before the ask was made and no more than five minutes ahead of Casework's clock.\"},\"status\":{\"const\":422},\"title\":{\"const\":\"Review ask answer time invalid\"},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-casework/review/ask-answer-time-invalid\"}}}]}")], + ["/components/schemas/ProblemReviewAskFormUnknown", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"const\":\"review.ask-form-unknown\"},\"detail\":{\"const\":\"The review source does not declare the requested form.\"},\"status\":{\"const\":422},\"title\":{\"const\":\"Unknown review ask form\"},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-casework/review/ask-form-unknown\"}}}]}")], ["/components/schemas/ProblemReviewAskLimitReached", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"const\":\"review.ask-limit-reached\"},\"detail\":{\"const\":\"This review request has reached its limit of 50 asks. Continue the review without opening another ask.\"},\"status\":{\"const\":409},\"title\":{\"const\":\"Review ask limit reached\"},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-casework/review/ask-limit-reached\"}}}]}")], ["/components/schemas/ProblemReviewAskNotOffered", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"const\":\"review.ask-not-offered\"},\"detail\":{\"const\":\"The active stage of this review policy does not let a reviewer ask the applicant.\"},\"status\":{\"const\":409},\"title\":{\"const\":\"Review ask not offered\"},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-casework/review/ask-not-offered\"}}}]}")], ["/components/schemas/ProblemReviewAskNotOpen", JSON.parse("{\"allOf\":[{\"$ref\":\"/components/schemas/Problem\"},{\"properties\":{\"code\":{\"const\":\"review.ask-not-open\"},\"detail\":{\"const\":\"This ask was already answered or closed, or the applicant answered after its due date.\"},\"status\":{\"const\":409},\"title\":{\"const\":\"Review ask not open\"},\"type\":{\"const\":\"https://id.registrystack.org/problems/registry-casework/review/ask-not-open\"}}}]}")], @@ -404,13 +413,14 @@ const rules: Record = Object.fromEntries([ ["/components/schemas/ReviewAccountabilityRecord", JSON.parse("{\"additionalProperties\":false,\"properties\":{\"actor\":{\"$ref\":\"/components/schemas/IssuerPrincipal\"},\"actorRef\":{\"type\":\"string\"},\"decision\":{\"type\":\"string\"},\"decisionReceipt\":{\"anyOf\":[{\"$ref\":\"/components/schemas/ReviewDecisionReceipt\"},{\"type\":\"null\"}]},\"eventId\":{\"type\":\"string\"},\"occurredAt\":{\"type\":\"string\"},\"privateReason\":{\"type\":[\"string\",\"null\"]},\"profileId\":{\"type\":\"string\"},\"requestId\":{\"type\":\"string\"},\"resultDigest\":{\"type\":[\"string\",\"null\"]},\"retainedUntil\":{\"type\":\"string\"},\"taskId\":{\"type\":\"string\"}},\"required\":[\"eventId\",\"requestId\",\"taskId\",\"actorRef\",\"actor\",\"profileId\",\"decision\",\"occurredAt\",\"retainedUntil\"],\"type\":\"object\"}")], ["/components/schemas/ReviewAnswerDocument", JSON.parse("{\"additionalProperties\":false,\"properties\":{\"byteSize\":{\"minimum\":0,\"type\":\"integer\"},\"contentType\":{\"type\":\"string\"},\"download\":{\"anyOf\":[{\"$ref\":\"/components/schemas/ReviewAnswerDownload\"},{\"type\":\"null\"}]},\"id\":{\"type\":\"string\"},\"sha256\":{\"pattern\":\"^[0-9a-f]{64}$\",\"type\":\"string\"},\"verificationStatus\":{\"type\":[\"string\",\"null\"]}},\"required\":[\"id\",\"sha256\",\"contentType\",\"byteSize\"],\"type\":\"object\"}")], ["/components/schemas/ReviewAnswerDownload", JSON.parse("{\"additionalProperties\":false,\"properties\":{\"accessProfile\":{\"type\":\"string\"},\"method\":{\"pattern\":\"^GET$\",\"type\":\"string\"},\"operation\":{\"type\":\"string\"},\"path\":{\"type\":\"string\"}},\"required\":[\"method\",\"operation\",\"accessProfile\",\"path\"],\"type\":\"object\"}")], + ["/components/schemas/ReviewAnswerFormEntry", JSON.parse("{\"additionalProperties\":false,\"properties\":{\"addedAt\":{\"type\":\"string\"},\"contractChanged\":{\"type\":\"boolean\"},\"id\":{\"type\":\"string\"},\"input\":{\"additionalProperties\":true,\"type\":[\"object\",\"null\"]}},\"required\":[\"id\",\"addedAt\"],\"type\":\"object\"}")], ["/components/schemas/ReviewAsk", JSON.parse("{\"additionalProperties\":false,\"properties\":{\"answeredAt\":{\"type\":[\"string\",\"null\"]},\"askId\":{\"type\":\"string\"},\"askedAt\":{\"type\":\"string\"},\"closedAt\":{\"type\":[\"string\",\"null\"]},\"dueAt\":{\"type\":[\"string\",\"null\"]},\"requestId\":{\"type\":\"string\"},\"state\":{\"$ref\":\"/components/schemas/ReviewAskState\"},\"subject\":{\"$ref\":\"/components/schemas/SubjectBinding\"},\"text\":{\"maxLength\":2000,\"minLength\":1,\"type\":\"string\"},\"wants\":{\"items\":{\"$ref\":\"/components/schemas/ReviewAskWant\"},\"maxItems\":8,\"type\":\"array\",\"uniqueItems\":true}},\"required\":[\"askId\",\"requestId\",\"subject\",\"text\",\"wants\",\"askedAt\",\"state\"],\"type\":\"object\"}")], ["/components/schemas/ReviewAskAnswer", JSON.parse("{\"additionalProperties\":false,\"properties\":{\"answeredAt\":{\"type\":\"string\"},\"subject\":{\"$ref\":\"/components/schemas/InputSubjectBinding\"}},\"required\":[\"subject\",\"answeredAt\"],\"type\":\"object\"}")], ["/components/schemas/ReviewAskFeedEntry", JSON.parse("{\"additionalProperties\":false,\"properties\":{\"askId\":{\"type\":\"string\"},\"changedAt\":{\"type\":\"string\"},\"eventId\":{\"type\":\"string\"},\"requestId\":{\"type\":\"string\"}},\"required\":[\"eventId\",\"requestId\",\"askId\",\"changedAt\"],\"type\":\"object\"}")], ["/components/schemas/ReviewAskFeedPage", JSON.parse("{\"additionalProperties\":false,\"properties\":{\"items\":{\"items\":{\"$ref\":\"/components/schemas/ReviewAskFeedEntry\"},\"type\":\"array\"},\"nextCursor\":{\"type\":[\"string\",\"null\"]}},\"required\":[\"items\"],\"type\":\"object\"}")], ["/components/schemas/ReviewAskOnDue", JSON.parse("{\"enum\":[\"return-to-reviewer\"],\"type\":\"string\"}")], ["/components/schemas/ReviewAskState", JSON.parse("{\"enum\":[\"open\",\"answered\",\"expired\",\"closed\"],\"type\":\"string\"}")], - ["/components/schemas/ReviewAskWant", JSON.parse("{\"oneOf\":[{\"additionalProperties\":false,\"properties\":{\"kind\":{\"const\":\"answer\",\"type\":\"string\"}},\"required\":[\"kind\"],\"type\":\"object\"},{\"additionalProperties\":false,\"properties\":{\"kind\":{\"const\":\"document\",\"type\":\"string\"}},\"required\":[\"kind\"],\"type\":\"object\"}]}")], + ["/components/schemas/ReviewAskWant", JSON.parse("{\"oneOf\":[{\"additionalProperties\":false,\"properties\":{\"kind\":{\"const\":\"answer\",\"type\":\"string\"}},\"required\":[\"kind\"],\"type\":\"object\"},{\"additionalProperties\":false,\"properties\":{\"kind\":{\"const\":\"document\",\"type\":\"string\"}},\"required\":[\"kind\"],\"type\":\"object\"},{\"additionalProperties\":false,\"properties\":{\"form\":{\"pattern\":\"^[a-z][a-z0-9_-]{0,63}$\",\"type\":\"string\"},\"kind\":{\"const\":\"form\",\"type\":\"string\"}},\"required\":[\"kind\",\"form\"],\"type\":\"object\"}]}")], ["/components/schemas/ReviewCancelRequest", JSON.parse("{\"additionalProperties\":false,\"properties\":{\"reason\":{\"type\":\"string\"},\"subject\":{\"$ref\":\"/components/schemas/InputSubjectBinding\"}},\"required\":[\"subject\",\"reason\"],\"type\":\"object\"}")], ["/components/schemas/ReviewCancelResponse", JSON.parse("{\"oneOf\":[{\"additionalProperties\":false,\"properties\":{\"outcome\":{\"const\":\"cancelled\",\"type\":\"string\"},\"result\":{\"$ref\":\"/components/schemas/ReviewResult\"}},\"required\":[\"outcome\",\"result\"],\"type\":\"object\"},{\"additionalProperties\":false,\"properties\":{\"outcome\":{\"const\":\"already-terminal\",\"type\":\"string\"},\"result\":{\"$ref\":\"/components/schemas/ReviewResult\"}},\"required\":[\"outcome\",\"result\"],\"type\":\"object\"}]}")], ["/components/schemas/ReviewCaseloadApplyRequest", JSON.parse("{\"additionalProperties\":false,\"properties\":{\"previewId\":{\"type\":\"string\"}},\"required\":[\"previewId\"],\"type\":\"object\"}")], @@ -429,7 +439,7 @@ const rules: Record = Object.fromEntries([ ["/components/schemas/ReviewClockState", JSON.parse("{\"enum\":[\"running\",\"paused\",\"completed\",\"cancelled\",\"source-facts-missing\"],\"type\":\"string\"}")], ["/components/schemas/ReviewCompletionDestinationPolicy", JSON.parse("{\"additionalProperties\":false,\"properties\":{\"destinationId\":{\"$ref\":\"/components/schemas/LocalId\"},\"recipientBinding\":{\"type\":\"string\"}},\"required\":[\"destinationId\",\"recipientBinding\"],\"type\":\"object\"}")], ["/components/schemas/ReviewCompletionType", JSON.parse("{\"enum\":[\"review.completed\"],\"type\":\"string\"}")], - ["/components/schemas/ReviewContextAnswer", JSON.parse("{\"additionalProperties\":false,\"properties\":{\"answeredAt\":{\"type\":\"string\"},\"documents\":{\"items\":{\"$ref\":\"/components/schemas/ReviewAnswerDocument\"},\"maxItems\":32,\"type\":\"array\"},\"text\":{\"maxLength\":2000,\"type\":[\"string\",\"null\"]}},\"required\":[\"documents\",\"answeredAt\"],\"type\":\"object\"}")], + ["/components/schemas/ReviewContextAnswer", JSON.parse("{\"additionalProperties\":false,\"properties\":{\"answeredAt\":{\"type\":\"string\"},\"documents\":{\"items\":{\"$ref\":\"/components/schemas/ReviewAnswerDocument\"},\"maxItems\":32,\"type\":\"array\"},\"formEntries\":{\"items\":{\"$ref\":\"/components/schemas/ReviewAnswerFormEntry\"},\"maxItems\":32,\"type\":\"array\"},\"text\":{\"maxLength\":2000,\"type\":[\"string\",\"null\"]}},\"required\":[\"documents\",\"answeredAt\"],\"type\":\"object\"}")], ["/components/schemas/ReviewContextAsk", JSON.parse("{\"additionalProperties\":false,\"properties\":{\"answer\":{\"anyOf\":[{\"$ref\":\"/components/schemas/ReviewContextAnswer\"},{\"type\":\"null\"}]},\"answeredAt\":{\"type\":[\"string\",\"null\"]},\"askId\":{\"type\":\"string\"},\"askedAt\":{\"type\":\"string\"},\"dueAt\":{\"type\":[\"string\",\"null\"]},\"state\":{\"$ref\":\"/components/schemas/ReviewAskState\"},\"taskId\":{\"type\":\"string\"},\"text\":{\"type\":\"string\"},\"wants\":{\"items\":{\"$ref\":\"/components/schemas/ReviewAskWant\"},\"type\":\"array\"}},\"required\":[\"askId\",\"taskId\",\"text\",\"wants\",\"askedAt\",\"state\"],\"type\":\"object\"}")], ["/components/schemas/ReviewContextCapability", JSON.parse("{\"enum\":[\"human-display\",\"service-status\",\"task-grant-context\",\"routing-context\"],\"type\":\"string\"}")], ["/components/schemas/ReviewContextContract", JSON.parse("{\"additionalProperties\":false,\"properties\":{\"id\":{\"$ref\":\"/components/schemas/ExternalId\",\"maxLength\":256,\"pattern\":\"\\\\S\"},\"revision\":{\"$ref\":\"/components/schemas/ContentDigest\"},\"schemaDigest\":{\"$ref\":\"/components/schemas/Digest\"}},\"required\":[\"id\",\"revision\",\"schemaDigest\"],\"type\":\"object\"}")], @@ -466,10 +476,10 @@ const rules: Record = Object.fromEntries([ ["/components/schemas/ReviewSourceProjection", JSON.parse("{\"additionalProperties\":false,\"properties\":{\"binding\":{\"$ref\":\"/components/schemas/SubjectBinding\"},\"display\":{\"additionalProperties\":true,\"type\":\"object\"},\"displayReference\":{\"type\":[\"string\",\"null\"]}},\"required\":[\"binding\",\"display\"],\"type\":\"object\"}")], ["/components/schemas/ReviewStageAsksPolicy", JSON.parse("{\"additionalProperties\":false,\"allOf\":[{\"if\":{\"properties\":{\"pauseClocks\":{\"const\":true}},\"required\":[\"pauseClocks\"]},\"then\":{\"required\":[\"answerWithin\"]}}],\"properties\":{\"answerWithin\":{\"anyOf\":[{\"$ref\":\"/components/schemas/ElapsedDuration\"},{\"type\":\"null\"}]},\"onDue\":{\"$ref\":\"/components/schemas/ReviewAskOnDue\"},\"pauseClocks\":{\"type\":\"boolean\"}},\"type\":\"object\"}")], ["/components/schemas/ReviewStagePolicy", JSON.parse("{\"additionalProperties\":false,\"properties\":{\"asks\":{\"anyOf\":[{\"$ref\":\"/components/schemas/ReviewStageAsksPolicy\"},{\"type\":\"null\"}]},\"decidingProfiles\":{\"items\":{\"type\":\"string\"},\"type\":\"array\"},\"excludeInitiator\":{\"type\":\"boolean\"},\"excludePreviousStageReviewers\":{\"type\":\"boolean\"},\"id\":{\"$ref\":\"/components/schemas/LocalId\"},\"label\":{\"anyOf\":[{\"$ref\":\"/components/schemas/DisplayText\"},{\"type\":\"null\"}]},\"negativeDecisions\":{\"$ref\":\"/components/schemas/ReviewNegativeDecisionMode\"},\"outcomes\":{\"items\":{\"$ref\":\"/components/schemas/LocalId\"},\"minItems\":1,\"type\":[\"array\",\"null\"],\"uniqueItems\":true},\"publicProgressCode\":{\"anyOf\":[{\"$ref\":\"/components/schemas/ReviewProgressCode\"},{\"type\":\"null\"}]},\"queue\":{\"type\":\"string\"},\"requiredApprovals\":{\"maximum\":32,\"minimum\":1,\"type\":\"integer\"}},\"required\":[\"id\",\"queue\",\"decidingProfiles\",\"requiredApprovals\",\"excludeInitiator\",\"excludePreviousStageReviewers\"],\"type\":\"object\"}")], - ["/components/schemas/ReviewTask", JSON.parse("{\"additionalProperties\":false,\"properties\":{\"createdAt\":{\"type\":\"string\"},\"deadlineAt\":{\"type\":[\"string\",\"null\"]},\"decidedByCaller\":{\"type\":[\"boolean\",\"null\"]},\"decisionReceipt\":{\"anyOf\":[{\"$ref\":\"/components/schemas/ReviewDecisionReceipt\"},{\"type\":\"null\"}]},\"displayReference\":{\"type\":[\"string\",\"null\"]},\"eligibleProfiles\":{\"items\":{\"type\":\"string\"},\"type\":\"array\"},\"marker\":{\"anyOf\":[{\"$ref\":\"/components/schemas/ReviewTaskMarker\"},{\"type\":\"null\"}]},\"queue\":{\"type\":\"string\"},\"requestId\":{\"type\":\"string\"},\"requesterReference\":{\"type\":\"string\"},\"revision\":{\"type\":\"integer\"},\"staffingDiagnostic\":{\"$ref\":\"/components/schemas/StaffingDiagnostic\"},\"stageId\":{\"type\":\"string\"},\"stageIndex\":{\"maximum\":65535,\"minimum\":0,\"type\":\"integer\"},\"state\":{\"$ref\":\"/components/schemas/ReviewTaskState\"},\"subject\":{\"$ref\":\"/components/schemas/SubjectBinding\"},\"taskId\":{\"type\":\"string\"}},\"required\":[\"subject\",\"requesterReference\",\"deadlineAt\",\"createdAt\",\"taskId\",\"requestId\",\"stageIndex\",\"stageId\",\"queue\",\"revision\",\"eligibleProfiles\",\"state\"],\"type\":\"object\"}")], + ["/components/schemas/ReviewTask", JSON.parse("{\"additionalProperties\":false,\"properties\":{\"createdAt\":{\"type\":\"string\"},\"deadlineAt\":{\"type\":[\"string\",\"null\"]},\"decidedByCaller\":{\"type\":[\"boolean\",\"null\"]},\"decisionReceipt\":{\"anyOf\":[{\"$ref\":\"/components/schemas/ReviewDecisionReceipt\"},{\"type\":\"null\"}]},\"displayReference\":{\"type\":[\"string\",\"null\"]},\"eligibleProfiles\":{\"items\":{\"type\":\"string\"},\"type\":\"array\"},\"marker\":{\"anyOf\":[{\"$ref\":\"/components/schemas/ReviewTaskMarker\"},{\"type\":\"null\"}]},\"queue\":{\"type\":\"string\"},\"requestId\":{\"type\":\"string\"},\"requesterReference\":{\"type\":\"string\"},\"revision\":{\"type\":\"integer\"},\"staffingDiagnostic\":{\"$ref\":\"/components/schemas/StaffingDiagnostic\"},\"stageId\":{\"type\":\"string\"},\"stageIndex\":{\"maximum\":65535,\"minimum\":0,\"type\":\"integer\"},\"state\":{\"$ref\":\"/components/schemas/ReviewTaskState\"},\"subject\":{\"$ref\":\"/components/schemas/SubjectBinding\"},\"taskId\":{\"type\":\"string\"},\"unreadMessages\":{\"minimum\":0,\"type\":[\"integer\",\"null\"]}},\"required\":[\"subject\",\"requesterReference\",\"deadlineAt\",\"createdAt\",\"taskId\",\"requestId\",\"stageIndex\",\"stageId\",\"queue\",\"revision\",\"eligibleProfiles\",\"state\"],\"type\":\"object\"}")], ["/components/schemas/ReviewTaskAskRequest", JSON.parse("{\"additionalProperties\":false,\"properties\":{\"text\":{\"maxLength\":2000,\"minLength\":1,\"type\":\"string\"},\"wants\":{\"items\":{\"$ref\":\"/components/schemas/InputReviewAskWant\"},\"maxItems\":8,\"type\":\"array\"}},\"required\":[\"text\",\"wants\"],\"type\":\"object\"}")], ["/components/schemas/ReviewTaskAsked", JSON.parse("{\"additionalProperties\":false,\"properties\":{\"ask\":{\"$ref\":\"/components/schemas/ReviewAsk\"},\"task\":{\"$ref\":\"/components/schemas/ReviewTask\"}},\"required\":[\"task\",\"ask\"],\"type\":\"object\"}")], - ["/components/schemas/ReviewTaskContext", JSON.parse("{\"additionalProperties\":false,\"properties\":{\"asks\":{\"items\":{\"$ref\":\"/components/schemas/ReviewContextAsk\"},\"type\":\"array\"},\"context\":{\"$ref\":\"/components/schemas/ReviewTaskContextData\"},\"policy\":{\"$ref\":\"/components/schemas/PolicyBinding\"},\"policyClosure\":{\"$ref\":\"/components/schemas/ReviewPolicyClosure\"},\"requestId\":{\"type\":\"string\"},\"requesterReference\":{\"type\":\"string\"},\"resultConstraints\":true,\"subject\":{\"$ref\":\"/components/schemas/SubjectBinding\"},\"taskId\":{\"type\":\"string\"}},\"required\":[\"taskId\",\"requestId\",\"subject\",\"requesterReference\",\"policy\",\"policyClosure\",\"context\"],\"type\":\"object\"}")], + ["/components/schemas/ReviewTaskContext", JSON.parse("{\"additionalProperties\":false,\"properties\":{\"additionalForms\":{\"additionalProperties\":{\"type\":\"string\"},\"type\":\"object\"},\"asks\":{\"items\":{\"$ref\":\"/components/schemas/ReviewContextAsk\"},\"type\":\"array\"},\"context\":{\"$ref\":\"/components/schemas/ReviewTaskContextData\"},\"messages\":{\"anyOf\":[{\"$ref\":\"/components/schemas/SourceMessageThread\"},{\"type\":\"null\"}]},\"policy\":{\"$ref\":\"/components/schemas/PolicyBinding\"},\"policyClosure\":{\"$ref\":\"/components/schemas/ReviewPolicyClosure\"},\"requestId\":{\"type\":\"string\"},\"requesterReference\":{\"type\":\"string\"},\"resultConstraints\":true,\"subject\":{\"$ref\":\"/components/schemas/SubjectBinding\"},\"taskId\":{\"type\":\"string\"}},\"required\":[\"taskId\",\"requestId\",\"subject\",\"requesterReference\",\"policy\",\"policyClosure\",\"context\"],\"type\":\"object\"}")], ["/components/schemas/ReviewTaskContextData", JSON.parse("{\"oneOf\":[{\"additionalProperties\":false,\"properties\":{\"mode\":{\"const\":\"submitted\",\"type\":\"string\"},\"snapshot\":true},\"required\":[\"mode\",\"snapshot\"],\"type\":\"object\"},{\"additionalProperties\":false,\"properties\":{\"bindingStatus\":{\"$ref\":\"/components/schemas/ReviewSourceBindingStatus\"},\"mode\":{\"const\":\"current-source\",\"type\":\"string\"},\"projection\":{\"anyOf\":[{\"$ref\":\"/components/schemas/ReviewSourceProjection\"},{\"type\":\"null\"}]},\"reference\":{\"type\":\"string\"}},\"required\":[\"mode\",\"reference\",\"bindingStatus\"],\"type\":\"object\"}]}")], ["/components/schemas/ReviewTaskDecisionRequest", JSON.parse("{\"additionalProperties\":false,\"properties\":{\"decision\":{\"$ref\":\"/components/schemas/InputDecisionKind\"}},\"required\":[\"decision\"],\"type\":\"object\"}")], ["/components/schemas/ReviewTaskDraft", JSON.parse("{\"additionalProperties\":false,\"properties\":{\"author\":{\"$ref\":\"/components/schemas/IssuerPrincipal\"},\"body\":true,\"revision\":{\"type\":\"integer\"},\"taskId\":{\"type\":\"string\"},\"updatedAt\":{\"type\":\"string\"}},\"required\":[\"taskId\",\"author\",\"body\",\"revision\",\"updatedAt\"],\"type\":\"object\"}")], @@ -481,6 +491,12 @@ const rules: Record = Object.fromEntries([ ["/components/schemas/RoutingPredicate", JSON.parse("{\"oneOf\":[{\"additionalProperties\":false,\"properties\":{\"equals\":true},\"required\":[\"equals\"],\"type\":\"object\"},{\"additionalProperties\":false,\"properties\":{\"oneOf\":{\"items\":true,\"type\":\"array\"}},\"required\":[\"oneOf\"],\"type\":\"object\"}]}")], ["/components/schemas/RoutingRule", JSON.parse("{\"additionalProperties\":false,\"properties\":{\"because\":{\"$ref\":\"/components/schemas/DisplayText\"},\"id\":{\"$ref\":\"/components/schemas/LocalId\"},\"label\":{\"anyOf\":[{\"$ref\":\"/components/schemas/DisplayText\"},{\"type\":\"null\"}]},\"queue\":{\"type\":\"string\"},\"when\":{\"$ref\":\"/components/schemas/RoutingCondition\"}},\"required\":[\"id\",\"because\",\"when\",\"queue\"],\"type\":\"object\"}")], ["/components/schemas/SchedulingTaskPermission", JSON.parse("{\"additionalProperties\":false,\"properties\":{\"actions\":{\"items\":{\"type\":\"string\"},\"type\":\"array\"},\"location\":{\"type\":\"string\"},\"service\":{\"type\":\"string\"}},\"required\":[\"service\",\"location\",\"actions\"],\"type\":\"object\"}")], + ["/components/schemas/SourceMessage", JSON.parse("{\"additionalProperties\":false,\"properties\":{\"from\":{\"$ref\":\"/components/schemas/SourceMessageSide\"},\"id\":{\"type\":\"string\"},\"mine\":{\"type\":\"boolean\"},\"partyRole\":{\"anyOf\":[{\"$ref\":\"/components/schemas/SourceMessagePartyRole\"},{\"type\":\"null\"}]},\"sentAt\":{\"type\":\"string\"},\"text\":{\"type\":[\"string\",\"null\"]}},\"required\":[\"id\",\"from\",\"mine\",\"sentAt\"],\"type\":\"object\"}")], + ["/components/schemas/SourceMessageAvailability", JSON.parse("{\"additionalProperties\":false,\"properties\":{\"available\":{\"type\":\"boolean\"},\"observedRevision\":{\"minimum\":0,\"type\":\"integer\"},\"reason\":{\"type\":[\"string\",\"null\"]},\"recovery\":{\"type\":[\"string\",\"null\"]}},\"required\":[\"available\",\"observedRevision\"],\"type\":\"object\"}")], + ["/components/schemas/SourceMessageLink", JSON.parse("{\"additionalProperties\":false,\"properties\":{\"accessProfile\":{\"type\":\"string\"},\"availability\":{\"anyOf\":[{\"$ref\":\"/components/schemas/SourceMessageAvailability\"},{\"type\":\"null\"}]},\"ifMatch\":{\"type\":[\"string\",\"null\"]},\"method\":{\"type\":\"string\"},\"operation\":{\"type\":\"string\"},\"path\":{\"type\":\"string\"}},\"required\":[\"method\",\"path\",\"accessProfile\",\"operation\",\"availability\"],\"type\":\"object\"}")], + ["/components/schemas/SourceMessagePartyRole", JSON.parse("{\"enum\":[\"owner\",\"subject\"],\"type\":\"string\"}")], + ["/components/schemas/SourceMessageSide", JSON.parse("{\"enum\":[\"party\",\"official\"],\"type\":\"string\"}")], + ["/components/schemas/SourceMessageThread", JSON.parse("{\"additionalProperties\":false,\"properties\":{\"count\":{\"maximum\":65535,\"minimum\":0,\"type\":\"integer\"},\"items\":{\"items\":{\"$ref\":\"/components/schemas/SourceMessage\"},\"type\":[\"array\",\"null\"]},\"lastSentAt\":{\"type\":[\"string\",\"null\"]},\"links\":{\"additionalProperties\":{\"$ref\":\"/components/schemas/SourceMessageLink\"},\"type\":[\"object\",\"null\"]},\"unread\":{\"maximum\":65535,\"minimum\":0,\"type\":\"integer\"}},\"required\":[\"count\",\"unread\"],\"type\":\"object\"}")], ["/components/schemas/StaffingDiagnostic", JSON.parse("{\"enum\":[\"no-cover-available\",\"insufficient-distinct-approvers\"],\"type\":\"string\"}")], ["/components/schemas/StageClockAnchor", JSON.parse("{\"additionalProperties\":false,\"properties\":{\"type\":{\"$ref\":\"/components/schemas/StageClockAnchorType\"}},\"required\":[\"type\"],\"type\":\"object\"}")], ["/components/schemas/StageClockAnchorType", JSON.parse("{\"enum\":[\"stage-entered\"],\"type\":\"string\"}")], @@ -1021,7 +1037,7 @@ const rules: Record = Object.fromEntries([ ["/paths/~1v1~1review-tasks~1{taskId}~1asks/post/responses/412/content/application~1problem+json/schema", JSON.parse("{\"$ref\":\"/components/schemas/ProblemPreconditionFailed\"}")], ["/paths/~1v1~1review-tasks~1{taskId}~1asks/post/responses/413/content/application~1problem+json/schema", JSON.parse("{\"$ref\":\"/components/schemas/ProblemRequestBodyTooLarge\"}")], ["/paths/~1v1~1review-tasks~1{taskId}~1asks/post/responses/415/content/application~1problem+json/schema", JSON.parse("{\"$ref\":\"/components/schemas/ProblemRequestUnsupportedMediaType\"}")], - ["/paths/~1v1~1review-tasks~1{taskId}~1asks/post/responses/422/content/application~1problem+json/schema", JSON.parse("{\"$ref\":\"/components/schemas/ProblemRequestUnprocessable\"}")], + ["/paths/~1v1~1review-tasks~1{taskId}~1asks/post/responses/422/content/application~1problem+json/schema", JSON.parse("{\"oneOf\":[{\"$ref\":\"/components/schemas/ProblemRequestUnprocessable\"},{\"$ref\":\"/components/schemas/ProblemReviewAskFormUnknown\"}]}")], ["/paths/~1v1~1review-tasks~1{taskId}~1asks/post/responses/428/content/application~1problem+json/schema", JSON.parse("{\"$ref\":\"/components/schemas/ProblemPreconditionRequired\"}")], ["/paths/~1v1~1review-tasks~1{taskId}~1asks/post/responses/500/content/application~1problem+json/schema", JSON.parse("{\"$ref\":\"/components/schemas/ProblemRuntimeFailure\"}")], ["/paths/~1v1~1review-tasks~1{taskId}~1asks/post/responses/502/content/application~1problem+json/schema", JSON.parse("{\"oneOf\":[{\"$ref\":\"/components/schemas/ProblemSourceBadGateway\"},{\"$ref\":\"/components/schemas/ProblemSourceVersionMismatch\"},{\"$ref\":\"/components/schemas/ProblemSourceVersionUnavailable\"}]}")], 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/casework.test.ts b/clients/typescript/tests/casework.test.ts index cdf5d1d2cf..39d0f3d676 100644 --- a/clients/typescript/tests/casework.test.ts +++ b/clients/typescript/tests/casework.test.ts @@ -78,3 +78,45 @@ test('Casework returns an empty pending answer and rejects an undeclared bare st assert.equal(data, undefined) await assert.rejects(client(410).call('getReviewAsk', { path: ask }), { kind: 'unexpected', status: 410 }) }) + +test('Casework accepts source threads with absent optional fields and still requires message identity', async () => { + const digest = 'sha256:' + '0'.repeat(64) + const policy = { id: 'address-review', version: '1', digest } + const taskContext = { + taskId: id, requestId: id, requesterReference: 'case-1', policy, + subject: { id, source: 'registry', type: 'proposal', version: '1', digest }, + context: { mode: 'current-source', reference: 'proposal-ref', bindingStatus: 'current' }, + policyClosure: { + identity: policy, purpose: 'approval', stages: [], displaySchema: { type: 'object' }, + context: { mode: 'current-source', provider: 'registry', contract: { id: 'context', revision: digest, schemaDigest: digest } }, + retention: { terminalRetentionDays: 30, accountabilityRetentionDays: 30 }, + dependencies: { + accessProfiles: [], queues: [], teams: [], clocks: [], calendars: [], + contextProvider: null, taskTemplates: [], trustedProducers: [], + inbox: { defaultPageSize: 25, maximumCandidateScan: 100, maximumSourceReads: 25, + maximumConcurrentSourceReads: 4, pageDeadlineMilliseconds: 2000 }, + }, + }, + } + const sentAt = '2026-12-01T10:00:00.000000Z' + const official = { id, from: 'official', mine: true, sentAt, text: 'Received' } + const erased = { id: '00000000-0000-4000-8000-000000000002', from: 'party', partyRole: 'owner', mine: false, sentAt } + const link = { path: '/v1/proposals/' + id + '/messages', accessProfile: 'reviewer', operation: 'message' } + const availability = { available: true, observedRevision: 2 } + const links = { + message: { ...link, method: 'POST', ifMatch: '"proposal-2"', availability }, + markRead: { ...link, method: 'POST', path: link.path + '/read', availability }, + list: { ...link, method: 'GET', availability }, + } + const readContext = (messages: unknown) => client(200, JSON.stringify({ ...taskContext, messages }), + { 'content-type': 'application/json', traceparent }).call('getReviewTaskContext', { path: { taskId: id } }) + + const thread = { count: 2, unread: 1, lastSentAt: sentAt, items: [erased, official], links } + assert.equal((await readContext(undefined)).data.messages, undefined) + for (const messages of [{ count: 0, unread: 0, items: [], links }, { count: 2, unread: 1, lastSentAt: sentAt }, thread]) { + const { data } = await readContext(messages) + assert.deepEqual(data.messages, messages) + } + const { id: _id, ...withoutIdentity } = official + await assert.rejects(readContext({ ...thread, items: [withoutIdentity] }), { kind: 'unexpected', reason: 'schema', status: 200 }) +}) 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/clients/typescript/tests/live-audit-key.test.ts b/clients/typescript/tests/live-audit-key.test.ts new file mode 100644 index 0000000000..efd299d469 --- /dev/null +++ b/clients/typescript/tests/live-audit-key.test.ts @@ -0,0 +1,21 @@ +import assert from 'node:assert/strict' +import { mkdtempSync, readFileSync, rmSync, statSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import test from 'node:test' +import { writeTextAuditKey } from './live/harness.ts' + +test('the live text audit fixture writes 32 bytes as private hex text', t => { + const root = mkdtempSync(join(tmpdir(), 'rstack-ts-audit-key-test-')) + t.after(() => rmSync(root, { recursive: true, force: true })) + const path = join(root, 'audit-key') + + writeTextAuditKey(path) + + const key = readFileSync(path, 'utf8') + assert.ok(/^[0-9a-f]{64}$/u.test(key), 'expected exactly 64 lowercase hex characters') + assert.equal(Buffer.from(key, 'hex').length, 32) + if (process.platform !== 'win32') { + assert.equal(statSync(path).mode & 0o777, 0o600) + } +}) diff --git a/clients/typescript/tests/live/harness.ts b/clients/typescript/tests/live/harness.ts index 8ace60a5d8..4e627648e6 100644 --- a/clients/typescript/tests/live/harness.ts +++ b/clients/typescript/tests/live/harness.ts @@ -120,6 +120,10 @@ function writePrivateFile(path: string, content: string | Uint8Array): void { chmodSync(path, 0o600) } +export function writeTextAuditKey(path: string): void { + writePrivateFile(path, randomBytes(32).toString('hex')) +} + type IssuerEndpoints = Pick export function oid4vpTokenRoles(issuer: IssuerEndpoints, audience: string): string { @@ -1029,6 +1033,8 @@ export function stageMainPlan(root: string, dhis2Origin: string): string { 'read-updated-contact': 'editor', 'start-registration': 'editor', 'submit-registration': 'editor', + 'await-registration': 'editor', + 'read-registered-contact': 'editor', }, }, journeyFile: 'dev-journeys.yaml', @@ -1285,7 +1291,7 @@ export async function startLiveEnvironment(options: StartLiveEnvironmentOptions const mcpDir = join(root, 'mcp') const mcpSecrets = join(mcpDir, 'secrets') mkdirSync(mcpSecrets, { recursive: true, mode: 0o700 }) - writePrivateFile(join(mcpSecrets, 'audit-key'), randomBytes(32)) + writeTextAuditKey(join(mcpSecrets, 'audit-key')) writePrivateFile(join(mcpSecrets, 'adapter-token'), adapterReaderTokens.adapter!) const contractFilePath = join(mcpDir, 'adapter-contract.json') writePrivateFile(contractFilePath, contractDocument.bytes) @@ -1383,7 +1389,7 @@ export async function startLiveEnvironment(options: StartLiveEnvironmentOptions mkdirSync(sessionAuditDir, { recursive: true, mode: 0o700 }) writePrivateFile(join(sessionSecrets, 'staff-secret'), staffClientSecret) writePrivateFile(join(sessionSecrets, 'evidence-secret'), evidenceClientSecret) - writePrivateFile(join(sessionSecrets, 'audit-key'), randomBytes(32)) + writeTextAuditKey(join(sessionSecrets, 'audit-key')) const sessionConfigPath = join(sessionDir, 'runtime.yaml') writePrivateFile(sessionConfigPath, [ 'apiVersion: id.registrystack.org/formats/platform/session-runtime/v1alpha1', 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-adapter-connectors/tests/support/breg_native_service.rs b/crates/registry-adapter-connectors/tests/support/breg_native_service.rs index 34d3bf8cf0..e19ddf1372 100644 --- a/crates/registry-adapter-connectors/tests/support/breg_native_service.rs +++ b/crates/registry-adapter-connectors/tests/support/breg_native_service.rs @@ -450,9 +450,9 @@ impl Breg { {"action": "register-household", "operations": ["start"], "targets": [{"recordType": "household", "rowBoundaries": [{"field": "owner", "claim": "sub", "operator": "equals"}]}]} ], "proposals": [ - {"action": "propose-item", "operations": ["get", "submit"], "ownership": "caller", "targets": [{"recordType": "item", "rowBoundaries": [{"field": "owner", "claim": "sub", "operator": "equals"}]}]}, - {"action": "manual-item", "operations": ["get", "submit", "apply"], "ownership": "caller", "targets": [{"recordType": "item", "rowBoundaries": [{"field": "owner", "claim": "sub", "operator": "equals"}]}]}, - {"action": "register-household", "operations": ["get", "submit"], "ownership": "caller", "targets": [{"recordType": "household", "rowBoundaries": [{"field": "owner", "claim": "sub", "operator": "equals"}]}]} + {"action": "propose-item", "operations": ["get", "submit"], "party": "owner", "targets": [{"recordType": "item", "rowBoundaries": [{"field": "owner", "claim": "sub", "operator": "equals"}]}]}, + {"action": "manual-item", "operations": ["get", "submit", "apply"], "party": "owner", "targets": [{"recordType": "item", "rowBoundaries": [{"field": "owner", "claim": "sub", "operator": "equals"}]}]}, + {"action": "register-household", "operations": ["get", "submit"], "party": "owner", "targets": [{"recordType": "household", "rowBoundaries": [{"field": "owner", "claim": "sub", "operator": "equals"}]}]} ] } }} diff --git a/crates/registry-adapter/src/metrics.rs b/crates/registry-adapter/src/metrics.rs index 86981d488a..cf1ddda37c 100644 --- a/crates/registry-adapter/src/metrics.rs +++ b/crates/registry-adapter/src/metrics.rs @@ -409,7 +409,10 @@ mod tests { .lines() .filter(|line| line.starts_with("adapter_request_refusals_total{check=\"")) .count(); - assert_eq!(declared, registry_platform_authcommon::FailedCheck::COUNT); + assert_eq!( + declared, + registry_platform_authcommon::FailedCheck::shared().count() + ); } /// The refusal line a scope refusal writes, driven through the recording diff --git a/crates/registry-adapter/tests/facade_refusals.rs b/crates/registry-adapter/tests/facade_refusals.rs index 21e2fcddad..bf07ca61c8 100644 --- a/crates/registry-adapter/tests/facade_refusals.rs +++ b/crates/registry-adapter/tests/facade_refusals.rs @@ -340,7 +340,11 @@ async fn every_refusal_keeps_its_answer_and_is_counted_and_logged_under_its_chec expected.values().sum::(), "no other check was counted: {counted:?}" ); - assert_eq!(counted.len(), 45, "every check is declared at zero"); + assert_eq!(counted.len(), 45, "every shared check is declared"); + assert!( + !counted.contains_key("membership"), + "membership is a BReg-only check" + ); let stderr = served.wait_for_stderr("\"request refused\"", STDERR_WAIT); std::thread::sleep(Duration::from_millis(300)); 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 b8d16ef376..07f9c8daed 100644 --- a/crates/registry-breg-client-node/__test__/additions.test.js +++ b/crates/registry-breg-client-node/__test__/additions.test.js @@ -13,9 +13,14 @@ 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'; + const formEntryId = '00000000-0000-4000-8000-000000000004'; + const formPath = `/v1/proposals/${id}/additional-forms/${formId}`; + const messageId = '00000000-0000-4000-8000-000000000005'; + const threadPath = `/v1/proposals/${id}/messages`; const requests = []; const server = http.createServer(async (request, response) => { const chunks = []; for await (const chunk of request) chunks.push(chunk); @@ -27,7 +32,30 @@ test('additions preserve the submitted version and use exact binary exchanges', response.setHeader('x-content-type-options', 'nosniff'); response.setHeader('vary', 'authorization'); return response.end(bytes); } - if (request.method === 'POST') { + 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, links: {}})); + if (!request.url.includes(threadPath + '/read')) { + const {text} = JSON.parse(requests.at(-1).body.toString()); + document.revision++; + for (const link of Object.values(document.messages.links)) link.availability.observedRevision = document.revision; + document.additions.other.links.add.availability.observedRevision = document.revision; + document.additionalForms[formId].links.add.availability.observedRevision = document.revision; + document.messages.count++; + document.messages.items.unshift({id: messageId, from: 'party', partyRole: 'owner', + mine: true, sentAt: '2026-11-27T00:00:00Z', text}); + } + return response.end(JSON.stringify(document)); + } + if (request.method === 'POST' && request.url.includes(formPath)) { + document.revision++; + document.formEntryId = formEntryId; + document.additions.other.links.add.availability.observedRevision = document.revision; + const slot = document.additionalForms[formId]; + slot.items.push({id: formEntryId, submissionVersion: 1, addedAt: '2026-11-27T00:00:00Z', + input: JSON.parse(requests.at(-1).body.toString()).input}); + slot.links.add.availability.observedRevision = document.revision; + } else if (request.method === 'POST') { document.revision++; document.additions.other.items.push({id: file, submissionVersion: 1, sha256: createHash('sha256').update(bytes).digest('hex'), byteSize: bytes.length, contentType: 'text/plain', addedAt: '2026-11-27T00:00:00Z', verificationStatus: 'notRequired', @@ -60,5 +88,32 @@ test('additions preserve the submitted version and use exact binary exchanges', const retained = await client.getProposal(contract.selectProposalGet('writer'), id); assert.equal(JSON.parse(retained.documentJson).additions.other.items.length, 2); assert.deepEqual((await client.downloadProposalAddition(retained, file)).body, bytes); + document.additionalForms = {[formId]: {id: formId, maximumCount: 2, items: [], + links: {add: {method: 'POST', path: formPath, accessProfile: 'writer', operation: 'add', + ifMatch: '"form-condition"', availability: {available: true, observedRevision: document.revision}}}}}; + const withForm = await client.getProposal(contract.selectProposalGet('writer'), id); + const sent = await client.addProposalFormEntry(withForm, formId, {confirmed: true}, 'form-one'); + assert.equal(JSON.parse(sent.documentJson).formEntryId, formEntryId); + assert.deepEqual(JSON.parse(requests.at(-1).body.toString()), {input: {confirmed: true}}); + assert.equal(requests.at(-1).headers['idempotency-key'], 'form-one'); + assert.equal(requests.at(-1).headers['if-match'], '"form-condition"'); + const threadLink = (method, tail = '') => ({method, path: threadPath + tail, accessProfile: 'writer', + operation: 'message', availability: {available: true, observedRevision: document.revision}}); + document.messages = {count: 0, unread: 0, items: [], links: { + message: {...threadLink('POST'), ifMatch: '"message-condition"'}, + markRead: threadLink('POST', '/read'), list: threadLink('GET'), + }}; + const current = await client.getProposal(contract.selectProposalGet('writer'), id); + 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, '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}); + assert.equal(requests.at(-1).headers['if-match'], undefined); + assert.equal(requests.at(-1).headers['idempotency-key'], undefined); } finally { await new Promise(resolve => server.close(resolve)); } }); 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 4d5a2a21b8..1382446636 100644 --- a/crates/registry-breg-client-node/__test__/proposals.test.js +++ b/crates/registry-breg-client-node/__test__/proposals.test.js @@ -9,7 +9,7 @@ const id = '00000000-0000-4000-8000-000000000001'; const metadata = { id: 'proposal-client', version: '1', revision, metadataVersion: '2', recordTypes: [], operations: [], proposals: {method: 'GET', path: '/v1/proposals', accessProfiles: ['author'], - actions: [{actionId: 'correct', accessProfile: 'author', operations: ['get', 'list', 'submit'], readableInputs: [], readableContextFields: []}], + actions: [{actionId: 'correct', accessProfile: 'author', party: 'owner', operations: ['get', 'list', 'submit'], readableInputs: [], writableInputs: ['address'], readableContextFields: []}], get: {method: 'GET', path: '/v1/proposals/{proposal_id}', accessProfiles: ['author']}}, actions: [{id: 'correct', apiName: 'correct', revision, display: {}, execution: {mode: 'proposal'}, attachments: [{id: 'supporting-file', required: true, contentTypes: ['application/pdf'], maximumBytes: 1024}], @@ -17,12 +17,12 @@ const metadata = { {id: 'address', apiName: 'address', required: true, nullable: false, classification: 'internal', schema: {type: 'string', minLength: 1, maxLength: 100}, fieldType: {type: 'string', minimumLength: 1, maximumLength: 100}}, - ], referenceInputs: [], requiredConditionKeys: [], resultEffects: [], + ], referenceInputs: [], requiredConditionKeys: [], resultEffects: [], subject: {input: 'address'}, writableInputs: ['address'], access: {selectedProfile: 'author'}, routes: {start: {method: 'POST', path: '/v1/actions/correct/proposals', operationId: 'actions.correct.start', 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', 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)); @@ -86,10 +87,13 @@ test('proposal object methods preserve exact bodies and refuse JSON strings befo const client = new BaseRegistryClient({baseUrl: `http://127.0.0.1:${server.address().port}/tenant/`}); const contract = await client.registryContract('author'); assert.deepEqual(contract.proposalActions, metadata.proposals.actions); + assert.equal(contract.actions[0].subjectInput, 'address'); + assert.deepEqual(contract.actions[0].writableInputs, ['address']); assert.deepEqual(contract.actions[0].attachments, metadata.actions[0].attachments); const getBinding = contract.selectProposalGet('author'); const located = await client.getProposal(getBinding, id); assert.equal(located.identifier, id); + assert.equal(JSON.parse(located.documentJson).partyRole, 'owner'); assert.equal(requests.at(-1).url, `/tenant/v1/proposals/${id}?accessProfile=author`); const getCount = requests.length; for (const invalid of ['../secret', id.toUpperCase(), '00000000-0000-0000-0000-00000000000A']) { @@ -281,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; @@ -339,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)); @@ -389,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-documents.test.js b/crates/registry-breg-client-node/__test__/review-documents.test.js index ee23492e7a..75d6fedaa0 100644 --- a/crates/registry-breg-client-node/__test__/review-documents.test.js +++ b/crates/registry-breg-client-node/__test__/review-documents.test.js @@ -53,7 +53,7 @@ test('review-only binding reads context and exact document without Proposal Get' const binding = contract.selectProposalReviewContext('reviewer', 'correct'); assert.ok(binding instanceof BRegProposalReviewBinding); const observed = (await client.readProposalReviewById(binding, id)).value; - assert.equal(new URL(requests.at(-1), 'http://local').searchParams.get('include'), 'answers'); + assert.deepEqual(new URL(requests.at(-1), 'http://local').searchParams.getAll('include'), ['answers', 'messages']); const batch = await client.readProposalReviewContextBatch(binding, [id, concealedId]); assert.deepEqual(batch.value, [observed, null]); const batchUrl = new URL(requests.at(-1), 'http://local'); diff --git a/crates/registry-breg-client-node/__test__/review-messages.test.js b/crates/registry-breg-client-node/__test__/review-messages.test.js new file mode 100644 index 0000000000..f320e1c172 --- /dev/null +++ b/crates/registry-breg-client-node/__test__/review-messages.test.js @@ -0,0 +1,80 @@ +'use strict'; +const assert = require('node:assert/strict'); +const http = require('node:http'); +const { test } = require('node:test'); +const { BaseRegistryClient } = require('..'); + +// A reviewer writes through the review context's thread link. BReg answers +// with the review context, with the Proposal document when the profile also +// holds Get, or with the thread alone while no review context is readable. +test('a review-context thread write accepts each answer BReg gives a reviewer', async () => { + const id = '00000000-0000-4000-8000-000000000001'; + const question = '00000000-0000-4000-8000-000000000002'; + const reply = '00000000-0000-4000-8000-000000000003'; + const revision = `sha256:${'a'.repeat(64)}`; + const threadPath = `/v1/proposals/${id}/messages`; + const metadata = { id: 'review-messages', version: '1', revision, metadataVersion: '2', + recordTypes: [], operations: [], actions: [], proposals: { actions: [ + { actionId: 'correct', accessProfile: 'reviewer', operations: ['get-review-context', 'message'], + readableInputs: [], readableContextFields: [] }, + ] } }; + let observed = 2; + const link = (method, tail = '') => ({ method, path: threadPath + tail, accessProfile: 'reviewer', + operation: 'message', availability: { available: true, observedRevision: observed } }); + const thread = items => ({ count: items.length, unread: 0, items, links: { + message: { ...link('POST'), ifMatch: `"condition-${observed}"` }, + markRead: link('POST', '/read'), list: link('GET') } }); + const party = { id: question, from: 'party', partyRole: 'owner', mine: false, + sentAt: '2026-12-01T10:00:00Z', text: 'Is a scan enough?' }; + const mine = text => ({ id: reply, from: 'official', mine: true, sentAt: '2026-12-01T10:01:00Z', text }); + const context = items => ({ id, actionId: 'correct', actionRevision: revision, submissionVersion: 1, + revision: observed, effectDigest: revision, + subject: { source: 'review-messages', subjectType: 'proposal', id, version: '1', digest: revision }, + reviewable: true, context: { reference: 'opaque', + contract: { id: 'urn:registry:breg:review-context:review-messages:correct:review', revision, schemaDigest: revision }, + fields: {}, messages: thread(items) } }); + const proposal = items => ({ id, actionId: 'correct', actionRevision: revision, submissionVersion: 1, + revision: observed, state: 'submitted', effectDigest: revision, links: {}, messages: thread(items) }); + let answer = 'review'; + const requests = []; + const server = http.createServer(async (request, response) => { + const chunks = []; for await (const chunk of request) chunks.push(chunk); + requests.push({ method: request.method, url: request.url, body: Buffer.concat(chunks) }); + response.setHeader('traceparent', '00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01'); + response.setHeader('cache-control', 'no-store'); + 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]; + const body = answer === 'review' ? context(items) : answer === 'proposal' ? proposal(items) : thread(items); + return response.end(JSON.stringify(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}/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; + observed = 2; + const read = (await client.readProposalReviewById(binding, id)).value; + const sent = await client.sendProposalMessageFromReview(binding, read, `Reply as ${kind}`, `reply-${kind}`); + const items = member(sent.value).items; + assert.equal(items[0].text, `Reply as ${kind}`, kind); + assert.equal(items[0].mine, true, kind); + assert.equal(requests.at(-1).url, `/tenant${threadPath}?accessProfile=reviewer`); + if (kind === 'thread') assert.equal(sent.value.context, undefined); + } + } finally { await new Promise(resolve => server.close(resolve)); } +}); diff --git a/crates/registry-breg-client-node/client.d.ts b/crates/registry-breg-client-node/client.d.ts index 649d277ddc..cb00a57a8d 100644 --- a/crates/registry-breg-client-node/client.d.ts +++ b/crates/registry-breg-client-node/client.d.ts @@ -517,8 +517,15 @@ export interface BRegOperationDescriptor { export interface BRegProposalActionDescriptor { readonly actionId: string readonly accessProfile: string + /** The Proposal party this entry is bound to; absent for an entry bound to no party. */ + readonly party?: BRegProposalPartyRole readonly operations: ReadonlyArray readonly readableInputs: ReadonlyArray + /** + * The inputs this entry may set through Start, Edit, Revise or Rebase; + * absent from a server that predates the member. Empty when it writes none. + */ + readonly writableInputs?: ReadonlyArray readonly readableContextFields: ReadonlyArray } @@ -530,6 +537,8 @@ export interface BRegActionAttachmentDescriptor { } export interface BRegActionDescriptor { + readonly messages: {readonly maximumCount: number; readonly maximumTextBytes: 2000} | null + readonly additionalForms: Readonly> readonly attachments: ReadonlyArray readonly apiName: string readonly revision: string @@ -567,6 +576,13 @@ export interface BRegActionDescriptor { readonly targetRecordType: string }> readonly requiredConditionKeys: ReadonlyArray + /** The input that names the person a Proposal is about, or `null` when the Action declares none. */ + readonly subjectInput: string | null + /** + * The inputs the selected profile may set, or `null` for an immediate Action + * or a server that predates the member. + */ + readonly writableInputs: ReadonlyArray | null readonly resultEffects: ReadonlyArray<{ readonly effect: string readonly recordType: string @@ -874,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 @@ -902,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 @@ -1006,6 +1024,13 @@ export declare class BaseRegistryClient { downloadProposalAttachment(proposal: BRegProposal, slot: string): Promise 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, 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, 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> readProposalReviewStatusWithProgress(proposal: BRegProposal, request?: ReadRequestOptions): Promise> @@ -1023,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 @@ -1087,21 +1112,54 @@ export interface BRegProposalApplicationStatus { readonly recovery?: 'retry' | 'rebase' | 'revise' | 'correct-input' readonly automaticRetry?: {readonly scheduled: boolean; readonly attempts: number; readonly maximumAttempts: number} } +export interface BRegProposalMessage { + readonly id: string; readonly from: 'party' | 'official'; readonly partyRole?: 'owner' | 'subject'; + readonly mine: boolean; readonly sentAt: string; readonly text?: string; +} +export interface BRegProposalMessages { + readonly count: number; readonly unread: number; readonly lastSentAt?: string; + /** Present on review-context batch summaries that identify the read position. */ + readonly readerSide?: 'party' | 'official'; + readonly items?: ReadonlyArray; + readonly links?: Readonly>>; +} +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: 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 { readonly id: string; readonly actionId: string; readonly actionRevision: string readonly submissionVersion: number; readonly revision: number; readonly effectDigest: string; readonly reviewable: boolean readonly subject: {readonly source: string; readonly subjectType: 'proposal'; readonly id: string; readonly version: string; readonly digest: string} - readonly context: {readonly reference: string; readonly contract?: {readonly id: string; readonly revision: string; readonly schemaDigest: string}; readonly fields?: Readonly>; readonly asks?: ReadonlyArray} + readonly context: {readonly reference: string; readonly contract?: {readonly id: string; readonly revision: string; readonly schemaDigest: string}; readonly fields?: Readonly>; readonly additionalForms?: Readonly>; readonly messages?: BRegProposalMessages; readonly asks?: ReadonlyArray} readonly requestId?: string /** Present only on an explicit progress status read while the accepted request remains pending. */ 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. */ export type BRegProposalTurn = 'party' | 'official' | 'nobody' +/** Which party of a Proposal a party-bound entry admitted the caller as. */ +export type BRegProposalPartyRole = 'owner' | 'subject' export type BRegProposalStatus = 'draft' | 'awaiting-party' | 'in-review' | 'approved' | 'processing' | 'applied' | 'rejected' | 'cancelled' /** The review decision on one submission. The public reason is the only reviewer text BReg serves. */ export interface BRegProposalDecision { readonly status: 'approved' | 'rejected' | 'changes-requested' | 'answered'; readonly decidedAt: string; readonly publicReason?: string } @@ -1114,7 +1172,7 @@ export interface BRegProposalSubmission { readonly decision?: BRegProposalDecision readonly handoffRefusal?: BRegProposalHandoffRefusal } -export interface BRegProposalDocument { readonly id: string; readonly actionId: string; readonly actionRevision: string; readonly submissionVersion: number; readonly revision: number; readonly state: 'draft' | 'submitted' | 'cancelled' | 'applied' | 'rejected'; readonly createdAt?: string; readonly turn?: BRegProposalTurn; readonly status?: BRegProposalStatus; readonly decision?: BRegProposalDecision; readonly handoffRefusal?: BRegProposalHandoffRefusal; readonly title?: string; readonly input?: JsonObject; readonly blockedReason?: 'package-changed'; readonly effectDigest?: string; readonly application?: BRegProposalApplication; readonly applicationStatus?: BRegProposalApplicationStatus; readonly links: Readonly>>; readonly attachments?: Readonly>; readonly additions?: Readonly>; readonly asks?: ReadonlyArray } +export interface BRegProposalDocument { readonly id: string; readonly actionId: string; readonly actionRevision: string; readonly submissionVersion: number; readonly revision: number; readonly state: 'draft' | 'submitted' | 'cancelled' | 'applied' | 'rejected'; readonly createdAt?: string; readonly partyRole?: BRegProposalPartyRole; readonly turn?: BRegProposalTurn; readonly status?: BRegProposalStatus; readonly decision?: BRegProposalDecision; readonly handoffRefusal?: BRegProposalHandoffRefusal; readonly title?: string; readonly input?: JsonObject; readonly blockedReason?: 'package-changed'; readonly effectDigest?: string; readonly application?: BRegProposalApplication; readonly applicationStatus?: BRegProposalApplicationStatus; readonly links: Readonly>>; readonly attachments?: Readonly>; readonly additions?: Readonly>; readonly additionalForms?: Readonly>; readonly formEntryId?: string; readonly messages?: BRegProposalMessages; readonly asks?: ReadonlyArray } export declare class BRegProposal { private constructor(); private readonly __opaque: void; readonly responseEtag: string | null; readonly identifier: string; readonly actionIdentifier: string; readonly documentJson: string; readonly inputJson?: string | null } export declare class BRegProposalGetBinding { private constructor(); private readonly __opaque: void } export declare class BRegProposalReviewBinding { private constructor(); private readonly __opaque: void } @@ -1139,9 +1197,15 @@ export declare class BRegPreparedProposal { private constructor(); private reado export type BRegProposalAskState = 'open' | 'answered' | 'expired' | 'closed' -export type BRegProposalAskWant = {readonly kind: 'answer'} | {readonly kind: 'document'} -export interface BRegProposalAnswerRequest {readonly text?: string; readonly additions?: ReadonlyArray} -export interface BRegProposalAskAnswer {readonly text?: string; readonly additions: ReadonlyArray; readonly answeredAt: string} +export type BRegProposalAskWant = {readonly kind: 'answer'} | {readonly kind: 'document'} | {readonly kind: 'form'; readonly form: string} +export interface BRegReviewFormEntry { readonly id: string; readonly addedAt: string; readonly input?: JsonObject; readonly contractChanged?: boolean } +export interface BRegProposalFormEntry extends BRegReviewFormEntry { readonly submissionVersion: number } +export interface BRegProposalForm { + readonly id: string; readonly maximumCount: number; readonly items?: ReadonlyArray; + readonly links?: Readonly>>; +} +export interface BRegProposalAnswerRequest {readonly text?: string; readonly additions?: ReadonlyArray; readonly formEntries?: ReadonlyArray} +export interface BRegProposalAskAnswer {readonly text?: string; readonly additions: ReadonlyArray; readonly formEntries?: ReadonlyArray; readonly answeredAt: string} export interface BRegProposalAsk { readonly id: string; readonly text: string; readonly wants: ReadonlyArray readonly askedAt: string; readonly dueAt?: string; readonly state: BRegProposalAskState @@ -1152,5 +1216,5 @@ export interface BRegProposalReviewAnswerDocument { readonly id: string; readonly sha256: string; readonly contentType: string; readonly byteSize: number readonly verificationStatus: 'notRequired' | 'pending' | 'approved' | 'rejected'; readonly download?: BRegProposalReviewAnswerDownload } -export interface BRegProposalReviewAnswer {readonly text?: string; readonly documents: ReadonlyArray; readonly answeredAt: string} +export interface BRegProposalReviewAnswer {readonly text?: string; readonly documents: ReadonlyArray; readonly formEntries?: ReadonlyArray; readonly answeredAt: string} export interface BRegProposalReviewAsk extends Omit {readonly answer?: BRegProposalReviewAnswer} diff --git a/crates/registry-breg-client-node/client.js b/crates/registry-breg-client-node/client.js index 4382702991..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], @@ -304,7 +310,9 @@ for (const [method, jsonIndexes, requiredIndexes] of [ ['startProposal', [1], [1]], ['readProposal'], ['readProposalSubmission'], ['getProposal'], ['listProposals', [1], [1]], ['executeProposal'], ['listProposalsJson'], ['downloadProposalAttachment'], ['uploadProposalAttachment'], ['deleteProposalAttachment'], ['answerProposalAsk'], - ['addProposalAddition'], ['downloadProposalAddition'], + ['sendProposalMessage'], ['listProposalMessages'], ['markProposalMessagesRead'], + ['sendProposalMessageFromReview'], ['listProposalMessagesFromReview'], ['markProposalMessagesReadFromReview'], + ['addProposalFormEntry'], ['addProposalAddition'], ['downloadProposalAddition'], ['downloadRecordAttachment'], ['readProposalReviewStatus'], ['readProposalReviewStatusWithProgress'], ['readProposalReviewContext'], ['readProposalReviewContextBatch', [1], [1]], diff --git a/crates/registry-breg-client-node/index.d.ts b/crates/registry-breg-client-node/index.d.ts index e08d7793cd..ffa58de3f3 100644 --- a/crates/registry-breg-client-node/index.d.ts +++ b/crates/registry-breg-client-node/index.d.ts @@ -68,6 +68,13 @@ export declare class BaseRegistryClient { readProposalReviewContext(proposal: BRegProposal, cancellation?: ReadCancellation | undefined | null): Promise 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, 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, 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 downloadProposalAddition(proposal: BRegProposal, addition: string): Promise uploadProposalAttachment(proposal: BRegProposal, slot: string, contentType: string, bytes: Buffer, key: string): Promise @@ -122,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 @@ -183,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 0ea6c03e26..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", }), @@ -1683,6 +1686,50 @@ fn metadata_parts( ) } +fn review_message_document( + value: Value, +) -> Result { + serde_json::from_value(value) + .map_err(|_| binding_error("invalid-request", "Expected a Proposal review document")) +} + +fn review_message_result( + result: BRegComplete, +) -> Result { + // The answer follows the reviewer's profile: the review context, the + // Proposal document when it also holds Get, or the thread alone while + // no review context is readable. + match result.value { + registry_breg_client::BRegProposalMessageOutcome::Review(document) => { + complete_value(*document, result.metadata) + } + registry_breg_client::BRegProposalMessageOutcome::Proposal(proposal) => { + complete_value(*proposal, result.metadata) + } + registry_breg_client::BRegProposalMessageOutcome::Thread(thread) => { + complete_value(*thread, result.metadata) + } + registry_breg_client::BRegProposalMessageOutcome::NoContent => { + complete_value(Value::Null, result.metadata) + } + } +} + +fn proposal_message_result( + result: BRegComplete, +) -> Result { + let registry_breg_client::BRegProposalMessageOutcome::Proposal(inner) = result.value else { + return Err(binding_error( + "protocol", + "Expected a Proposal message response", + )); + }; + Ok(Proposal { + response_etag: result.metadata.etag().map(|etag| etag.as_str().to_owned()), + inner: *inner, + }) +} + fn complete_value( value: T, metadata: registry_breg_client::BRegResponseMetadata, @@ -2036,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()) } @@ -2346,6 +2404,16 @@ impl IngestionPrefixDigest { } } +fn form_input_value(input: ®istry_breg_client::BRegActionInputDescriptor) -> Value { + json!({ + "id": input.identifier(), "apiName": input.api_name(), + "label": input.label(), "description": input.description(), + "schemaJson": input.schema().to_string(), + "fieldTypeJson": input.field_type().to_string(), "required": input.required(), + "nullable": input.nullable(), "classification": input.classification(), + }) +} + fn action_descriptor_value(value: ®istry_breg_client::BRegActionDescriptor) -> Value { let bounds = value.bounds(); json!({ @@ -2355,18 +2423,18 @@ fn action_descriptor_value(value: ®istry_breg_client::BRegActionDescriptor) - "inputMode": value.input_mode(), "maximumInputStringBytes": value.maximum_input_string_bytes(), "attachments": value.attachments(), - "inputs": value.inputs().iter().map(|input| json!({ - "id": input.identifier(), "apiName": input.api_name(), - "label": input.label(), "description": input.description(), - "schemaJson": input.schema().to_string(), - "fieldTypeJson": input.field_type().to_string(), "required": input.required(), - "nullable": input.nullable(), "classification": input.classification(), - })).collect::>(), + "inputs": value.inputs().iter().map(form_input_value).collect::>(), + "messages": value.maximum_message_count().map(|limit| json!({"maximumCount":limit,"maximumTextBytes":2000})), + "additionalForms": value.additional_forms().iter().map(|(id, inputs)| { + (id, inputs.iter().map(form_input_value).collect::>()) + }).collect::>(), "referenceInputs": value.reference_inputs().iter().map(|input| json!({ "input": input.input_identifier(), "apiName": input.api_name(), "targetRecordType": input.target_record_type(), })).collect::>(), "requiredConditionKeys": value.required_condition_keys(), + "subjectInput": value.subject_input(), + "writableInputs": value.writable_inputs(), "resultEffects": value.result_effects().iter().map(|effect| json!({ "effect": effect.effect_identifier(), "recordType": effect.record_type_identifier(), "operation": effect.operation().as_str(), @@ -3582,6 +3650,158 @@ impl BaseRegistryClient { .map_err(client_error) } + #[napi] + pub async fn send_proposal_message( + &self, + proposal: &Proposal, + text: String, + key: String, + ) -> Result { + let key = idempotency_key(key)?; + let result = self + .inner + .send_proposal_message( + registry_breg_client::BRegProposalMessageTarget::Proposal(&proposal.inner), + &text, + &key, + ) + .await + .map_err(client_error)?; + proposal_message_result(result) + } + + #[napi] + pub async fn list_proposal_messages( + &self, + proposal: &Proposal, + cursor: Option, + limit: Option, + ) -> Result { + let result = self + .inner + .list_proposal_messages( + registry_breg_client::BRegProposalMessageTarget::Proposal(&proposal.inner), + cursor.as_deref(), + limit.unwrap_or(20), + ) + .await + .map_err(client_error)?; + complete_value(result.value, result.metadata) + } + + #[napi] + pub async fn mark_proposal_messages_read( + &self, + proposal: &Proposal, + through: String, + ) -> Result> { + let result = self + .inner + .mark_proposal_messages_read( + registry_breg_client::BRegProposalMessageTarget::Proposal(&proposal.inner), + &through, + ) + .await + .map_err(client_error)?; + if matches!( + result.value, + registry_breg_client::BRegProposalMessageOutcome::NoContent + ) { + return Ok(None); + } + proposal_message_result(result).map(Some) + } + + #[napi] + pub async fn send_proposal_message_from_review( + &self, + binding: &ProposalReviewBinding, + context: Value, + text: String, + key: String, + ) -> Result { + let document = review_message_document(context)?; + let key = idempotency_key(key)?; + let target = registry_breg_client::BRegProposalMessageTarget::Review { + binding: &binding.inner, + document: &document, + }; + let result = self + .inner + .send_proposal_message(target, &text, &key) + .await + .map_err(client_error)?; + review_message_result(result) + } + + #[napi] + pub async fn list_proposal_messages_from_review( + &self, + binding: &ProposalReviewBinding, + context: Value, + cursor: Option, + limit: Option, + ) -> Result { + let document = review_message_document(context)?; + let target = registry_breg_client::BRegProposalMessageTarget::Review { + binding: &binding.inner, + document: &document, + }; + let result = self + .inner + .list_proposal_messages(target, cursor.as_deref(), limit.unwrap_or(20)) + .await + .map_err(client_error)?; + complete_value(result.value, result.metadata) + } + + #[napi] + pub async fn mark_proposal_messages_read_from_review( + &self, + binding: &ProposalReviewBinding, + context: Value, + through: String, + ) -> Result { + let document = review_message_document(context)?; + let target = registry_breg_client::BRegProposalMessageTarget::Review { + binding: &binding.inner, + document: &document, + }; + let result = self + .inner + .mark_proposal_messages_read(target, &through) + .await + .map_err(client_error)?; + review_message_result(result) + } + + #[napi( + ts_args_type = "proposal: BRegProposal, formId: string, input: Record, key: string" + )] + pub async fn add_proposal_form_entry( + &self, + proposal: &Proposal, + form_id: String, + input: Value, + key: String, + ) -> Result { + let input = input.as_object().ok_or_else(|| { + binding_error("invalid-request", "Proposal form input must be an object") + })?; + let key = idempotency_key(key)?; + self.inner + .add_proposal_form_entry(&proposal.inner, &form_id, input, &key) + .await + .map(|response| Proposal { + response_etag: response + .metadata + .etag() + .map(|etag| etag.as_str().to_owned()), + inner: response.value, + }) + .map_err(client_error) + } + #[napi] pub async fn add_proposal_addition( &self, @@ -4043,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) @@ -4063,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) @@ -4079,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) @@ -4096,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) @@ -4116,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) @@ -4134,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) @@ -4154,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, @@ -4162,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) @@ -4723,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 4a50bb57c6..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 @@ -319,10 +320,26 @@ class BRegRecoveredAction: ... class BRegProposalActionDescriptor(TypedDict): action_id: str access_profile: str + party: Literal['owner', 'subject'] | None operations: Sequence[str] readable_inputs: Sequence[str] + writable_inputs: Sequence[str] | None readable_context_fields: Sequence[str] +BRegProposalMessage = TypedDict('BRegProposalMessage', { + 'id': str, 'from': Literal['party', 'official'], + 'partyRole': NotRequired[Literal['owner', 'subject']], + 'mine': bool, 'sentAt': str, 'text': NotRequired[str], +}) +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 + trace_id: str + class BRegProposalReviewDocument(TypedDict): id: str actionId: str @@ -340,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 @@ -695,6 +746,13 @@ class BaseRegistryClient: def download_proposal_attachment(self, proposal: BRegProposal, slot: str) -> dict[str, Any]: ... 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, 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]: ... def read_proposal_review_status_with_progress(self, proposal: BRegProposal) -> BRegProposalReviewCompleteOutcome: ... @@ -720,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, @@ -735,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, @@ -748,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, @@ -761,6 +829,8 @@ class BaseRegistryClient: run_id: str, chunk_index: int, profile_id: str, + *, + access_reason: str | None = None, ) -> dict[str, Any]: ... __version__: str @@ -802,14 +872,20 @@ class BRegPreparedProposal: def to_bytes(self) -> bytes: ... BRegProposalAskState = Literal['open', 'answered', 'expired', 'closed'] -class BRegProposalAskWant(TypedDict): +class _BRegProposalBasicAskWant(TypedDict): kind: Literal['answer', 'document'] +class _BRegProposalFormAskWant(TypedDict): + kind: Literal['form'] + form: str +BRegProposalAskWant = _BRegProposalBasicAskWant | _BRegProposalFormAskWant class BRegProposalAnswerRequest(TypedDict): text: NotRequired[str] additions: NotRequired[list[str]] + formEntries: NotRequired[list[str]] class BRegProposalAskAnswer(TypedDict): text: NotRequired[str] additions: list[str] + formEntries: NotRequired[list[str]] answeredAt: str class BRegProposalAsk(TypedDict): id: str @@ -832,9 +908,15 @@ class BRegProposalReviewAnswerDocument(TypedDict): byteSize: int verificationStatus: Literal['notRequired', 'pending', 'approved', 'rejected'] download: NotRequired[BRegProposalReviewAnswerDownload] +class BRegReviewFormEntry(TypedDict): + id: str + addedAt: str + input: NotRequired[dict[str, JsonValue]] + contractChanged: NotRequired[bool] class BRegProposalReviewAnswer(TypedDict): text: NotRequired[str] documents: list[BRegProposalReviewAnswerDocument] + formEntries: NotRequired[list[BRegReviewFormEntry]] answeredAt: str class BRegProposalReviewAsk(TypedDict): id: str diff --git a/crates/registry-breg-client-py/src/lib.rs b/crates/registry-breg-client-py/src/lib.rs index a01525d68f..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); @@ -480,6 +485,58 @@ fn projection_from_python( serde_json::from_value(value).map_err(|_| invalid(py, format!("{what} is invalid"))) } +fn review_message_document( + py: Python<'_>, + context: &Bound<'_, PyAny>, +) -> PyResult { + let bad = || invalid(py, "Expected a Proposal review document"); + let value = python_to_json(context).map_err(|_| bad())?; + serde_json::from_value(value).map_err(|_| bad()) +} + +fn review_message_result<'py>( + py: Python<'py>, + result: breg_client_sdk::BRegComplete, +) -> PyResult> { + // The answer follows the reviewer's profile: the review context, the + // Proposal document when it also holds Get, or the thread alone while + // no review context is readable. + match result.value { + breg_client_sdk::BRegProposalMessageOutcome::Review(document) => { + complete_value(py, &*document, &result.metadata) + } + breg_client_sdk::BRegProposalMessageOutcome::Proposal(proposal) => { + complete_value(py, &*proposal, &result.metadata) + } + 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<'_>, + outcome: breg_client_sdk::BRegProposalMessageOutcome, + etag: Option<&BRegEtag>, +) -> PyResult { + 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: etag.map(|etag| etag.as_str().to_owned()), + inner: *inner, + }) +} + fn complete_value<'py, T: Serialize>( py: Python<'py>, value: &T, @@ -751,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()) } @@ -1258,6 +1329,20 @@ fn metadata_operation_value(value: &breg_client_sdk::BRegMetadataOperation) -> V }) } +fn form_input_value(input: &breg_client_sdk::BRegActionInputDescriptor) -> Value { + json!({ + "id": input.identifier(), + "api_name": input.api_name(), + "label": input.label(), + "description": input.description(), + "schema": input.schema(), + "field_type": input.field_type(), + "required": input.required(), + "nullable": input.nullable(), + "classification": input.classification(), + }) +} + fn action_value(value: &breg_client_sdk::BRegActionDescriptor) -> Value { let bounds = value.bounds(); json!({ @@ -1270,23 +1355,19 @@ fn action_value(value: &breg_client_sdk::BRegActionDescriptor) -> Value { "id": slot.identifier(), "required": slot.required(), "content_types": slot.content_types(), "maximum_bytes": slot.maximum_bytes(), })).collect::>(), - "inputs": value.inputs().iter().map(|input| json!({ - "id": input.identifier(), - "api_name": input.api_name(), - "label": input.label(), - "description": input.description(), - "schema": input.schema(), - "field_type": input.field_type(), - "required": input.required(), - "nullable": input.nullable(), - "classification": input.classification(), - })).collect::>(), + "inputs": value.inputs().iter().map(form_input_value).collect::>(), + "messages": value.maximum_message_count().map(|limit| json!({"maximumCount":limit,"maximumTextBytes":2000})), + "additional_forms": value.additional_forms().iter().map(|(id, inputs)| { + (id, inputs.iter().map(form_input_value).collect::>()) + }).collect::>(), "reference_inputs": value.reference_inputs().iter().map(|input| json!({ "input": input.input_identifier(), "api_name": input.api_name(), "target_record_type": input.target_record_type(), })).collect::>(), "required_condition_keys": value.required_condition_keys(), + "subject_input": value.subject_input(), + "writable_inputs": value.writable_inputs(), "result_effects": value.result_effects().iter().map(|effect| json!({ "effect": effect.effect_identifier(), "record_type": effect.record_type_identifier(), @@ -1566,7 +1647,9 @@ impl Metadata { fn proposal_actions<'py>(&self, py: Python<'py>) -> PyResult> { json_to_python(py, &Value::Array(self.inner.proposal_actions().iter().map(|entry| json!({ "action_id": entry.action_identifier(), "access_profile": entry.access_profile(), + "party": entry.party(), "operations": entry.operations(), "readable_inputs": entry.readable_inputs(), + "writable_inputs": entry.writable_inputs(), "readable_context_fields": entry.readable_context_fields(), })).collect())) } @@ -3061,6 +3144,175 @@ impl BaseRegistryClient { }) } + fn send_proposal_message( + &self, + py: Python<'_>, + proposal: PyRef<'_, Proposal>, + text: &str, + key: &str, + ) -> PyResult { + let proposal = proposal.inner.clone(); + let key = BRegIdempotencyKey::parse(key).map_err(|error| invalid(py, error.to_string()))?; + let result = py + .detach(|| { + self.runtime.block_on(self.inner.send_proposal_message( + breg_client_sdk::BRegProposalMessageTarget::Proposal(&proposal), + text, + &key, + )) + }) + .map_err(|error| sdk_error(py, error))?; + proposal_message_result(py, result.value, result.metadata.etag()) + } + + #[pyo3(signature = (proposal, cursor=None, limit=20))] + fn list_proposal_messages<'py>( + &self, + py: Python<'py>, + proposal: PyRef<'_, Proposal>, + cursor: Option<&str>, + limit: u8, + ) -> PyResult> { + let proposal = proposal.inner.clone(); + let result = py + .detach(|| { + self.runtime.block_on(self.inner.list_proposal_messages( + breg_client_sdk::BRegProposalMessageTarget::Proposal(&proposal), + cursor, + limit, + )) + }) + .map_err(|error| sdk_error(py, error))?; + complete_value(py, &result.value, &result.metadata) + } + + fn mark_proposal_messages_read( + &self, + py: Python<'_>, + proposal: PyRef<'_, Proposal>, + through: &str, + ) -> PyResult> { + let proposal = proposal.inner.clone(); + let result = py + .detach(|| { + self.runtime + .block_on(self.inner.mark_proposal_messages_read( + breg_client_sdk::BRegProposalMessageTarget::Proposal(&proposal), + through, + )) + }) + .map_err(|error| sdk_error(py, error))?; + 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>( + &self, + py: Python<'py>, + binding: PyRef<'_, ProposalReviewBinding>, + context: &Bound<'_, PyAny>, + text: &str, + key: &str, + ) -> PyResult> { + let document = review_message_document(py, context)?; + let binding = binding.inner.clone(); + let key = BRegIdempotencyKey::parse(key).map_err(|error| invalid(py, error.to_string()))?; + let target = breg_client_sdk::BRegProposalMessageTarget::Review { + binding: &binding, + document: &document, + }; + let result = py + .detach(|| { + self.runtime + .block_on(self.inner.send_proposal_message(target, text, &key)) + }) + .map_err(|error| sdk_error(py, error))?; + review_message_result(py, result) + } + + #[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>, + cursor: Option<&str>, + limit: u8, + ) -> PyResult> { + let document = review_message_document(py, context)?; + let binding = binding.inner.clone(); + let target = breg_client_sdk::BRegProposalMessageTarget::Review { + binding: &binding, + document: &document, + }; + let result = py + .detach(|| { + self.runtime + .block_on(self.inner.list_proposal_messages(target, cursor, limit)) + }) + .map_err(|error| sdk_error(py, error))?; + complete_value(py, &result.value, &result.metadata) + } + + fn mark_proposal_messages_read_from_review<'py>( + &self, + py: Python<'py>, + binding: PyRef<'_, ProposalReviewBinding>, + context: &Bound<'_, PyAny>, + through: &str, + ) -> PyResult> { + let document = review_message_document(py, context)?; + let binding = binding.inner.clone(); + let target = breg_client_sdk::BRegProposalMessageTarget::Review { + binding: &binding, + document: &document, + }; + let result = py + .detach(|| { + self.runtime + .block_on(self.inner.mark_proposal_messages_read(target, through)) + }) + .map_err(|error| sdk_error(py, error))?; + review_message_result(py, result) + } + + fn add_proposal_form_entry( + &self, + py: Python<'_>, + proposal: PyRef<'_, Proposal>, + form_id: &str, + input: &Bound<'_, PyAny>, + key: &str, + ) -> PyResult { + let proposal = proposal.inner.clone(); + let value = python_to_json(input) + .map_err(|_| invalid(py, "Proposal form input must be exact JSON"))?; + let input = value + .as_object() + .ok_or_else(|| invalid(py, "Proposal form input must be an object"))?; + let key = BRegIdempotencyKey::parse(key).map_err(|error| invalid(py, error.to_string()))?; + let response = py + .detach(|| { + self.runtime.block_on( + self.inner + .add_proposal_form_entry(&proposal, form_id, input, &key), + ) + }) + .map_err(|error| sdk_error(py, error))?; + Ok(Proposal { + response_etag: response + .metadata + .etag() + .map(|etag| etag.as_str().to_owned()), + inner: response.value, + }) + } + fn add_proposal_addition( &self, py: Python<'_>, @@ -3424,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>, @@ -3432,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()))?; @@ -3441,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) @@ -3450,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, @@ -3480,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) @@ -3517,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>, @@ -3524,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) @@ -3565,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>, @@ -3573,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) @@ -3674,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 f7d3e461fa..46870e76a1 100644 --- a/crates/registry-breg-client-py/tests/python/test_additions.py +++ b/crates/registry-breg-client-py/tests/python/test_additions.py @@ -16,13 +16,17 @@ def test_addition_and_download_keep_the_exact_submission(self): addition_id = '00000000-0000-4000-8000-000000000002' revision = 'sha256:' + 'a' * 64 content = b'support' + form_entry_id = '00000000-0000-4000-8000-000000000004' + form_path = f'/v1/proposals/{proposal_id}/additional-forms/details' + message_id = '00000000-0000-4000-8000-000000000005' + thread_path = f'/v1/proposals/{proposal_id}/messages' requests = [] metadata = {'id': 'additions', 'version': '1', 'revision': 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']}}} 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"'}}}}} @@ -30,7 +34,9 @@ def test_addition_and_download_keep_the_exact_submission(self): class Handler(BaseHTTPRequestHandler): def do_GET(self): requests.append(('GET', self.path, dict(self.headers), b'')) - if f'/additions/{addition_id}?' in self.path: + if thread_path in self.path: + 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: self.respond(json.dumps(metadata if '/registry?' in self.path else document).encode()) @@ -38,7 +44,29 @@ def do_GET(self): def do_POST(self): body = self.rfile.read(int(self.headers['content-length'])) requests.append(('POST', self.path, dict(self.headers), body)) + if thread_path in self.path: + if f'{thread_path}/read' not in self.path: + document['revision'] += 1 + document['additions']['other']['links']['add']['availability']['observedRevision'] = document['revision'] + document['additionalForms']['details']['links']['add']['availability']['observedRevision'] = document['revision'] + for link in document['messages']['links'].values(): + link['availability']['observedRevision'] = document['revision'] + document['messages']['count'] += 1 + document['messages']['items'].insert(0, {'id': message_id, 'from': 'party', + 'partyRole': 'owner', 'mine': True, 'sentAt': '2026-11-27T00:00:00Z', + 'text': json.loads(body)['text']}) + self.respond(json.dumps(document).encode()) + return document['revision'] += 1 + if form_path in self.path: + document['formEntryId'] = form_entry_id + document['additions']['other']['links']['add']['availability']['observedRevision'] = document['revision'] + slot = document['additionalForms']['details'] + slot['links']['add']['availability']['observedRevision'] = document['revision'] + slot['items'].append({'id': form_entry_id, 'submissionVersion': 1, + 'addedAt': '2026-11-27T00:00:00Z', 'input': json.loads(body)['input']}) + self.respond(json.dumps(document).encode()) + return document['additions']['other']['items'].append({'id': addition_id, 'submissionVersion': 1, 'sha256': hashlib.sha256(content).hexdigest(), 'byteSize': len(content), 'contentType': 'text/plain', 'addedAt': '2026-11-27T00:00:00Z', 'verificationStatus': 'notRequired', 'links': {'download': { @@ -92,6 +120,35 @@ def log_message(self, *args): retained = client.get_proposal(contract.select_proposal_get('writer'), proposal_id) self.assertEqual(len(retained.document['additions']['other']['items']), 2) self.assertEqual(client.download_proposal_addition(retained, addition_id)['body'], content) + document['additionalForms'] = {'details': {'id': 'details', 'maximumCount': 2, 'items': [], + 'links': {'add': {'method': 'POST', 'path': form_path, 'accessProfile': 'writer', + 'operation': 'add', 'ifMatch': '"form-condition"', + 'availability': {'available': True, 'observedRevision': document['revision']}}}}} + with_form = client.get_proposal(contract.select_proposal_get('writer'), proposal_id) + sent = client.add_proposal_form_entry(with_form, 'details', {'confirmed': True}, 'form-one') + self.assertEqual(sent.document['formEntryId'], form_entry_id) + self.assertEqual(json.loads(requests[-1][3]), {'input': {'confirmed': True}}) + headers = {key.lower(): value for key, value in requests[-1][2].items()} + self.assertEqual(headers['if-match'], '"form-condition"') + self.assertEqual(headers['idempotency-key'], 'form-one') + def thread_link(method, tail=''): + return {'method': method, 'path': thread_path + tail, 'accessProfile': 'writer', + 'operation': 'message', 'availability': {'available': True, 'observedRevision': document['revision']}} + + document['messages'] = {'count': 0, 'unread': 0, 'items': [], 'links': { + 'message': {**thread_link('POST'), 'ifMatch': '"message-condition"'}, + 'markRead': thread_link('POST', '/read'), 'list': thread_link('GET')}} + 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, 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}) + headers = {key.lower(): value for key, value in requests[-1][2].items()} + self.assertNotIn('if-match', headers) + self.assertNotIn('idempotency-key', headers) finally: server.shutdown() thread.join() 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 674e03fe28..221e12f714 100644 --- a/crates/registry-breg-client-py/tests/python/test_proposals.py +++ b/crates/registry-breg-client-py/tests/python/test_proposals.py @@ -15,12 +15,12 @@ 'id': 'proposal-lookup', 'version': '1', 'revision': REVISION, 'metadataVersion': '2', 'recordTypes': [], 'operations': [], 'actions': [], 'proposals': {'method': 'GET', 'path': '/v1/proposals', 'accessProfiles': [], - 'actions': [{'actionId': 'correct', 'accessProfile': 'reader', 'operations': ['get'], 'readableInputs': ['address-line'], 'readableContextFields': []}], + 'actions': [{'actionId': 'correct', 'accessProfile': 'reader', 'party': 'subject', 'operations': ['get'], 'readableInputs': ['address-line'], 'writableInputs': [], 'readableContextFields': []}], 'get': {'method': 'GET', 'path': '/v1/proposals/{proposal_id}', 'accessProfiles': ['reader']}}, } 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'}}, @@ -110,8 +110,10 @@ def log_message(self, *args): client = BaseRegistryClient(f'http://127.0.0.1:{server.server_port}/') metadata = client.registry_contract('writer') self.assertEqual(metadata.proposal_actions, [ - {'action_id': 'correct', 'access_profile': 'queue', 'operations': ['list'], 'readable_inputs': [], 'readable_context_fields': []}, - {'action_id': 'correct', 'access_profile': 'executor', 'operations': ['apply'], 'readable_inputs': [], 'readable_context_fields': []}]) + {'action_id': 'correct', 'access_profile': 'queue', 'party': None, 'operations': ['list'], 'readable_inputs': [], + 'writable_inputs': None, 'readable_context_fields': []}, + {'action_id': 'correct', 'access_profile': 'executor', 'party': None, 'operations': ['apply'], 'readable_inputs': [], + 'writable_inputs': None, 'readable_context_fields': []}]) self.assertEqual(metadata.actions[0]['attachments'], [{'id': 'supporting-file', 'required': True, 'content_types': ['application/pdf'], 'maximum_bytes': 1024}]) with self.assertRaises(BaseRegistryClientError): @@ -204,8 +206,9 @@ def log_message(self, *args): try: client = BaseRegistryClient(f'http://127.0.0.1:{server.server_port}/tenant/') metadata = client.registry_contract('reader') - self.assertEqual(metadata.proposal_actions, [{'action_id': 'correct', 'access_profile': 'reader', - 'operations': ['get'], 'readable_inputs': ['address-line'], 'readable_context_fields': []}]) + self.assertEqual(metadata.proposal_actions, [{'action_id': 'correct', 'access_profile': 'reader', 'party': 'subject', + 'operations': ['get'], 'readable_inputs': ['address-line'], + 'writable_inputs': [], 'readable_context_fields': []}]) with self.assertRaises(BaseRegistryClientError): metadata.select_proposals('reader') binding = metadata.select_proposal_get('reader') @@ -385,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) @@ -493,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)))]: @@ -569,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-py/tests/python/test_review_documents.py b/crates/registry-breg-client-py/tests/python/test_review_documents.py index 37369b52c7..f8ff884cc8 100644 --- a/crates/registry-breg-client-py/tests/python/test_review_documents.py +++ b/crates/registry-breg-client-py/tests/python/test_review_documents.py @@ -77,7 +77,7 @@ def do_GET(self): binding = contract.select_proposal_review_context('reviewer', 'correct') self.assertIsInstance(binding, BRegProposalReviewBinding) observed = client.read_proposal_review_by_id(binding, identifier)['value'] - self.assertEqual(parse_qs(urlsplit(requests[-1]).query)['include'], ['answers']) + self.assertEqual(parse_qs(urlsplit(requests[-1]).query)['include'], ['answers', 'messages']) batch = client.read_proposal_review_context_batch(binding, [identifier, concealed_id]) self.assertEqual(batch['value'], [observed, None]) batch_url = urlsplit(requests[-1]) 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 de0422ecb5..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,21 +1505,64 @@ 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, ) -> Result, BaseRegistryClientError> { - self.proposal_review_include_exchange(link, "get-review-status", "progress") + self.proposal_review_include_exchange(link, "get-review-status", &["progress"]) .await } @@ -1459,7 +1570,8 @@ impl BaseRegistryClient { &self, link: &BRegProposalLink, ) -> Result, BaseRegistryClientError> { - self.proposal_review_include_exchange(link, "get-review-context", "answers") + // The displayed context carries the live answers and message thread. + self.proposal_review_include_exchange(link, "get-review-context", &["answers", "messages"]) .await } @@ -1467,7 +1579,7 @@ impl BaseRegistryClient { &self, link: &BRegProposalLink, operation: &str, - include: &str, + includes: &[&str], ) -> Result, BaseRegistryClientError> { if link.method() != "GET" || link.operation() != operation { return Err(BaseRegistryClientError::invalid_request( @@ -1476,7 +1588,11 @@ impl BaseRegistryClient { } let segments = fixed_operation_segments(link.path())?; let mut pairs = access_profile_query(Some(link.access_profile()))?; - pairs.push(("include".to_owned(), include.to_owned())); + pairs.extend( + includes + .iter() + .map(|include| ("include".to_owned(), (*include).to_owned())), + ); let url = self.url_with_query(&segments, &pairs)?; let builder = self .authorize( @@ -1487,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 } @@ -1523,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, @@ -1537,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)?; @@ -1550,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), @@ -1577,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, @@ -1586,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, @@ -1638,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), @@ -1854,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 @@ -1864,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?; @@ -2236,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, @@ -2829,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) { @@ -2877,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()) @@ -2887,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, @@ -2934,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(), @@ -2962,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!( @@ -3234,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", @@ -3257,9 +3413,7 @@ const BREG_QUERY_PARAMETERS: [&str; 26] = [ "pendingManualApplication", "target", "cursor", - "top", "inputDigest", - "after", "query", ]; @@ -3404,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 b45093ce73..51cfb0b7ee 100644 --- a/crates/registry-breg-client/src/error.rs +++ b/crates/registry-breg-client/src/error.rs @@ -166,8 +166,13 @@ pub enum BRegProblemCode { PreconditionFailed, PreconditionRequired, ProfileNotAuthorized, + ProposalFormLimitReached, + ProposalFormUndeclared, + ProposalMessageLimitReached, ProposalRejected, ProposalReviewResultMismatch, + ProposalSubjectChanged, + ProposalSubjectNotCaller, ProposalSubmissionExpired, QueryCursorInvalid, QueryFilterRequired, @@ -189,7 +194,7 @@ pub enum BRegProblemCode { } impl BRegProblemCode { - pub const ALL: [Self; 48] = [ + pub const ALL: [Self; 53] = [ Self::AccessProfileAmbiguous, Self::ActionEvidenceFailed, Self::ActionGuardFailed, @@ -218,8 +223,13 @@ impl BRegProblemCode { Self::PreconditionFailed, Self::PreconditionRequired, Self::ProfileNotAuthorized, + Self::ProposalFormLimitReached, + Self::ProposalFormUndeclared, + Self::ProposalMessageLimitReached, Self::ProposalRejected, Self::ProposalReviewResultMismatch, + Self::ProposalSubjectChanged, + Self::ProposalSubjectNotCaller, Self::ProposalSubmissionExpired, Self::QueryCursorInvalid, Self::QueryFilterRequired, @@ -271,8 +281,13 @@ impl BRegProblemCode { Self::PreconditionFailed => "precondition.failed", Self::PreconditionRequired => "precondition.required", Self::ProfileNotAuthorized => "profile.not-authorized", + Self::ProposalFormLimitReached => "proposal.form-limit-reached", + Self::ProposalFormUndeclared => "proposal.form-undeclared", + Self::ProposalMessageLimitReached => "proposal.message-limit-reached", Self::ProposalRejected => "proposal.rejected", Self::ProposalReviewResultMismatch => "proposal.review-result-mismatch", + Self::ProposalSubjectChanged => "proposal.subject-changed", + Self::ProposalSubjectNotCaller => "proposal.subject-not-caller", Self::ProposalSubmissionExpired => "proposal.submission-expired", Self::QueryCursorInvalid => "query.cursor-invalid", Self::QueryFilterRequired => "query.filter-required", @@ -306,9 +321,10 @@ impl BRegProblemCode { Self::ActionEvidenceFailed => 503, Self::ActionHandlerFailed => 500, Self::AuthenticationRefused | Self::DevelopmentTaskAssertion => 401, - Self::LookupUnresolved | Self::ResourceNotFound => 404, + Self::LookupUnresolved | Self::ResourceNotFound | Self::ProposalFormUndeclared => 404, Self::IngestionProfileMismatch | Self::ProfileNotAuthorized + | Self::ProposalSubjectNotCaller | Self::WriteOutsideBoundary => 403, Self::AttachmentSlotWriteOnce | Self::AttachmentLimitReached @@ -318,7 +334,10 @@ impl BRegProblemCode { | Self::IngestionRunBlocked | Self::IngestionRunNotOpen | Self::MutationConflict + | Self::ProposalFormLimitReached + | Self::ProposalMessageLimitReached | Self::ProposalRejected + | Self::ProposalSubjectChanged | Self::StatisticalDatasetVersionConflict => 409, Self::IdempotencyExpired | Self::IngestionReceiptErased @@ -404,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." } @@ -429,7 +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::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::PreconditionRequired => "The mutation precondition is required.", Self::ProfileNotAuthorized => "No access profile admits this caller for this request.", Self::ProposalRejected => { @@ -548,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( @@ -573,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, @@ -591,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 } @@ -690,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> { @@ -954,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 76a01d4c98..285af64663 100644 --- a/crates/registry-breg-client/src/metadata.rs +++ b/crates/registry-breg-client/src/metadata.rs @@ -1052,8 +1052,12 @@ impl fmt::Debug for BRegActionAttachmentDescriptor { pub struct BRegProposalActionDescriptor { action_id: String, access_profile: String, + #[serde(skip_serializing_if = "Option::is_none")] + party: Option, operations: Vec, readable_inputs: Vec, + #[serde(skip_serializing_if = "Option::is_none")] + writable_inputs: Option>, readable_context_fields: Vec, } @@ -1064,12 +1068,24 @@ impl BRegProposalActionDescriptor { pub fn access_profile(&self) -> &str { &self.access_profile } + /// The Proposal party this entry is bound to; `None` for an entry bound + /// to no party, such as an officer's. + #[must_use] + pub const fn party(&self) -> Option { + self.party + } pub fn operations(&self) -> &[String] { &self.operations } pub fn readable_inputs(&self) -> &[String] { &self.readable_inputs } + /// The inputs this entry may set through Start, Edit, Revise or Rebase. + /// Empty when it writes none; `None` from a server that predates the + /// member. + pub fn writable_inputs(&self) -> Option<&[String]> { + self.writable_inputs.as_deref() + } pub fn readable_context_fields(&self) -> &[String] { &self.readable_context_fields } @@ -1100,9 +1116,13 @@ pub struct BRegActionDescriptor { input_mode: Option, maximum_input_string_bytes: Option, inputs: Vec, + additional_forms: BTreeMap>, + maximum_message_count: Option, attachments: Vec, reference_inputs: Vec, required_condition_keys: Vec, + subject_input: Option, + writable_inputs: Option>, result_effects: Vec, access_profile: String, invoke_path: Option, @@ -1112,6 +1132,14 @@ pub struct BRegActionDescriptor { } impl BRegActionDescriptor { + pub fn maximum_message_count(&self) -> Option { + self.maximum_message_count + } + + pub fn additional_forms(&self) -> &BTreeMap> { + &self.additional_forms + } + pub fn api_name(&self) -> &str { &self.api_name } @@ -1138,6 +1166,16 @@ impl BRegActionDescriptor { pub const fn application(&self) -> Option<&BRegActionApplication> { self.application.as_ref() } + /// The input that names the person a Proposal is about. `None` when the + /// Action declares no subject or the selected profile cannot read it. + pub fn subject_input(&self) -> Option<&str> { + self.subject_input.as_deref() + } + /// The inputs the selected profile may set. `None` for an immediate + /// Action or a server that predates the member. + pub fn writable_inputs(&self) -> Option<&[String]> { + self.writable_inputs.as_deref() + } #[must_use] pub fn identifier(&self) -> &str { &self.id @@ -1737,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() @@ -3287,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" => { @@ -3429,6 +3481,47 @@ fn parse_actions(value: Value) -> Result, BRegMetadata .collect::, _>>()?; ensure_unique(inputs.iter().map(|input| input.id.as_str()))?; ensure_unique(inputs.iter().map(|input| input.api_name.as_str()))?; + let maximum_message_count = action + .remove("messages") + .map(|value| { + let mut messages = object(value)?; + let maximum = positive_integer(required(&mut messages, "maximumCount")?)?; + let text_bytes = positive_integer(required(&mut messages, "maximumTextBytes")?)?; + finish(messages)?; + if mode != BRegActionMode::Proposal || maximum > 1000 || text_bytes != 2000 { + return Err(metadata_error(BRegMetadataErrorKind::Shape)); + } + Ok(maximum as u16) + }) + .transpose()?; + let additional_forms = action + .remove("additionalForms") + .map(object) + .transpose()? + .unwrap_or_default(); + if additional_forms.len() > 8 + || mode == BRegActionMode::Immediate && !additional_forms.is_empty() + { + return Err(metadata_error(BRegMetadataErrorKind::Shape)); + } + let additional_forms = additional_forms + .into_iter() + .map(|(id, value)| { + let id = identifier(Value::String(id))?; + let mut form = object(value)?; + let inputs = array(required(&mut form, "inputs")?)? + .into_iter() + .map(parse_action_input) + .collect::, _>>()?; + if !(1..=16).contains(&inputs.len()) { + return Err(metadata_error(BRegMetadataErrorKind::Shape)); + } + ensure_unique(inputs.iter().map(|input| input.id.as_str()))?; + ensure_unique(inputs.iter().map(|input| input.api_name.as_str()))?; + finish(form)?; + Ok((id, inputs)) + }) + .collect::, BRegMetadataError>>()?; let reference_inputs = array(required(&mut action, "referenceInputs")?)? .into_iter() .map(parse_action_reference_input) @@ -3456,6 +3549,28 @@ fn parse_actions(value: Value) -> Result, BRegMetadata .map(parse_action_result_effect) .collect::, _>>()?; ensure_unique(result_effects.iter().map(|effect| effect.effect.as_str()))?; + let subject_input = action + .remove("subject") + .map(|value| { + let mut subject = object(value)?; + let input = identifier(required(&mut subject, "input")?)?; + finish(subject)?; + Ok::<_, BRegMetadataError>(input) + }) + .transpose()?; + if subject_input + .as_ref() + .is_some_and(|subject| !inputs.iter().any(|input| input.id == *subject)) + { + return Err(metadata_error(BRegMetadataErrorKind::DanglingReference)); + } + let writable_inputs = action + .remove("writableInputs") + .map(identifier_array) + .transpose()?; + if let Some(writable) = &writable_inputs { + ensure_unique(writable.iter().map(String::as_str))?; + } let mut access = object(required(&mut action, "access")?)?; let access_profile = identifier(required(&mut access, "selectedProfile")?)?; @@ -3549,9 +3664,13 @@ fn parse_actions(value: Value) -> Result, BRegMetadata input_mode, maximum_input_string_bytes, inputs, + additional_forms, + maximum_message_count, attachments, reference_inputs, required_condition_keys, + subject_input, + writable_inputs, result_effects, access_profile, invoke_path, @@ -3573,7 +3692,14 @@ fn parse_proposal_actions( let mut entry = object(value)?; let action_id = identifier(required(&mut entry, "actionId")?)?; let access_profile = identifier(required(&mut entry, "accessProfile")?)?; - if !identities.insert((action_id.clone(), access_profile.clone())) { + let party = entry + .remove("party") + .map(|value| { + serde_json::from_value::(value) + .map_err(|_| metadata_error(BRegMetadataErrorKind::Shape)) + }) + .transpose()?; + if !identities.insert((action_id.clone(), access_profile.clone(), party)) { return Err(metadata_error(BRegMetadataErrorKind::DuplicateIdentifier)); } let operations = identifier_array(required(&mut entry, "operations")?)?; @@ -3587,6 +3713,13 @@ fn parse_proposal_actions( { return Err(metadata_error(BRegMetadataErrorKind::Shape)); } + let writable_inputs = entry + .remove("writableInputs") + .map(identifier_array) + .transpose()?; + if let Some(writable) = &writable_inputs { + ensure_unique(writable.iter().map(String::as_str))?; + } let readable_context_fields = entry .remove("readableContextFields") .map(api_name_array) @@ -3608,8 +3741,10 @@ fn parse_proposal_actions( Ok(BRegProposalActionDescriptor { action_id, access_profile, + party, operations, readable_inputs, + writable_inputs, readable_context_fields, }) }) diff --git a/crates/registry-breg-client/src/metadata_tests.rs b/crates/registry-breg-client/src/metadata_tests.rs index 4917abe9ea..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, @@ -955,6 +981,53 @@ fn scalar_api_names_and_query_field_identities_remain_strict() { assert!(BRegMetadata::from_slice(&serde_json::to_vec(&source).unwrap()).is_err()); } +#[test] +fn proposal_inventory_keeps_one_entry_per_party_and_its_writable_inputs() { + let mut source = proposal_action_metadata(); + source["proposals"]["actions"] = json!([ + {"actionId":"correct-address","accessProfile":"citizen","party":"owner","operations":["get","edit"], + "readableInputs":["address"],"writableInputs":["address"],"readableContextFields":[]}, + {"actionId":"correct-address","accessProfile":"citizen","party":"subject","operations":["get"], + "readableInputs":["address"],"writableInputs":[],"readableContextFields":[]} + ]); + let metadata = parse(&source); + let entries = metadata.proposal_actions(); + assert_eq!(entries.len(), 2); + assert_eq!( + entries[0].party(), + Some(crate::BRegProposalPartyRole::Owner) + ); + assert_eq!( + entries[0].writable_inputs(), + Some(&["address".to_owned()][..]) + ); + assert_eq!( + entries[1].party(), + Some(crate::BRegProposalPartyRole::Subject) + ); + assert_eq!(entries[1].writable_inputs(), Some(&[][..])); + assert_eq!( + serde_json::to_value(entries).unwrap(), + source["proposals"]["actions"] + ); + let mut duplicate = source.clone(); + duplicate["proposals"]["actions"][1]["party"] = json!("owner"); + assert_eq!( + BRegMetadata::from_slice(&serde_json::to_vec(&duplicate).unwrap()) + .unwrap_err() + .kind(), + BRegMetadataErrorKind::DuplicateIdentifier + ); + let mut unknown = source; + unknown["proposals"]["actions"][1]["party"] = json!("representative"); + assert_eq!( + BRegMetadata::from_slice(&serde_json::to_vec(&unknown).unwrap()) + .unwrap_err() + .kind(), + BRegMetadataErrorKind::Shape + ); +} + #[test] fn proposal_inventory_preserves_exact_profile_operations_and_readable_inputs() { let mut source = proposal_action_metadata(); @@ -1163,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, @@ -1219,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 e4d0d45efa..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; @@ -10,11 +10,19 @@ use time::{format_description::well_known::Rfc3339, OffsetDateTime}; use zeroize::Zeroizing; mod additions; +mod forms; +mod messages; +pub use forms::{BRegProposalForm, BRegProposalFormEntry}; +pub use messages::{ + BRegProposalMessage, BRegProposalMessageOutcome, BRegProposalMessagePage, + BRegProposalMessageSide, BRegProposalMessageTarget, BRegProposalMessages, +}; mod asks; pub use asks::{ BRegProposalAnswerRequest, BRegProposalAsk, BRegProposalAskAnswer, BRegProposalAskState, BRegProposalAskWant, }; +mod response; mod review_asks; mod review_document; pub use additions::{BRegProposalAddition, BRegProposalAdditionSlot}; @@ -408,6 +416,12 @@ pub struct BRegProposalReviewContext { pub fields: Option>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub asks: Vec, + #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] + pub additional_forms: BTreeMap, + /// The Proposal's message thread, read live: its newest messages and + /// links on a displayed context, its counts on a batch read. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub messages: Option, } /// Exact local interface exported by the governed producer, independent of a review policy pin. #[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] @@ -616,6 +630,12 @@ pub struct BRegProposal { attachments: BTreeMap, #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] additions: BTreeMap, + #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] + additional_forms: BTreeMap, + #[serde(default, skip_serializing_if = "Option::is_none")] + form_entry_id: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + messages: Option, #[serde(default, skip_serializing_if = "Vec::is_empty")] asks: Vec, #[serde(default, skip_serializing_if = "Option::is_none")] @@ -624,6 +644,8 @@ pub struct BRegProposal { application_status: Option, #[serde(default, skip_serializing_if = "Option::is_none")] turn: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + party_role: Option, #[serde( default, skip_serializing_if = "Option::is_none", @@ -637,7 +659,24 @@ pub struct BRegProposal { #[serde(skip)] source: Option, } +/// Which party of a Proposal a party-bound grant admitted the caller as. +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Serialize, Deserialize)] +#[serde(rename_all = "kebab-case")] +pub enum BRegProposalPartyRole { + /// The caller filed the Proposal. + Owner, + /// The Proposal is about the caller, who may not have filed it. + Subject, +} + impl BRegProposal { + /// The party a party-bound grant admitted the caller as. `None` for an + /// officer's read and from a server that predates the member. + #[must_use] + pub const fn party_role(&self) -> Option { + self.party_role + } /// Only input fields explicitly disclosed to the selected caller profile. pub fn input(&self) -> Option<&serde_json::Map> { self.input.as_ref() @@ -651,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 @@ -710,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 } @@ -882,6 +941,14 @@ impl BRegProposal { } } self.validate_additions()?; + self.validate_forms()?; + if self + .messages + .as_ref() + .is_some_and(|thread| !messages::valid_thread(thread, &self.id, self.revision)) + { + return Err(refusal()); + } self.validate_asks()?; Ok(()) } @@ -966,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() @@ -975,12 +1047,22 @@ impl BRegProposal { .flat_map(|slot| slot.links.values()), ) .chain(self.addition_links()) + .chain( + self.additional_forms + .values() + .flat_map(|form| form.links.values()), + ) + .chain( + self.messages + .iter() + .flat_map(|thread| thread.links.values()), + ) .chain(self.asks.iter().flat_map(|ask| ask.links.values())) .any(|link| link.access_profile != profile) { return Err(refusal()); } - Ok(self.bind(source)) + Ok(()) } } impl fmt::Debug for BRegProposal { @@ -1321,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() @@ -1399,16 +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()) + || (!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()); } @@ -1458,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()); } @@ -1474,6 +1568,9 @@ impl BaseRegistryClient { && context.id == id && context.action_id == binding.action && valid_review_document(&context, true, false) + && context.context.messages.as_ref().is_none_or(|thread| { + thread.items.is_none() && thread.links.is_empty() + }) && review_asks::profiles(&context, &binding.profile) => { values.push(Some(*context)) @@ -1506,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, }) } @@ -1562,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 @@ -1577,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()); } @@ -1692,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 @@ -1794,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) @@ -1807,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 @@ -1823,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 { @@ -1930,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()); } @@ -1952,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 @@ -1993,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 @@ -2136,6 +2232,12 @@ fn valid_review_document( is_context: bool, include_progress: bool, ) -> bool { + if document.context.messages.as_ref().is_some_and(|thread| { + !is_context || !messages::valid_thread(thread, &document.id, document.revision) + }) { + return false; + } + canonical_proposal_id(&document.id) && identifier(&document.action_id) && digest(&document.action_revision) @@ -2150,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 @@ -2352,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 ( @@ -2405,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, @@ -2601,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", @@ -2712,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, ) -> ( @@ -2723,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(); @@ -2792,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" { @@ -2829,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"); } @@ -3323,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 @@ -3678,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"}), @@ -3685,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"), ] { @@ -4455,6 +4653,50 @@ 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, + "sentAt": "2026-12-01T10:00:00Z", "text": "Received"}], + "links": {"list": {"method": "GET", "path": format!("/v1/proposals/{ID}/messages"), + "accessProfile": "author", "operation": "message", + "availability": {"available": true, "observedRevision": 2}}} + }); + let (client, response, server) = proposal_response_client(value.clone()).await; + let binding = BRegProposalGetBinding::from_metadata( + &json!({"method":"GET","path":"/v1/proposals/{proposal_id}","accessProfiles":["author"]}), + &client.source_binding(), + "author", + ) + .unwrap(); + for count in [1001, 2000] { + value["messages"]["count"] = json!(count); + *response.lock().unwrap() = value.clone(); + let proposal = client.get_proposal(&binding, ID).await.unwrap().value; + let messages = proposal.messages().unwrap(); + assert_eq!((messages.count, messages.unread), (count, 1000)); + } + for (count, unread) in [(2001, 1000), (2000, 1001), (12, 13)] { + value["messages"]["count"] = json!(count); + value["messages"]["unread"] = json!(unread); + *response.lock().unwrap() = value.clone(); + assert!( + matches!( + client.get_proposal(&binding, ID).await, + Err(BaseRegistryClientError::Protocol { + failure: BRegProtocolFailure::Body, + .. + }) + ), + "count={count}, unread={unread}" + ); + } + server.abort(); + } + #[tokio::test] async fn proposal_uuid_lookup_refuses_foreign_bindings_and_noncanonical_ids_before_io() { let source = client("https://registry.example/tenant/"); @@ -4563,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 { @@ -4660,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 635904a129..04c95d3904 100644 --- a/crates/registry-breg-client/src/proposal/asks.rs +++ b/crates/registry-breg-client/src/proposal/asks.rs @@ -27,6 +27,8 @@ pub struct BRegProposalAskAnswer { #[serde(default, skip_serializing_if = "Option::is_none")] pub text: Option, pub additions: Vec, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub form_entries: Vec, pub answered_at: String, } #[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] @@ -41,6 +43,8 @@ pub struct BRegProposalAnswerRequest { pub text: Option, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub additions: Vec, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub form_entries: Vec, } impl fmt::Debug for BRegProposalAsk { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { @@ -58,20 +62,30 @@ impl fmt::Debug for BRegProposalAnswerRequest { } } -fn valid_answer(text: Option<&str>, additions: &[String], wants: &[BRegProposalAskWant]) -> bool { - (text.is_some() || !additions.is_empty()) +fn valid_answer( + text: Option<&str>, + additions: &[String], + forms: &[String], + wants: &[BRegProposalAskWant], +) -> bool { + (text.is_some() || !additions.is_empty() || !forms.is_empty()) && text.is_none_or(|text| { !text.trim().is_empty() && text.len() <= 2000 && !text.contains('\0') }) && (text.is_some() || !wants.contains(&BRegProposalAskWant::Answer {})) - && additions.len() <= 32 - && additions.iter().all(|id| canonical_proposal_id(id)) - && additions - .iter() - .collect::>() - .len() - == additions.len() + && valid_entry_ids(additions) + && valid_entry_ids(forms) && (!additions.is_empty() || !wants.contains(&BRegProposalAskWant::Document {})) + && (!forms.is_empty() + || !wants + .iter() + .any(|want| matches!(want, BRegProposalAskWant::Form { .. }))) +} + +fn valid_entry_ids(ids: &[String]) -> bool { + ids.len() <= 32 + && ids.iter().all(|id| canonical_proposal_id(id)) + && ids.iter().collect::>().len() == ids.len() } impl BRegProposal { @@ -103,7 +117,12 @@ impl BRegProposal { if ask.state != BRegProposalAskState::Answered || at < asked || !at.nanosecond().is_multiple_of(1000) - || !valid_answer(answer.text.as_deref(), &answer.additions, &ask.wants) + || !valid_answer( + answer.text.as_deref(), + &answer.additions, + &answer.form_entries, + &ask.wants, + ) { return Err(refusal()); } @@ -163,7 +182,12 @@ impl BaseRegistryClient { } if ask.state != BRegProposalAskState::Open || ask.answer.is_some() - || !valid_answer(body.text.as_deref(), &body.additions, &ask.wants) + || !valid_answer( + body.text.as_deref(), + &body.additions, + &body.form_entries, + &ask.wants, + ) { return Err(refusal()); } @@ -181,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 @@ -194,6 +219,14 @@ impl BaseRegistryClient { && candidate.due_at == ask.due_at && candidate.answer.as_ref().is_some_and(|answer| { answer.text == body.text + && answer + .form_entries + .iter() + .collect::>() + == body + .form_entries + .iter() + .collect::>() && answer .additions .iter() @@ -229,7 +262,7 @@ mod tests { use super::*; #[test] fn an_answer_without_wants_still_needs_content_before_io() { - assert!(!valid_answer(None, &[], &[])); - assert!(valid_answer(Some("explanation"), &[], &[])); + assert!(!valid_answer(None, &[], &[], &[])); + assert!(valid_answer(Some("explanation"), &[], &[], &[])); } } diff --git a/crates/registry-breg-client/src/proposal/forms.rs b/crates/registry-breg-client/src/proposal/forms.rs new file mode 100644 index 0000000000..4db321dbf2 --- /dev/null +++ b/crates/registry-breg-client/src/proposal/forms.rs @@ -0,0 +1,146 @@ +// SPDX-License-Identifier: Apache-2.0 +use super::*; +use serde_json::json; + +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[derive(Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct BRegProposalForm { + pub id: String, + pub maximum_count: u8, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub items: Option>, + #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] + pub links: BTreeMap, +} + +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[derive(Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct BRegProposalFormEntry { + pub id: String, + pub submission_version: u32, + pub added_at: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub input: Option>, + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub contract_changed: bool, +} + +impl BRegProposal { + pub fn additional_forms(&self) -> &BTreeMap { + &self.additional_forms + } + + pub fn form_entry_id(&self) -> Option<&str> { + self.form_entry_id.as_deref() + } + + pub(super) fn validate_forms(&self) -> Result<(), BaseRegistryClientError> { + if self.additional_forms.len() > 8 + || self + .form_entry_id + .as_deref() + .is_some_and(|id| !canonical_proposal_id(id)) + { + return Err(refusal()); + } + let mut ids = std::collections::BTreeSet::new(); + for (id, form) in &self.additional_forms { + if !identifier(id) + || form.id != *id + || !(1..=32).contains(&form.maximum_count) + || form.items.is_none() && form.links.is_empty() + || form.items.as_ref().is_some_and(|entries| { + entries.len() > 32 + || entries.iter().any(|entry| { + !canonical_proposal_id(&entry.id) + || !ids.insert(&entry.id) + || entry.submission_version != self.submission_version + || proposal_instant(&entry.added_at).is_none() + || entry.contract_changed == entry.input.is_some() + }) + }) + { + return Err(refusal()); + } + for (name, link) in &form.links { + validate_link(link)?; + if name != "add" + || link.operation != "add" + || link.method != "POST" + || link.path != format!("/v1/proposals/{}/additional-forms/{id}", self.id) + || link + .availability + .as_ref() + .is_none_or(|value| !valid_availability(value, self.revision, self.state)) + { + return Err(refusal()); + } + } + } + Ok(()) + } +} + +impl BaseRegistryClient { + /// Append typed inputs using the selected Proposal's advertised form link. + pub async fn add_proposal_form_entry( + &self, + proposal: &BRegProposal, + form_id: &str, + input: &serde_json::Map, + key: &BRegIdempotencyKey, + ) -> Result, BaseRegistryClientError> { + if proposal.source.as_deref() != Some(self.source_binding().as_str()) + || proposal.state != BRegProposalState::Submitted + || input.is_empty() + || input.len() > 16 + { + return Err(refusal()); + } + let form = proposal.additional_forms.get(form_id).ok_or_else(refusal)?; + let link = form.links.get("add").ok_or_else(refusal)?; + if let Some(availability) = link.availability.as_ref().filter(|value| !value.available) { + return Err(unavailable(availability)); + } + let body = serde_json::to_vec(&json!({"input":input})).map_err(|_| refusal())?; + if body.len() > 16_384 { + return Err(refusal()); + } + let response = self.proposal_exchange(link, Some(body), Some(key)).await?; + let invalid = || { + BaseRegistryClientError::protocol( + 200, + BRegProtocolFailure::Body, + Some(response.metadata.trace_id().clone()), + ) + }; + 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() + || current.id != proposal.id + || current.action_id != proposal.action_id + || current.action_revision != proposal.action_revision + || current.submission_version != proposal.submission_version + || current.state != BRegProposalState::Submitted + || current.effect_digest != proposal.effect_digest + || Some(current.revision) != proposal.revision.checked_add(1) + || slot.items.as_ref().is_some_and(|entries| { + !entries + .iter() + .any(|entry| entry.id == entry_id && entry.input.as_ref() == Some(input)) + }) + { + return Err(invalid()); + } + Ok(BRegComplete { + value: current + .bind_profile(self.source_binding(), &link.access_profile) + .map_err(|_| invalid())?, + metadata: response.metadata, + }) + } +} diff --git a/crates/registry-breg-client/src/proposal/messages.rs b/crates/registry-breg-client/src/proposal/messages.rs new file mode 100644 index 0000000000..f1b78ea651 --- /dev/null +++ b/crates/registry-breg-client/src/proposal/messages.rs @@ -0,0 +1,467 @@ +// SPDX-License-Identifier: Apache-2.0 +use super::*; +use serde_json::json; + +const MAX_MESSAGES_PER_SIDE: u16 = 1000; + +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[derive(Clone, Copy, Eq, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "kebab-case")] +pub enum BRegProposalMessageSide { + Party, + Official, +} + +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[derive(Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct BRegProposalMessage { + pub id: String, + pub from: BRegProposalMessageSide, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub party_role: Option, + pub mine: bool, + pub sent_at: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub text: Option, +} + +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[derive(Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct BRegProposalMessages { + pub count: u16, + pub unread: u16, + /// The read position that produced `unread`, supplied by review-context batches. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub reader_side: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub last_sent_at: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub items: Option>, + #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] + pub links: BTreeMap, +} + +#[derive(Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct BRegProposalMessagePage { + pub items: Vec, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub next_cursor: Option, + /// The thread's links, with the write's current condition. + pub links: BTreeMap, +} + +pub enum BRegProposalMessageTarget<'a> { + Proposal(&'a BRegProposal), + Review { + binding: &'a BRegProposalReviewBinding, + document: &'a BRegProposalReviewDocument, + }, +} + +pub enum BRegProposalMessageOutcome { + Proposal(Box), + Review(Box), + /// The thread alone: the answer to a reviewer without Get while no + /// 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 { + pub fn messages(&self) -> Option<&BRegProposalMessages> { + self.messages.as_ref() + } +} + +/// The server's text rule: no control character but a line break or tab +/// (a carriage return only before a line feed), and no character that +/// reorders text or does not display. +fn valid_text(text: &str) -> bool { + let mut characters = text.chars().peekable(); + while let Some(character) = characters.next() { + let allowed = match character { + '\r' => characters.peek() == Some(&'\n'), + '\n' | '\t' => true, + _ => { + !character.is_control() + && !matches!( + character, + '\u{061C}' + | '\u{200B}'..='\u{200F}' + | '\u{2028}'..='\u{202E}' + | '\u{2060}'..='\u{2064}' + | '\u{2066}'..='\u{2069}' + | '\u{FEFF}' + | '\u{E0000}'..='\u{E007F}' + ) + } + }; + if !allowed { + return false; + } + } + !text.trim().is_empty() && text.len() <= 2000 +} + +fn valid_items(items: &[BRegProposalMessage], maximum: usize) -> bool { + let mut ids = std::collections::BTreeSet::new(); + items.len() <= maximum + && items.iter().all(|message| { + canonical_proposal_id(&message.id) + && ids.insert(&message.id) + && proposal_instant(&message.sent_at).is_some() + && (message.from == BRegProposalMessageSide::Party) == message.party_role.is_some() + && message.text.as_deref().is_none_or(valid_text) + }) +} + +pub(super) fn valid_thread(thread: &BRegProposalMessages, id: &str, revision: u64) -> bool { + thread.count <= 2 * MAX_MESSAGES_PER_SIDE + && thread.unread <= MAX_MESSAGES_PER_SIDE + && thread.unread <= thread.count + && thread + .last_sent_at + .as_deref() + .is_none_or(|value| proposal_instant(value).is_some()) + && thread + .items + .as_ref() + .is_none_or(|items| items.len() <= usize::from(thread.count) && valid_items(items, 20)) + && 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> { + fn identity(&self) -> (&str, &str, u64) { + match self { + Self::Proposal(value) => (&value.id, &value.action_id, value.revision), + Self::Review { document, .. } => (&document.id, &document.action_id, document.revision), + } + } + + fn link( + &self, + source: &str, + operation: &str, + ) -> Result<&BRegProposalLink, BaseRegistryClientError> { + match self { + Self::Proposal(value) if value.source.as_deref() == Some(source) => value + .messages() + .and_then(|thread| thread.links.get(operation)), + Self::Review { binding, document } + if binding.source == source + && binding.action == document.action_id + && binding.operation == "get-review-context" + && canonical_proposal_id(&document.id) + && valid_review_document(document, true, false) => + { + document + .context + .messages + .as_ref() + .and_then(|thread| thread.links.get(operation)) + .filter(|link| link.access_profile == binding.profile) + } + _ => None, + } + .ok_or_else(refusal) + } +} + +impl BaseRegistryClient { + pub async fn send_proposal_message( + &self, + target: BRegProposalMessageTarget<'_>, + text: &str, + key: &BRegIdempotencyKey, + ) -> Result, BaseRegistryClientError> { + if !valid_text(text) { + return Err(refusal()); + } + self.proposal_message_command(target, "message", json!({"text":text}), Some(key)) + .await + } + + pub async fn mark_proposal_messages_read( + &self, + target: BRegProposalMessageTarget<'_>, + through: &str, + ) -> Result, BaseRegistryClientError> { + if !canonical_proposal_id(through) { + return Err(refusal()); + } + self.proposal_message_command(target, "markRead", json!({"through":through}), None) + .await + } + + pub async fn list_proposal_messages( + &self, + target: BRegProposalMessageTarget<'_>, + cursor: Option<&str>, + limit: u8, + ) -> Result, BaseRegistryClientError> { + if !(1..=50).contains(&limit) + || cursor.is_some_and(|value| cursor_position(value).is_none()) + { + return Err(refusal()); + } + let source = self.source_binding(); + let link = target.link(&source, "list")?; + let mut query = vec![ + ("accessProfile".into(), link.access_profile.clone()), + ("limit".into(), limit.to_string()), + ]; + if let Some(cursor) = cursor { + query.push(("cursor".into(), cursor.into())); + } + let result = self + .proposal_list_exchange(&link.path, &query, ProblemContext::ProposalThreadList) + .await?; + let invalid = || { + BaseRegistryClientError::protocol( + 200, + BRegProtocolFailure::Body, + Some(result.metadata.trace_id().clone()), + ) + }; + let page: BRegProposalMessagePage = + response::decode(result.value.as_bytes(), response::message_page) + .map_err(|_| invalid())?; + let (id, _, _) = target.identity(); + let observed = page + .links + .values() + .filter_map(|item| item.availability.as_ref()) + .map(|availability| availability.observed_revision) + .collect::>(); + if !valid_items(&page.items, usize::from(limit)) + || 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_position(next).is_none() + || page.items.len() != usize::from(limit) + || cursor.is_some_and(|prior| cursor_position(next) >= cursor_position(prior)) + }) + { + return Err(invalid()); + } + Ok(BRegComplete { + value: page, + metadata: result.metadata, + }) + } + + async fn proposal_message_command( + &self, + target: BRegProposalMessageTarget<'_>, + operation: &str, + body: Value, + key: Option<&BRegIdempotencyKey>, + ) -> Result, BaseRegistryClientError> { + let source = self.source_binding(); + let link = target.link(&source, operation)?; + if let Some(availability) = link.availability.as_ref().filter(|value| !value.available) { + return Err(unavailable(availability)); + } + let (id, action, prior) = target.identity(); + 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, + BRegProtocolFailure::Body, + Some(response.metadata.trace_id().clone()), + ) + }; + let valid_revision = |revision| { + if key.is_some() { + Some(revision) == prior.checked_add(1) + } else { + revision >= prior + } + }; + let text = body.get("text").and_then(Value::as_str); + let matches_outcome = |thread: &BRegProposalMessages| { + text.is_none_or(|text| { + thread + .items + .as_ref() + .and_then(|items| items.first()) + .is_some_and(|entry| entry.mine && entry.text.as_deref() == Some(text)) + }) + }; + 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 != action_revision + || current.submission_version != submission_version + || current.effect_digest.as_deref() != effect_digest) + || current + .messages + .as_ref() + .is_none_or(|thread| !matches_outcome(thread)) + || current.discloses_application_actor() + { + return 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) + || 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 None; + } + Some(BRegProposalMessageOutcome::Review(Box::new(current))) + })(); + let thread = (|| { + let thread: BRegProposalMessages = + response::decode_value(document, response::thread).ok()?; + let observed = thread + .links + .values() + .filter_map(|item| item.availability.as_ref()) + .map(|availability| availability.observed_revision) + .collect::>(); + if !matches_outcome(&thread) + || observed.len() != 1 + || observed.iter().any(|revision| !valid_revision(*revision)) + || !valid_thread(&thread, id, observed.into_iter().next().unwrap_or(0)) + || thread + .links + .values() + .any(|item| item.access_profile != link.access_profile) + { + return None; + } + 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()), + } + } + }; + Ok(BRegComplete { + value, + metadata: response.metadata, + }) + } +} + +fn cursor_position(value: &str) -> Option { + value + .parse::() + .ok() + .filter(|position| *position > 0 && position.to_string() == value) +} 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/proposal/review_asks.rs b/crates/registry-breg-client/src/proposal/review_asks.rs index 9c49ba744c..f18116187e 100644 --- a/crates/registry-breg-client/src/proposal/review_asks.rs +++ b/crates/registry-breg-client/src/proposal/review_asks.rs @@ -23,6 +23,8 @@ pub struct BRegProposalReviewAnswer { #[serde(default, skip_serializing_if = "Option::is_none")] pub text: Option, pub documents: Vec, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub form_entries: Vec, pub answered_at: String, } #[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] @@ -93,7 +95,10 @@ pub(super) fn valid(document: &BRegProposalReviewDocument) -> bool { text.trim().is_empty() || text.len() > 2000 || text.contains('\0') }) || (answer.text.is_none() && ask.wants.contains(&BRegProposalAskWant::Answer {})) - || (answer.text.is_none() && answer.documents.is_empty()) + || (answer.text.is_none() + && answer.documents.is_empty() + && answer.form_entries.is_empty()) + || answer.form_entries.len() > 32 || answer.documents.len() > 32 || (answer.documents.is_empty() && ask.wants.contains(&BRegProposalAskWant::Document {})) 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 a5dfc8b519..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()))); @@ -2000,6 +2040,7 @@ async fn answer_commands_bind_the_selected_ask_and_validate_before_tokens_or_io( assert_eq!(fixture.token.0.load(Ordering::SeqCst), tokens); assert_eq!(fixture.requests.load(Ordering::SeqCst), requests); let body = BRegProposalAnswerRequest { + form_entries: Vec::new(), text: Some("explanation".into()), additions: vec![], }; diff --git a/crates/registry-breg-client/tests/proposal_party.rs b/crates/registry-breg-client/tests/proposal_party.rs new file mode 100644 index 0000000000..855c5e766e --- /dev/null +++ b/crates/registry-breg-client/tests/proposal_party.rs @@ -0,0 +1,33 @@ +// SPDX-License-Identifier: Apache-2.0 +//! The Proposal document names the party a party-bound grant admitted. +use registry_breg_client::{BRegProposal, BRegProposalPartyRole}; +use serde_json::{json, Value}; + +fn proposal(party: Option<&str>) -> Value { + let mut value = json!({"id":"00000000-0000-4000-8000-000000000001","actionId":"apply-for-licence", + "actionRevision":format!("sha256:{}","a".repeat(64)),"submissionVersion":1,"revision":2, + "state":"submitted","turn":"official","effectDigest":format!("sha256:{}","b".repeat(64)),"links":{}}); + if let Some(party) = party { + value["partyRole"] = json!(party); + } + value +} + +fn decode(value: &Value) -> Result { + BRegProposal::from_slice(&serde_json::to_vec(value).unwrap()) +} + +#[test] +fn party_role_decodes_and_stays_closed() { + assert_eq!( + decode(&proposal(Some("subject"))).unwrap().party_role(), + Some(BRegProposalPartyRole::Subject) + ); + assert_eq!( + decode(&proposal(Some("owner"))).unwrap().party_role(), + Some(BRegProposalPartyRole::Owner) + ); + // An officer's read carries none. + assert_eq!(decode(&proposal(None)).unwrap().party_role(), None); + assert!(decode(&proposal(Some("representative"))).is_err()); +} 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 0741dbaa76..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.", ), @@ -2251,10 +2259,21 @@ fn problem_detail(code: BRegProblemCode) -> &'static str { Code::PreconditionFailed => "The mutation precondition failed.", Code::PreconditionRequired => "The mutation precondition is required.", Code::ProfileNotAuthorized => "No access profile admits this caller for this request.", + Code::ProposalFormLimitReached => { + "The submission has reached the entry limit for this form." + } + Code::ProposalFormUndeclared => "The Action does not declare this additional form.", + Code::ProposalMessageLimitReached => "This Proposal's message thread is full.", Code::ProposalRejected => { "The review rejected this Proposal, and a rejection is final. A review result of changes-requested is what lets a Proposal be revised for another attempt." } Code::ProposalReviewResultMismatch => "The current review result does not match the retained approval.", + Code::ProposalSubjectChanged => { + "The person this Proposal is about changed since it was first submitted. Cancel it and file a new Proposal." + } + Code::ProposalSubjectNotCaller => { + "This Proposal names someone other than you as the person it is about, and your access profile files only for yourself." + } Code::ProposalSubmissionExpired => { "The review result and application receipt of the submission are no longer retained." } @@ -2450,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; @@ -2467,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] @@ -3185,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, @@ -3195,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, @@ -3209,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 @@ -3222,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 @@ -3238,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() @@ -3248,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 @@ -3270,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"); @@ -3459,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/citizen_project.rs b/crates/registry-breg-mcp/tests/support/citizen_project.rs index 6d916ff35e..f670514d69 100644 --- a/crates/registry-breg-mcp/tests/support/citizen_project.rs +++ b/crates/registry-breg-mcp/tests/support/citizen_project.rs @@ -37,7 +37,7 @@ pub fn project() -> Value { "permissions":{"records":[{"recordType":"person-address","operations":["get","list"], "readableFields":["address-line","locality","postal-code"],"rowBoundaries":boundary}], "actions":[{"action":"correct-address","operations":["start"],"targets":targets}], - "proposals":[{"action":"correct-address","operations":operations,"ownership":"caller", + "proposals":[{"action":"correct-address","operations":operations,"party":"owner", "readableInputs":inputs,"targets":targets}]}}); if actor == "agent" { profile["requiredPurposes"] = json!(["address-correction"]); 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/Cargo.toml b/crates/registry-breg/Cargo.toml index e31e51cb05..98d4aa1280 100644 --- a/crates/registry-breg/Cargo.toml +++ b/crates/registry-breg/Cargo.toml @@ -473,6 +473,11 @@ name = "postgres_proposal_security" path = "tests/postgres_proposal_security.rs" required-features = ["postgres-test"] +[[test]] +name = "postgres_proposal_subject" +path = "tests/postgres_proposal_subject.rs" +required-features = ["postgres-test"] + [[test]] name = "postgres_proposal_s3" path = "tests/postgres_proposal_s3.rs" diff --git a/crates/registry-breg/src/access.rs b/crates/registry-breg/src/access.rs index d1c9f26081..34635c893d 100644 --- a/crates/registry-breg/src/access.rs +++ b/crates/registry-breg/src/access.rs @@ -8,8 +8,9 @@ use serde::Serialize; use crate::compiler::operation_id; use crate::contract::{ AccessProfileSource, AccessRequirementsSource, ActorKindSource, BoundaryOperator, - Classification, ConsentIssuerSource, EntitySource, FieldTypeSource, MembershipBoundarySource, - Operation, ProjectAccessProfileSource, RegistryProject, RowBoundarySource, + Classification, ConsentIssuerSource, EntitySource, ExpandedMembershipBoundarySource, + FieldTypeSource, MembershipBoundarySource, Operation, ProjectAccessProfileSource, + RegistryProject, RowBoundarySource, }; use crate::diagnostics::Diagnostic; use crate::model::{ @@ -108,34 +109,120 @@ pub(crate) fn validate_access_requirements( } } +/// A direct write that sets a reference field must name a record the same +/// profile can read. Without a `get` or `reference` grant on the target +/// Record type every such write would be refused at run time, so the grant +/// is required here. A `reference` grant serves nothing else, so one that no +/// write of its profile uses is refused too. Predecessor rehearsal permits a +/// missing grant while reconstructing a schema under the archived authority. +pub(crate) fn validate_reference_targets( + entities: &BTreeMap, + require_target_grants: bool, + errors: &mut Vec, +) { + let mut named = BTreeSet::new(); + for entity in entities.values() { + for grant in &entity.access_profiles { + if !grant.operations.iter().any(|operation| { + matches!( + operation, + Operation::Create | Operation::Patch | Operation::Batch | Operation::Import + ) + }) { + continue; + } + for field_id in &grant.writable_fields { + let Some(crate::contract::FieldTypeSource::Reference { target, .. }) = entity + .fields + .iter() + .find(|field| field.id == *field_id) + .map(|field| &field.field_type) + else { + continue; + }; + // An unknown target has its own diagnostic. + let Some(target) = entities.get(target) else { + continue; + }; + named.insert((target.id.as_str(), grant.id.as_str())); + let readable = target.access_profiles.iter().any(|candidate| { + candidate.id == grant.id + && (candidate.operations.contains(&Operation::Get) + || candidate.operations.contains(&Operation::Reference)) + }); + if require_target_grants && !readable { + errors.push(Diagnostic::error( + "breg.access.reference-target-ungranted", + format!( + "recordTypes[id={}].accessProfiles[id={}].writableFields[field={field_id}]", + entity.id, grant.id + ), + "a direct write names a referenced record only if the same profile can read it; grant this profile get, or reference to name records without reading them, on the referenced Record type, bounded to the records it may name", + )); + } + } + } + } + for entity in entities.values() { + for grant in &entity.access_profiles { + if grant.operations.contains(&Operation::Reference) + && !named.contains(&(entity.id.as_str(), grant.id.as_str())) + { + errors.push(Diagnostic::error( + "breg.access.reference-grant-unused", + format!( + "recordTypes[id={}].accessProfiles[id={}].operations", + entity.id, grant.id + ), + "no direct write of this profile names a record of this Record type, so the reference grant admits nothing; remove it, or make the profile's reference field to this Record type writable", + )); + } + } + } +} + pub(crate) fn check_profile( requirements: &AccessRequirementsSource, profile: &AccessProfileSource, path: &str, errors: &mut Vec, ) { - for scope in requirements - .required_scopes - .difference(&profile.required_scopes) - { + check_profile_authority( + requirements, + &profile.required_scopes, + &profile.required_purposes, + path, + errors, + ); + for boundary in &requirements.row_boundaries { + if !profile.row_boundaries.contains(boundary) { + errors.push(Diagnostic::error( + "breg.access.requirements-row-boundary-missing", + format!("{path}.rowBoundaries[field={}]", boundary.field), + "Include the Record type's exact field, claim and operator binding. Request filters and other claim names do not satisfy this requirement.", + )); + } + } +} + +pub(crate) fn check_profile_authority( + requirements: &AccessRequirementsSource, + required_scopes: &crate::contract::UniqueSet, + required_purposes: &crate::contract::UniqueSet, + path: &str, + errors: &mut Vec, +) { + for scope in requirements.required_scopes.difference(required_scopes) { errors.push(Diagnostic::error("breg.access.requirements-scope-missing", format!("{path}.requiredScopes[value={scope}]"), "add the record type's mandatory scope to this profile; granting other scopes does not satisfy it")); } if !requirements.allowed_purposes.is_empty() - && (profile.required_purposes.is_empty() - || !profile - .required_purposes - .is_subset(&requirements.allowed_purposes)) + && (required_purposes.is_empty() + || !required_purposes.is_subset(&requirements.allowed_purposes)) { errors.push(Diagnostic::error("breg.access.requirements-purpose-widened", format!("{path}.requiredPurposes"), "require a nonempty subset of the record type's allowedPurposes; an empty list allows every purpose")); } - for boundary in &requirements.row_boundaries { - if !profile.row_boundaries.contains(boundary) { - errors.push(Diagnostic::error("breg.access.requirements-row-boundary-missing", format!("{path}.rowBoundaries[field={}]", boundary.field), - "include the record type's exact field, claim, and operator binding; request filters and other claim names do not satisfy this requirement")); - } - } } const TASK_GRANT_ROWS_UNBOUND: &str = "breg.access-profile.task-grant-rows-unbound"; @@ -157,10 +244,14 @@ pub(crate) fn access_findings(entities: &BTreeMap) -> Vec< findings.push(Diagnostic::finding("breg.access.profile-unrestricted-collection", format!("{path}.rowBoundaries"), "this profile lists rows without claim-bound or membership restrictions; configured consent and other disclosure checks still apply. Caller filters are not authorization. Review this broad access and restrict the profile to intended callers. Statistical release publishers require unrestricted reads of their dataset dependencies")); } + // A reference grant serves no read: an unrestricted one lets the + // profile's writes name any active record, as every write could + // before writes checked their references. if entity.classification != Classification::Public && profile.row_boundaries.is_empty() && profile.membership_boundaries.is_empty() && !profile.operations.contains(&Operation::List) + && !profile.operations.contains(&Operation::Reference) && !caller_is_bounded { findings.push(Diagnostic::finding("breg.access.profile-unrestricted-rows", format!("{path}.rowBoundaries"), @@ -377,7 +468,7 @@ pub(crate) fn compiled_access_findings( grant.entity_target_locks().map(move |target| { ( &target.entity_id, - &target.row_boundaries, + target.row_boundaries.is_empty() && target.membership_boundaries.is_empty(), format!( "actions[id={}].permissions[profile={}].targets[recordType={}].rowBoundaries", action.id, grant.profile_id, target.entity_id @@ -392,7 +483,7 @@ pub(crate) fn compiled_access_findings( grant.targets.iter().map(move |target| { ( &target.entity_id, - &target.row_boundaries, + target.row_boundaries.is_empty() && target.membership_boundaries.is_empty(), format!( "actions[id={}].execution.proposal.permissions[profile={}].targets[recordType={}].rowBoundaries", action.id, grant.profile_id, target.entity_id @@ -400,8 +491,8 @@ pub(crate) fn compiled_access_findings( ) }) }); - for (entity_id, boundaries, path) in action_targets.chain(proposal_targets) { - if boundaries.is_empty() + for (entity_id, unbounded, path) in action_targets.chain(proposal_targets) { + if unbounded && entities .get(entity_id) .is_some_and(|entity| entity.classification != Classification::Public) @@ -614,13 +705,16 @@ fn ungated_client_findings(entity: &CompiledEntity, findings: &mut Vec>() .join(", "); for profile in entity.access_profiles.values() { - // A create answers with the row the caller just wrote, and an action - // target only lets the action reference a row, so neither reads an - // existing row without consent. - let reads_existing_rows = profile - .operations - .iter() - .any(|operation| !matches!(operation, Operation::Create | Operation::Invoke)); + // A create answers with the row the caller just wrote, an action + // target only lets the action reference a row, and a reference grant + // only lets a direct write name one, so none reads an existing row + // without consent. + let reads_existing_rows = profile.operations.iter().any(|operation| { + !matches!( + operation, + Operation::Create | Operation::Invoke | Operation::Reference + ) + }); if profile.readable_fields.is_empty() || !reads_existing_rows || !crate::consent::requirements(entity, &profile.id).is_empty() @@ -852,7 +946,7 @@ fn inspect_record_profile( profile: &AccessProfileSource, ) -> serde_json::Value { let mut value = serde_json::to_value(profile).expect("compiled access profile serializes"); - if profile.row_boundaries.is_empty() { + if profile.row_boundaries.is_empty() && profile.membership_boundaries.is_empty() { value["rowBoundaries"] = serde_json::json!("unrestricted"); } value["allowCount"] = serde_json::json!(profile.allow_count); @@ -879,8 +973,11 @@ pub struct RowReachExplanation { pub rows: &'static str, pub row_boundaries: Vec, #[serde(skip_serializing_if = "Vec::is_empty")] - pub membership_boundaries: Vec, + pub membership_boundaries: Vec, pub owner_only: bool, + /// The Proposal party the grant is bound to, for a Proposal target. + #[serde(skip_serializing_if = "Option::is_none")] + pub party: Option, /// Action target authority is enforced only while the named Action runs. /// It is an additional grant and never becomes ordinary Record CRUD. #[serde(skip_serializing_if = "Option::is_none")] @@ -911,14 +1008,41 @@ fn row_reach( entities: &BTreeMap, actions: &CompiledActionInventory, ) -> Vec { + let record_memberships = |entries: &[MembershipBoundarySource]| { + entries + .iter() + .filter_map(|entry| match entry { + MembershipBoundarySource::Expanded(entry) => Some(entry.clone()), + MembershipBoundarySource::Declared(_) => None, + }) + .collect() + }; + let target_memberships = |entries: &[crate::model::CompiledMembershipBoundary]| { + entries + .iter() + .filter_map(|entry| { + let declaration = entities + .get(&entry.membership_entity)? + .membership + .as_ref()?; + Some(ExpandedMembershipBoundarySource { + field: entry.field.clone(), + membership_entity: entry.membership_entity.clone(), + membership_key_field: declaration.key.clone(), + principal_field: declaration.principal.clone(), + active_field: declaration.active.clone(), + }) + }) + .collect() + }; let mut reach = Vec::new(); let mut add = |entity: &str, profile: &str, source_path: String, surface, boundaries: &[RowBoundarySource], - memberships: &[MembershipBoundarySource], - owner, + memberships: Vec, + party: Option, action_target_authority| { reach.push(RowReachExplanation { entity: entity.to_owned(), @@ -932,8 +1056,9 @@ fn row_reach( (false, false) => "claim_and_membership_bound", }, row_boundaries: boundaries.to_vec(), - membership_boundaries: memberships.to_vec(), - owner_only: owner, + membership_boundaries: memberships, + owner_only: party == Some(crate::contract::ProposalParty::Owner), + party, action_target_authority, }); }; @@ -946,8 +1071,8 @@ fn row_reach( format!("{path}.rowBoundaries"), "record", &profile.row_boundaries, - &profile.membership_boundaries, - false, + record_memberships(&profile.membership_boundaries), + None, None, ); for grant in &profile.read_paths { @@ -960,8 +1085,8 @@ fn row_reach( format!("{path}.readPaths[path={}]", grant.path), "read_path", &profile.row_boundaries, - &profile.membership_boundaries, - false, + record_memberships(&profile.membership_boundaries), + None, None, ); } @@ -979,8 +1104,8 @@ fn row_reach( ), "action_target", &target.row_boundaries, - &[], - false, + target_memberships(&target.membership_boundaries), + None, Some(ActionTargetAuthorityExplanation { enforcement: "runtime_enforced", record_grant_relationship: "additional", @@ -1006,7 +1131,8 @@ fn row_reach( | Operation::Revisions | Operation::Snapshot | Operation::Invoke - | Operation::Start => "existing_target", + | Operation::Start + | Operation::Reference => "existing_target", }, operation: use_.operation, source: use_.source.clone(), @@ -1028,8 +1154,8 @@ fn row_reach( ), "proposal_target", &target.row_boundaries, - &[], - grant.ownership == Some(crate::contract::ProposalOwnership::Caller), + target_memberships(&target.membership_boundaries), + grant.party, None, ); } diff --git a/crates/registry-breg/src/api/actions.rs b/crates/registry-breg/src/api/actions.rs index 30a9d2c214..47d66c802d 100644 --- a/crates/registry-breg/src/api/actions.rs +++ b/crates/registry-breg/src/api/actions.rs @@ -191,6 +191,7 @@ fn authorize_action_mode<'a>( Some(selected), crate::postgres::ProposalAuthorityOperation::Start, None, + proposals::PartySelection::Any, ) .map_err(|err| match err { proposals::ProposalAdmissionError::Refused(check) => check, @@ -295,6 +296,18 @@ fn authorize_action_mode<'a>( target_authority, grant.results.clone(), ) + .with_target_memberships( + grant + .entity_target_locks() + .filter(|target| !target.membership_boundaries.is_empty()) + .map(|target| { + ( + target.entity_id.clone(), + target.membership_boundaries.clone(), + ) + }) + .collect(), + ) .with_audit_context(claims) .with_task_grant(task_grant), admitted_profiles: vec![selected.to_owned()], @@ -563,6 +576,9 @@ pub(super) async fn dispatch( } } } + Err(MutationError::MembershipPreconditionFailed) => { + membership_precondition_problem(&correlation) + } Err(error) => mutation_problem(error), } } @@ -581,6 +597,9 @@ pub(super) async fn dispatch( Err(crate::mutation::MutationError::PreconditionFailed) => { concealed(FailedCheck::RowBoundary) } + Err(MutationError::MembershipPreconditionFailed) => { + concealed(FailedCheck::Membership) + } Err(error) => mutation_problem(error), } } diff --git a/crates/registry-breg/src/api/actions/availability.rs b/crates/registry-breg/src/api/actions/availability.rs index 15db17d548..ec1d31755f 100644 --- a/crates/registry-breg/src/api/actions/availability.rs +++ b/crates/registry-breg/src/api/actions/availability.rs @@ -6,6 +6,7 @@ use super::*; use crate::contract::FieldTypeSource; +use crate::postgres::ActionTargetMembershipObservation; pub(super) enum Availability { Satisfied { @@ -115,6 +116,12 @@ pub(super) async fn observe( record_id, &guard_fields, &boundaries, + action + .context + .target_memberships() + .get(target) + .map(Vec::as_slice) + .unwrap_or_default(), correlation, ) .await? @@ -184,6 +191,7 @@ pub(in crate::api) async fn observe_target( record_id: &str, guard_fields: &BTreeSet, boundaries: &[crate::postgres::RowBoundaryContext], + memberships: &[crate::model::CompiledMembershipBoundary], correlation: &RequestCorrelation, ) -> Result, Response> { let target = &entity.id; @@ -196,6 +204,13 @@ pub(in crate::api) async fn observe_target( .filter(|boundary| boundary.field() != entity.canonical_id.id) .map(|boundary| boundary.field().to_owned()), ) + // The canonical identifier is the row itself, not a readable field. + .chain( + memberships + .iter() + .filter(|boundary| boundary.field != entity.canonical_id.id) + .map(|boundary| boundary.field.clone()), + ) .collect::>(); let Some(route) = service .registry @@ -222,6 +237,7 @@ pub(in crate::api) async fn observe_target( if let Some(refusal) = field_encryption_refusal(service, entity) { return Err(refusal); } + let membership_context = (!memberships.is_empty()).then(|| surface.context.clone()); let read = service .records .get(RecordReadRequest { @@ -286,6 +302,30 @@ pub(in crate::api) async fn observe_target( { return Err(concealed(FailedCheck::RowBoundary)); } + if let Some(context) = &membership_context { + let mutations = service.mutations.as_ref().ok_or_else(unavailable)?; + let observation = mutations + .observe_action_target_membership( + context, + entity, + Uuid::parse_str(record_id).map_err(|_| unavailable())?, + i64::try_from(revision).map_err(|_| unavailable())?, + memberships, + &fields, + ) + .await + .map_err(|_| unavailable())?; + match observation { + ActionTargetMembershipObservation::Authorized => {} + ActionTargetMembershipObservation::OutsideBoundary => { + return Err(concealed(FailedCheck::Membership)); + } + ActionTargetMembershipObservation::Withheld => return Ok(None), + ActionTargetMembershipObservation::Missing => { + return Err(concealed(FailedCheck::Visibility)); + } + } + } Ok(Some(ObservedTarget { revision, current })) } diff --git a/crates/registry-breg/src/api/attachments.rs b/crates/registry-breg/src/api/attachments.rs index eba680ff4a..dcecddc6d4 100644 --- a/crates/registry-breg/src/api/attachments.rs +++ b/crates/registry-breg/src/api/attachments.rs @@ -143,10 +143,10 @@ async fn authorize<'a>( None }; let slot = addition_slot.unwrap_or(slot); - let grant = proposal.permissions.iter().find(|grant| { - grant.profile_id == authority.common.access_profile() - && grant.operations.contains(&operation) - }); + // The entry that admitted the caller, party included, decides the slot. + let grant = authority + .permission(proposal) + .filter(|grant| grant.operations.contains(&operation)); let allowed = grant.is_some_and(|grant| match operation { ProposalOperation::Get => grant.readable_attachments.contains(slot), ProposalOperation::GetReviewContext => match context_source { @@ -254,6 +254,23 @@ async fn mutate( ) .await } + MutationError::MembershipPreconditionFailed => { + super::proposals::admitted_http_refusal_with( + mutations, + &authority, + mutation_method(removal, addition), + &correlation, + || { + if addition { + concealed(FailedCheck::Membership) + } else { + // Count the generic 412 only after audit accepts it. + membership_precondition_problem(&correlation) + } + }, + ) + .await + } MutationError::PreconditionFailed if addition => { super::proposals::admitted_http_refusal( mutations, @@ -371,7 +388,9 @@ async fn mutate( reason: None, executor_lease: None, rebase_start_authority: None, + form: None, answer: None, + message: None, attachment: Some(crate::attachment::AttachmentMutation { slot_id: slot, content_type, @@ -388,6 +407,12 @@ async fn mutate( "", service.field_encryption.as_deref(), ), + Err(MutationError::MembershipPreconditionFailed) if addition => { + concealed(FailedCheck::Membership) + } + Err(MutationError::MembershipPreconditionFailed) => { + membership_precondition_problem(&correlation) + } Err(MutationError::PreconditionFailed) => precondition_failed(), Err(error) => super::proposals::proposal_target_problem(error), } @@ -510,6 +535,7 @@ async fn download_file( .header(VARY, "authorization") .body(Body::from(bytes)) .unwrap_or_else(|_| unavailable()), + Err(MutationError::MembershipPreconditionFailed) => concealed(FailedCheck::Membership), Err(MutationError::PreconditionFailed) => concealed(FailedCheck::Visibility), Err(error) => super::proposals::proposal_target_problem(error), } diff --git a/crates/registry-breg/src/api/context.rs b/crates/registry-breg/src/api/context.rs index 2a1071e4bd..50c664a1bd 100644 --- a/crates/registry-breg/src/api/context.rs +++ b/crates/registry-breg/src/api/context.rs @@ -411,6 +411,15 @@ impl VerifiedRowBoundary { } } + #[cfg(test)] + pub(crate) fn equals_for_test(field: &str, value: &str) -> Self { + Self::new( + field.to_owned(), + RowBoundaryOperator::Equals, + BTreeSet::from([value.to_owned()]), + ) + } + #[must_use] pub fn field(&self) -> &str { &self.field @@ -462,9 +471,34 @@ pub struct AuthorizedRequestContext { human_identity: Option, recipients: BTreeSet, caller_issuer: Option, + /// The caller's context on each Record type a direct write may reference. + reference_contexts: Vec<(String, AuthorizedRequestContext)>, + /// Proof for the target grants. The reason text is retained only when the + /// written type's own grant calls for it. + reference_reason_validated: bool, } impl AuthorizedRequestContext { + pub(crate) fn with_reference_context( + mut self, + entity_id: &str, + context: AuthorizedRequestContext, + ) -> Self { + self.reference_contexts + .push((entity_id.to_owned(), context)); + self + } + + /// A target whose reason requirement was not met has no usable context. + /// This also covers operations such as Import that do not bind the header. + pub(crate) fn reference_contexts( + &self, + ) -> impl Iterator { + self.reference_contexts.iter().filter(|(_, reference)| { + !reference.requires_access_reason || self.reference_reason_validated + }) + } + pub(crate) fn new( principal: Option, purpose: Option, @@ -485,6 +519,8 @@ impl AuthorizedRequestContext { human_identity: None, recipients: BTreeSet::new(), caller_issuer: None, + reference_contexts: Vec::new(), + reference_reason_validated: false, } } @@ -548,19 +584,39 @@ impl AuthorizedRequestContext { self.bind_access_reason(headers) } - /// Validate only the access reason, for surfaces that never log reads. + /// Bind the reason to the route grant and any reference-target grants. + /// A refusal by the route grant is a request error. A refusal by a target + /// grant leaves that type unavailable if the write tries to reference it. pub(crate) fn bind_access_reason( &mut self, headers: &axum::http::HeaderMap, ) -> Result<(), AccessBindingRefusal> { - if self.requires_access_reason { - self.access_reason = Some( - crate::subject_access_log::access_reason(headers) - .map_err(|()| AccessBindingRefusal::ReasonRequired)?, - ); - } + self.access_reason = self.validate_access_reason(headers)?; Ok(()) } + + /// Validate the reason and admit eligible target contexts. Return reason + /// text only for a route grant that requires it, so callers without + /// subject access logging can discard it before reaching storage. + pub(crate) fn validate_access_reason( + &mut self, + headers: &axum::http::HeaderMap, + ) -> Result, AccessBindingRefusal> { + let target_requires_reason = self + .reference_contexts + .iter() + .any(|(_, reference)| reference.requires_access_reason); + if self.requires_access_reason || target_requires_reason { + let reason = crate::subject_access_log::access_reason(headers); + self.reference_reason_validated = reason.is_ok(); + if self.requires_access_reason { + return reason + .map(Some) + .map_err(|()| AccessBindingRefusal::ReasonRequired); + } + } + Ok(None) + } pub(crate) fn audit_context(&self) -> Option<&crate::audit::RequestAuditContext> { self.audit_context.as_ref() } @@ -626,6 +682,7 @@ pub struct AuthorizedActionContext { purpose: Option, selected_profile: String, target_authority: BTreeMap>, + target_memberships: BTreeMap>, result_effects: BTreeSet, audit_context: Option, task_grant: Option, @@ -647,6 +704,7 @@ impl AuthorizedActionContext { purpose, selected_profile, target_authority, + target_memberships: BTreeMap::new(), result_effects, audit_context: None, task_grant: None, @@ -654,6 +712,20 @@ impl AuthorizedActionContext { } } + pub(crate) fn with_target_memberships( + mut self, + memberships: BTreeMap>, + ) -> Self { + self.target_memberships = memberships; + self + } + + pub(crate) fn target_memberships( + &self, + ) -> &BTreeMap> { + &self.target_memberships + } + pub(crate) fn with_audit_context(mut self, claims: &VerifiedRequestClaims) -> Self { self.audit_context = crate::audit::RequestAuditContext::from_claims(claims); self.caller_issuer = claims.caller_issuer().map(str::to_owned); @@ -744,6 +816,57 @@ fn validate_value(value: String) -> Result { mod tests { use super::*; + #[test] + fn a_reference_context_requires_its_own_access_reason() { + use crate::subject_access_log::ACCESS_REASON_HEADER; + use axum::http::{HeaderMap, HeaderValue}; + + let context = || { + AuthorizedRequestContext::new( + Some("caller".to_owned()), + None, + "writer".to_owned(), + Vec::new(), + ) + }; + let mut write = context() + .with_reference_context("open-target", context()) + .with_reference_context( + "reason-target", + context().with_access_reason_requirement(true), + ); + let reached = |context: &AuthorizedRequestContext| { + context + .reference_contexts() + .map(|(target, _)| target.clone()) + .collect::>() + }; + + // Import carries the admitted context without binding access reasons. + assert_eq!(reached(&write), ["open-target"]); + + let mut headers = HeaderMap::new(); + write.bind_access_reason(&headers).unwrap(); + assert_eq!(reached(&write), ["open-target"]); + headers.insert(ACCESS_REASON_HEADER, HeaderValue::from_static("bad!")); + write.bind_access_reason(&headers).unwrap(); + assert_eq!(reached(&write), ["open-target"]); + + let mut required_write = write.clone().with_access_reason_requirement(true); + assert_eq!( + required_write.bind_access_reason(&headers), + Err(AccessBindingRefusal::ReasonRequired) + ); + + headers.insert(ACCESS_REASON_HEADER, HeaderValue::from_static("cmV2aWV3")); + write.bind_access_reason(&headers).unwrap(); + assert_eq!(reached(&write), ["open-target", "reason-target"]); + assert_eq!(write.access_reason(), None); + required_write.bind_access_reason(&headers).unwrap(); + assert_eq!(reached(&required_write), ["open-target", "reason-target"]); + assert_eq!(required_write.access_reason(), Some("review")); + } + #[test] fn authenticated_context_preserves_identity_values_larger_than_review_protocol_bounds() { let identity = registry_review_client::HumanIdentity { 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 2e7557230a..d6ce97f69b 100644 --- a/crates/registry-breg/src/api/ingestion.rs +++ b/crates/registry-breg/src/api/ingestion.rs @@ -92,6 +92,64 @@ pub(super) fn routes(service: &HttpService) -> Router> { app } +async fn admit_ingestion<'a>( + service: &'a HttpService, + mutations: &crate::postgres::PostgresRecordMutationService, + route: &'a CompiledRoute, + claims: &VerifiedRequestClaims, + options: &QueryOptions, + headers: &HeaderMap, + correlation: &RequestCorrelation, +) -> Result, Response> { + let mut surface = match authorize_route_with_reason(service, route, claims, options) { + Ok(surface) => surface, + Err(RouteAdmissionError::Ambiguous(profiles)) => { + return Err(crate::correlation::ambiguous_access_profile_response( + profiles, + )); + } + Err(RouteAdmissionError::Refused(refusal)) => { + return Err(audited_mutation_admission_refusal( + mutations, + route, + options, + claims, + None, + correlation, + refusal.check, + ) + .await); + } + }; + if let Err(refusal) = + validate_ingestion_access_reason(route.operation, &mut surface.context, headers) + { + return Err(audited_mutation_refusal( + mutations, + route, + &surface.context, + None, + access_binding_refusal(refusal), + correlation, + ) + .await); + } + Ok(surface) +} + +fn validate_ingestion_access_reason( + bulk: Operation, + context: &mut AuthorizedRequestContext, + headers: &HeaderMap, +) -> Result<(), context::AccessBindingRefusal> { + // Import grants cannot require a reason and do not supply one for + // reference probes. Batch validates it without retaining the text. + if bulk == Operation::Batch { + drop(context.validate_access_reason(headers)?); + } + Ok(()) +} + #[allow(clippy::too_many_arguments)] // Axum extractors are the HTTP contract. async fn create_run( State(service): State>, @@ -117,23 +175,19 @@ async fn create_run( ) .await; }; - let surface = match authorize_route_with_reason(&service, &binding.base, &claims, &options) { + let surface = match admit_ingestion( + &service, + mutations, + &binding.base, + &claims, + &options, + &headers, + &correlation, + ) + .await + { Ok(surface) => surface, - Err(RouteAdmissionError::Ambiguous(profiles)) => { - return crate::correlation::ambiguous_access_profile_response(profiles); - } - Err(RouteAdmissionError::Refused(refusal)) => { - return audited_mutation_admission_refusal( - mutations, - &binding.base, - &options, - &claims, - None, - &correlation, - refusal.check, - ) - .await; - } + Err(response) => return response, }; if headers.contains_key("idempotency-key") { return audited_mutation_refusal( @@ -208,6 +262,7 @@ async fn list_runs( Extension(correlation): Extension, Authenticated(claims): Authenticated, RawQuery(raw_query): RawQuery, + headers: HeaderMap, ) -> Response { let Some(mutations) = &service.mutations else { return concealed(FailedCheck::Visibility); @@ -227,29 +282,25 @@ async fn list_runs( .await; } }; - let surface = match authorize_route_with_reason(&service, &binding.base, &claims, &admission) { + let surface = match admit_ingestion( + &service, + mutations, + &binding.base, + &claims, + &admission, + &headers, + &correlation, + ) + .await + { Ok(surface) => surface, - Err(RouteAdmissionError::Ambiguous(profiles)) => { - return crate::correlation::ambiguous_access_profile_response(profiles); - } - Err(RouteAdmissionError::Refused(refusal)) => { - return audited_mutation_admission_refusal( - mutations, - &binding.base, - &admission, - &claims, - None, - &correlation, - refusal.check, - ) - .await; - } + Err(response) => return response, }; let query = match parse_list_query(raw_query.as_deref()) { 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.", ); } @@ -281,6 +332,7 @@ async fn read_run( Authenticated(claims): Authenticated, RawQuery(raw_query): RawQuery, Path(path): Path>, + headers: HeaderMap, ) -> Response { let Some(mutations) = &service.mutations else { return concealed(FailedCheck::Visibility); @@ -297,23 +349,19 @@ async fn read_run( ) .await; }; - let surface = match authorize_route_with_reason(&service, &binding.base, &claims, &options) { + let surface = match admit_ingestion( + &service, + mutations, + &binding.base, + &claims, + &options, + &headers, + &correlation, + ) + .await + { Ok(surface) => surface, - Err(RouteAdmissionError::Ambiguous(profiles)) => { - return crate::correlation::ambiguous_access_profile_response(profiles); - } - Err(RouteAdmissionError::Refused(refusal)) => { - return audited_mutation_admission_refusal( - mutations, - &binding.base, - &options, - &claims, - None, - &correlation, - refusal.check, - ) - .await; - } + Err(response) => return response, }; let Some(run_id) = path_run_id(&path) else { return audited_mutation_refusal( @@ -361,23 +409,19 @@ async fn cancel_run( ) .await; }; - let surface = match authorize_route_with_reason(&service, &binding.base, &claims, &options) { + let surface = match admit_ingestion( + &service, + mutations, + &binding.base, + &claims, + &options, + &headers, + &correlation, + ) + .await + { Ok(surface) => surface, - Err(RouteAdmissionError::Ambiguous(profiles)) => { - return crate::correlation::ambiguous_access_profile_response(profiles); - } - Err(RouteAdmissionError::Refused(refusal)) => { - return audited_mutation_admission_refusal( - mutations, - &binding.base, - &options, - &claims, - None, - &correlation, - refusal.check, - ) - .await; - } + Err(response) => return response, }; if headers.contains_key("idempotency-key") { return audited_mutation_refusal( @@ -477,23 +521,19 @@ async fn submit_chunk( ) .await; }; - let surface = match authorize_route_with_reason(&service, &binding.base, &claims, &options) { + let surface = match admit_ingestion( + &service, + mutations, + &binding.base, + &claims, + &options, + &headers, + &correlation, + ) + .await + { Ok(surface) => surface, - Err(RouteAdmissionError::Ambiguous(profiles)) => { - return crate::correlation::ambiguous_access_profile_response(profiles); - } - Err(RouteAdmissionError::Refused(refusal)) => { - return audited_mutation_admission_refusal( - mutations, - &binding.base, - &options, - &claims, - None, - &correlation, - refusal.check, - ) - .await; - } + Err(response) => return response, }; // The chunk items are the batch items of the compiled route, so the // entity must carry a batch surface at all. @@ -617,6 +657,7 @@ async fn chunk_receipt( Authenticated(claims): Authenticated, RawQuery(raw_query): RawQuery, Path(path): Path>, + headers: HeaderMap, ) -> Response { let Some(mutations) = &service.mutations else { return concealed(FailedCheck::Visibility); @@ -633,23 +674,19 @@ async fn chunk_receipt( ) .await; }; - let surface = match authorize_route_with_reason(&service, &binding.base, &claims, &options) { + let surface = match admit_ingestion( + &service, + mutations, + &binding.base, + &claims, + &options, + &headers, + &correlation, + ) + .await + { Ok(surface) => surface, - Err(RouteAdmissionError::Ambiguous(profiles)) => { - return crate::correlation::ambiguous_access_profile_response(profiles); - } - Err(RouteAdmissionError::Refused(refusal)) => { - return audited_mutation_admission_refusal( - mutations, - &binding.base, - &options, - &claims, - None, - &correlation, - refusal.check, - ) - .await; - } + Err(response) => return response, }; let Some(run_id) = path_run_id(&path) else { return audited_mutation_refusal( @@ -976,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, @@ -1005,6 +1041,9 @@ fn parse_list_query(raw: Option<&str>) -> Result { @@ -1029,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() @@ -1112,14 +1150,10 @@ pub(super) fn import_surfaces<'a>( /// caller that holds the batch or import operation under the selected profile /// and answers with a principal, and they never appear in `/v1/registry`. pub(super) fn append_openapi( - service: &HttpService, surfaces: &[AuthorizedSurface<'_>], paths: &mut Map, schemas: &mut Map, ) { - if service.mutations.is_none() { - return; - } let mut advertised = false; for surface in surfaces.iter().filter(|surface| { matches!( @@ -1132,6 +1166,17 @@ pub(super) fn append_openapi( continue; }; let profile = &surface.entity.access_profiles[surface.context.selected_profile()]; + let through_batch = surface.route.operation == Operation::Batch; + let requires_reason = through_batch && profile.require_access_reason; + let parameters = |mut parameters: Vec, supplies_target_reason| { + if through_batch && (requires_reason || supplies_target_reason) { + parameters.push(access_reason_parameter(requires_reason)); + } + parameters + }; + let responses = |status, schema, operation: IngestionApiOperation| { + ingestion_responses(status, schema, operation.problem_codes(), requires_reason) + }; let input_schema_id = crate::artifacts::openapi_input_schema_id(&surface.entity.id, surface.route.operation); // The batch input schema is collected from the visible routes; an @@ -1166,15 +1211,15 @@ pub(super) fn append_openapi( "x-registry-operation": "ingestionCreateRun", "security": [{"bearerAuth": []}], "x-registry-accessProfile": surface.context.selected_profile(), - "parameters": [access_profile_parameter()], + "parameters": parameters(vec![access_profile_parameter()], false), "requestBody": { "required": true, "content": {"application/json": {"schema": create_run_schema()}} }, - "responses": ingestion_responses( + "responses": responses( "201", create_run_answer(), - IngestionApiOperation::CreateRun.problem_codes(), + IngestionApiOperation::CreateRun, ), }), ); @@ -1186,9 +1231,9 @@ pub(super) fn append_openapi( "x-registry-operation": "ingestionListRuns", "security": [{"bearerAuth": []}], "x-registry-accessProfile": surface.context.selected_profile(), - "parameters": [ + "parameters": parameters(vec![ access_profile_parameter(), - { + json!({ "name": "limit", "in": "query", "required": false, @@ -1199,15 +1244,15 @@ pub(super) fn append_openapi( "maximum": crate::ingestion_store::MAX_RUN_PAGE_SIZE, "default": crate::ingestion_store::DEFAULT_RUN_PAGE_SIZE } - }, - { + }), + json!({ "name": "cursor", "in": "query", "required": false, "description": "The keyset cursor: only runs ordered before this run id.", "schema": {"type": "string", "format": "uuid"} - }, - { + }), + json!({ "name": "status", "in": "query", "required": false, @@ -1216,19 +1261,19 @@ pub(super) fn append_openapi( "type": "string", "enum": ["open", "complete", "cancelled", "blocked"] } - }, - { + }), + json!({ "name": "inputDigest", "in": "query", "required": false, "description": "Only runs announced with this input digest.", "schema": {"type": "string", "pattern": "^[0-9a-f]{64}$"} - } - ], - "responses": ingestion_responses( + }) + ], false), + "responses": responses( "200", list_runs_answer(), - IngestionApiOperation::ListRuns.problem_codes(), + IngestionApiOperation::ListRuns, ), }), ); @@ -1245,11 +1290,11 @@ pub(super) fn append_openapi( "x-registry-operation": "ingestionReadRun", "security": [{"bearerAuth": []}], "x-registry-accessProfile": surface.context.selected_profile(), - "parameters": [access_profile_parameter(), run_id_parameter()], - "responses": ingestion_responses( + "parameters": parameters(vec![access_profile_parameter(), run_id_parameter()], false), + "responses": responses( "200", run_answer(), - IngestionApiOperation::ReadRun.problem_codes(), + IngestionApiOperation::ReadRun, ), }), ); @@ -1268,7 +1313,7 @@ pub(super) fn append_openapi( "x-registry-accessProfile": surface.context.selected_profile(), "x-registry-maximumItems": batch.maximum_items, "x-registry-maximumBytes": batch.maximum_bytes, - "parameters": [access_profile_parameter(), run_id_parameter()], + "parameters": parameters(vec![access_profile_parameter(), run_id_parameter()], true), "requestBody": { "required": true, "content": { @@ -1277,12 +1322,18 @@ 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 + }), ) } } }, - "responses": ingestion_responses( + "responses": responses( "200", json!({ "type": "object", @@ -1295,7 +1346,7 @@ pub(super) fn append_openapi( } } }), - IngestionApiOperation::SubmitChunk.problem_codes(), + IngestionApiOperation::SubmitChunk, ), }), ); @@ -1312,11 +1363,11 @@ pub(super) fn append_openapi( "x-registry-operation": "ingestionCancelRun", "security": [{"bearerAuth": []}], "x-registry-accessProfile": surface.context.selected_profile(), - "parameters": [access_profile_parameter(), run_id_parameter()], - "responses": ingestion_responses( + "parameters": parameters(vec![access_profile_parameter(), run_id_parameter()], false), + "responses": responses( "200", run_answer(), - IngestionApiOperation::CancelRun.problem_codes(), + IngestionApiOperation::CancelRun, ), }), ); @@ -1333,20 +1384,20 @@ pub(super) fn append_openapi( "x-registry-operation": "ingestionChunkReceipt", "security": [{"bearerAuth": []}], "x-registry-accessProfile": surface.context.selected_profile(), - "parameters": [ + "parameters": parameters(vec![ access_profile_parameter(), run_id_parameter(), - { + json!({ "name": "chunk_index", "in": "path", "required": true, "schema": {"type": "integer", "minimum": 0} - } - ], - "responses": ingestion_responses( + }) + ], false), + "responses": responses( "200", json!({"$ref": "#/components/schemas/IngestionChunkReceipt"}), - IngestionApiOperation::ChunkReceipt.problem_codes(), + IngestionApiOperation::ChunkReceipt, ), }), ); @@ -1361,6 +1412,16 @@ pub(super) fn append_openapi( } } +fn access_reason_parameter(required: bool) -> Value { + json!({ + "name": "Registry-Access-Reason", + "in": "header", + "required": required, + "description": "The access reason as unpadded base64url UTF-8. A Batch chunk also needs it to name a reference whose target grant requires a reason.", + "schema": {"type": "string", "minLength": 1, "maxLength": 684, "pattern": "^[A-Za-z0-9_-]+$"} + }) +} + fn access_profile_parameter() -> Value { json!({ "name": "accessProfile", @@ -1419,7 +1480,8 @@ fn list_runs_answer() -> Value { fn ingestion_responses( success_status: &str, success_schema: Value, - problems: &[crate::problem::ProblemCode], + problems: &[ProblemCode], + requires_reason: bool, ) -> Value { let mut responses = Map::from_iter([( success_status.to_owned(), @@ -1441,6 +1503,8 @@ fn ingestion_responses( for status in [400u16, 401, 403, 404, 409, 410, 412, 415, 503] { let codes = problems .iter() + .copied() + .chain(requires_reason.then_some(ProblemCode::RequestAccessReasonRequired)) .filter(|code| code.status() == status) .collect::>(); if codes.is_empty() { @@ -1525,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", @@ -1630,6 +1694,165 @@ fn ingestion_chunk_receipt_schema() -> Value { #[cfg(test)] mod tests { use super::*; + use crate::subject_access_log::ACCESS_REASON_HEADER; + use context::AccessBindingRefusal; + + fn operator_context(requires_reason: bool) -> AuthorizedRequestContext { + AuthorizedRequestContext::new( + Some("operator".to_owned()), + None, + "operator".to_owned(), + vec![], + ) + .with_access_reason_requirement(requires_reason) + } + + #[test] + fn batch_ingestion_requires_a_valid_reason_when_its_grant_does() { + let mut batch = operator_context(true); + let mut headers = HeaderMap::new(); + for value in [None, Some("!")] { + if let Some(value) = value { + headers.insert(ACCESS_REASON_HEADER, HeaderValue::from_static(value)); + } + assert_eq!( + validate_ingestion_access_reason(Operation::Batch, &mut batch, &headers), + Err(AccessBindingRefusal::ReasonRequired) + ); + } + + let valid = HeaderValue::from_static("cmV2aWV3"); + headers.insert(ACCESS_REASON_HEADER, valid.clone()); + headers.append(ACCESS_REASON_HEADER, valid.clone()); + assert_eq!( + validate_ingestion_access_reason(Operation::Batch, &mut batch, &headers), + Err(AccessBindingRefusal::ReasonRequired) + ); + headers.insert(ACCESS_REASON_HEADER, valid); + validate_ingestion_access_reason(Operation::Batch, &mut batch, &headers).unwrap(); + assert_eq!(batch.access_reason(), None); + } + + #[test] + fn only_batch_ingestion_can_supply_a_targets_required_reason() { + let ordinary = operator_context(false) + .with_reference_context("open", operator_context(false)) + .with_reference_context("restricted", operator_context(true)); + let mut batch = ordinary.clone(); + let targets = |context: &AuthorizedRequestContext| { + context + .reference_contexts() + .map(|(target, _)| target.clone()) + .collect::>() + }; + let mut headers = HeaderMap::new(); + validate_ingestion_access_reason(Operation::Batch, &mut batch, &headers).unwrap(); + assert_eq!(targets(&batch), ["open"]); + headers.insert(ACCESS_REASON_HEADER, HeaderValue::from_static("!")); + validate_ingestion_access_reason(Operation::Batch, &mut batch, &headers).unwrap(); + assert_eq!(targets(&batch), ["open"]); + headers.insert(ACCESS_REASON_HEADER, HeaderValue::from_static("cmV2aWV3")); + validate_ingestion_access_reason(Operation::Batch, &mut batch, &headers).unwrap(); + assert_eq!(targets(&batch), ["open", "restricted"]); + assert_eq!(batch.access_reason(), None); + + let mut import = ordinary; + validate_ingestion_access_reason(Operation::Import, &mut import, &headers).unwrap(); + assert_eq!(targets(&import), ["open"]); + assert_eq!(import.access_reason(), None); + } + + #[test] + fn ingestion_openapi_publishes_the_selected_grants_reason_precondition() { + for (bulk, operations, requires_reason) in [ + (Operation::Batch, json!(["create", "get", "batch"]), true), + (Operation::Batch, json!(["create", "get", "batch"]), false), + (Operation::Import, json!(["import"]), false), + ] { + let source = json!({ + "apiVersion":"id.registrystack.org/formats/breg/project/v1alpha1", + "kind":"BRegProject", + "project":{"id":"ingestion-contract","version":"1","defaultLanguage":"en","canonicalBaseIri":"https://authoring.example.test"}, + "datasets":{"entries":{}}, + "recordTypes":{"entry":{ + "primaryDataset":"entries","route":"entries","mutationMode":"mutable","classification":"internal", + "batch":{"maximumItems":3,"maximumBytes":4096}, + "fields":[{"id":"label","type":"string","maximumLength":64,"classification":"internal"}] + }}, + "accessProfiles":{"operator":{ + "default":true,"principalClaim":"sub","requiredScopes":["records:write"], + "requireAccessReason":requires_reason, + "permissions":{"records":[{ + "recordType":"entry","operations":operations,"writableFields":["label"], + "rowBoundaries":"unrestricted" + }]} + }} + }); + let project = + crate::contract::parse_project_json(&serde_json::to_vec(&source).unwrap()).unwrap(); + let registry = crate::compiler::compile_project( + &project, + &[], + crate::compiler::CompileProfile::Authoring, + ) + .unwrap(); + let entity = ®istry.entities()["entry"]; + let route = crate::data::ingestion_route(®istry, "entry", "operator").unwrap(); + assert_eq!(route.operation, bulk); + let surface = AuthorizedSurface { + route, + entity, + response_entity: entity, + context: operator_context(requires_reason), + readable_fields: BTreeSet::new(), + read_path: None, + admitted_profiles: vec!["operator".to_owned()], + }; + let mut paths = Map::new(); + append_openapi(&[surface], &mut paths, &mut Map::new()); + let entries: Vec<_> = paths + .values() + .flat_map(|methods| methods.as_object().unwrap().values()) + .collect(); + assert_eq!(entries.len(), IngestionApiOperation::ALL.len()); + for entry in entries { + let is_chunk = entry["x-registry-operation"] == "ingestionSubmitChunk"; + let header = entry["parameters"] + .as_array() + .unwrap() + .iter() + .find(|parameter| parameter["name"] == "Registry-Access-Reason"); + assert_eq!( + header.map(|header| ( + header["in"].as_str().unwrap(), + header["required"].as_bool().unwrap() + )), + (bulk == Operation::Batch && (requires_reason || is_chunk)) + .then_some(("header", requires_reason)) + ); + let problem = &entry["responses"]["400"]["content"]["application/problem+json"] + ["examples"]["request.access-reason-required"]["value"]; + assert_eq!( + problem["code"].as_str(), + requires_reason.then_some("request.access-reason-required") + ); + if requires_reason { + assert_eq!(problem["status"], 400); + assert!(problem.get("fieldPath").is_none()); + } + } + } + } + + #[tokio::test] + async fn an_ingestion_reference_precondition_keeps_its_opaque_problem() { + let response = ingestion_problem(IngestionServiceError::PreconditionFailed); + assert_eq!(response.status(), StatusCode::PRECONDITION_FAILED); + let body = to_bytes(response.into_body(), 4096).await.unwrap(); + let problem: Value = serde_json::from_slice(&body).unwrap(); + assert_eq!(problem["code"], "precondition.failed"); + assert!(problem.get("fieldPath").is_none()); + } #[test] fn ingestion_openapi_401_declares_www_authenticate_bearer() { @@ -1637,6 +1860,7 @@ mod tests { "201", json!({"description": "Created"}), &[ProblemCode::AuthenticationRefused], + false, ); let header = &responses["401"]["headers"]["WWW-Authenticate"]; assert_eq!(header, &crate::artifacts::bearer_challenge_header()); 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 3fa675c1d9..704ed7d13f 100644 --- a/crates/registry-breg/src/api/mod.rs +++ b/crates/registry-breg/src/api/mod.rs @@ -208,10 +208,22 @@ fn route_set(service: Arc) -> Router { get(proposals::review_context_batch), ) .route("/v1/proposals/{proposal_id}", get(proposals::get)) + .route( + "/v1/proposals/{proposal_id}/additional-forms/{form_id}", + post(proposals::add_form), + ) .route( "/v1/proposals/{proposal_id}/asks/{ask_id}/answer", post(proposals::answer), ) + .route( + "/v1/proposals/{proposal_id}/messages", + get(proposals::messages::list).post(proposals::messages::write), + ) + .route( + "/v1/proposals/{proposal_id}/messages/read", + post(proposals::messages::mark_read), + ) .route( "/v1/proposals/{proposal_id}/submissions/{submission_version}", get(proposals::submission), @@ -631,8 +643,10 @@ async fn openapi( if service.review_completions.is_some() { crate::artifacts::append_review_completion_openapi(&mut paths, &mut schemas); } - ingestion::append_openapi(&service, &visible, &mut paths, &mut schemas); - ingestion::append_openapi(&service, &imports, &mut paths, &mut schemas); + if service.mutations.is_some() { + ingestion::append_openapi(&visible, &mut paths, &mut schemas); + ingestion::append_openapi(&imports, &mut paths, &mut schemas); + } Json(json!({ "openapi": "3.1.0", "info": {"title": service.registry.registry_id(), "version": service.registry.version()}, @@ -777,6 +791,13 @@ async fn registry_metadata( .as_array() .cloned() .unwrap_or_default(); + // A reader sees the effects on the Record types this document shows it. + let visible_record_types = metadata["recordTypes"] + .as_array() + .into_iter() + .flatten() + .filter_map(|record_type| record_type["id"].as_str().map(str::to_owned)) + .collect::>(); // A lifecycle reader can describe the inputs it may inspect without // acquiring authority to start another Proposal. for (action_id, profile_id, operation) in &visible_proposals { @@ -799,11 +820,12 @@ async fn registry_metadata( let crate::model::CompiledActionExecution::Proposal { proposal } = &action.execution else { continue; }; - let Some(grant) = proposal - .permissions - .iter() - .find(|grant| &grant.profile_id == profile_id) - else { + let Some(grant) = proposal.permissions.iter().find(|grant| { + &grant.profile_id == profile_id + && grant + .operations + .contains(&crate::model::ProposalOperation::Get) + }) else { continue; }; let mut description = @@ -818,7 +840,19 @@ async fn registry_metadata( .expect("Action description") .remove("conditionRoute"); description["requiredConditionKeys"] = json!([]); - description["resultEffects"] = json!([]); + description["writableInputs"] = json!([]); + // The effects a Proposal applies, limited to Record types this + // document already shows the reader; no Action grant is involved. + description["resultEffects"] = json!(action + .effects + .iter() + .filter(|effect| visible_record_types.contains(&effect.target.entity_id)) + .map(|effect| json!({ + "effect": effect.id, + "recordType": effect.target.entity_id, + "operation": crate::artifacts::operation_name(effect.operation), + })) + .collect::>()); if let Some(attachments) = description["attachments"].as_array_mut() { attachments.retain(|slot| { slot["id"] @@ -840,6 +874,16 @@ async fn registry_metadata( .is_some_and(|id| grant.readable_inputs.contains(id)) }); } + // The subject input is named only to a reader that can read it. + if !description["subject"]["input"] + .as_str() + .is_some_and(|id| grant.readable_inputs.contains(id)) + { + description + .as_object_mut() + .expect("Action description") + .remove("subject"); + } action_metadata.push(description); } if !action_metadata.is_empty() { @@ -856,34 +900,62 @@ async fn registry_metadata( .filter(|(_, _, operation)| *operation == crate::model::ProposalOperation::Get) .map(|(_, profile, _)| profile) .collect::>(); - let mut inventory = BTreeMap::<(&str, &str), Vec<&str>>::new(); - for (action, profile, operation) in &visible_proposals { - inventory - .entry((action.as_str(), profile.as_str())) - .or_default() - .push(operation.as_str()); + // One entry for each visible grant: a profile with an owner and a + // subject entry for one Action has two. + let mut inventory = Vec::new(); + let mut described = BTreeSet::new(); + for (action_id, profile, _) in &visible_proposals { + if !described.insert((action_id, profile)) { + continue; + } + let Some(action) = service + .registry + .actions() + .actions + .iter() + .find(|candidate| &candidate.id == action_id) + else { + continue; + }; + let crate::model::CompiledActionExecution::Proposal { proposal } = &action.execution + else { + continue; + }; + for grant in proposal + .permissions + .iter() + .filter(|grant| &grant.profile_id == profile) + { + let operations = grant + .operations + .iter() + .filter(|operation| { + visible_proposals.contains(&( + action_id.clone(), + profile.clone(), + **operation, + )) + }) + .map(|operation| operation.as_str()) + .collect::>(); + if operations.is_empty() { + continue; + } + let mut entry = json!({ + "actionId": action_id, "accessProfile": profile, "operations": operations, + "readableInputs": if operations.contains(&"get") { grant.readable_inputs.clone() } else { BTreeSet::new() }, + "writableInputs": crate::artifacts::proposal_writable_inputs(action, grant), + "readableContextFields": if operations.contains(&"get-review-context") || operations.contains(&"get-task-grant-context") { grant.readable_context_fields.clone() } else { BTreeSet::new() }, + }); + if let Some(party) = grant.party { + entry["party"] = json!(party); + } + inventory.push(entry); + } } metadata["proposals"] = json!({"method":"GET","path":"/v1/proposals", "accessProfiles":list_profiles, "get":{"method":"GET","path":"/v1/proposals/{proposal_id}","accessProfiles":get_profiles}, - "actions":inventory.into_iter().map(|((action,profile),operations)|json!({ - "actionId":action,"accessProfile":profile,"operations":operations, - "readableInputs":if operations.contains(&"get") { service.registry.actions().actions.iter() - .find(|candidate| candidate.id == action) - .and_then(|candidate| match &candidate.execution { - crate::model::CompiledActionExecution::Proposal { proposal } => proposal.permissions.iter() - .find(|grant| grant.profile_id == profile), - _ => None, - }).map(|grant| grant.readable_inputs.clone()).expect("visible Proposal grant") - } else { BTreeSet::new() }, - "readableContextFields":if operations.contains(&"get-review-context") || operations.contains(&"get-task-grant-context") { service.registry.actions().actions.iter() - .find(|candidate| candidate.id == action) - .and_then(|candidate| match &candidate.execution { - crate::model::CompiledActionExecution::Proposal { proposal } => proposal.permissions.iter() - .find(|grant| grant.profile_id == profile), - _ => None, - }).map(|grant| grant.readable_context_fields.clone()).expect("visible Proposal task-context grant") - } else { BTreeSet::new() } - })).collect::>()}); + "actions":inventory}); } // A peer that runs in lock-step with this engine release, such as a // Casework source adapter, compares this header with its own release and @@ -937,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, @@ -1057,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(), @@ -1103,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, @@ -1226,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, @@ -1275,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, @@ -1470,6 +1618,7 @@ fn proposal_link_access( crate::model::ProposalOperation::Get, ), None, + proposals::PartySelection::Any, )?; authority .task_grant @@ -1658,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( @@ -1707,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, @@ -2109,7 +2275,7 @@ async fn create_dispatch( public_deployment_prefix(&service), service.field_encryption.as_deref(), ), - Err(error) => mutation_problem_for_fields(error, &surface.readable_fields), + Err(error) => mutation_problem_for_fields(error, &surface.readable_fields, &correlation), } } @@ -2288,7 +2454,7 @@ async fn patch_dispatch( public_deployment_prefix(&service), service.field_encryption.as_deref(), ), - Err(error) => mutation_problem_for_fields(error, &surface.readable_fields), + Err(error) => mutation_problem_for_fields(error, &surface.readable_fields, &correlation), } } @@ -2441,7 +2607,7 @@ async fn batch_dispatch( public_deployment_prefix(&service), service.field_encryption.as_deref(), ), - Err(error) => mutation_problem_for_fields(error, &surface.readable_fields), + Err(error) => mutation_problem_for_fields(error, &surface.readable_fields, &correlation), } } @@ -2592,7 +2758,7 @@ async fn tombstone_dispatch( public_deployment_prefix(&service), service.field_encryption.as_deref(), ), - Err(error) => mutation_problem_for_fields(error, &surface.readable_fields), + Err(error) => mutation_problem_for_fields(error, &surface.readable_fields, &correlation), } } @@ -2914,6 +3080,7 @@ fn visible_proposal_operations( Some(&grant.profile_id), crate::postgres::ProposalAuthorityOperation::Lifecycle(*operation), None, + proposals::PartySelection::Any, ) .is_some() { @@ -3092,6 +3259,14 @@ fn authorize_direct_route_mode<'a>( .with_audit_context(claims) .with_recipients(claims) .with_access_reason_requirement(profile.require_access_reason); + let context = if matches!( + route.operation, + Operation::Create | Operation::Patch | Operation::Batch | Operation::Import + ) { + with_reference_contexts(service, context, claims, entity) + } else { + context + }; Ok(AuthorizedSurface { route, entity, @@ -3175,6 +3350,87 @@ fn authorize_read_path_route_mode<'a>( ) } +/// A direct write names a referenced record only if the caller can read it. +/// Resolve the caller's context on each Record type this one references, as +/// that type's `get` route would, or under the profile's `reference` grant +/// there, so the write can check each record it names. A type the caller +/// cannot read gets no context, and naming one of its records is refused. +fn with_reference_contexts( + service: &HttpService, + mut context: AuthorizedRequestContext, + claims: &VerifiedRequestClaims, + entity: &crate::model::CompiledEntity, +) -> AuthorizedRequestContext { + let targets = entity + .fields + .values() + .filter_map(|field| match &field.field_type { + crate::contract::FieldTypeSource::Reference { target, .. } => Some(target.as_str()), + _ => None, + }) + .collect::>(); + for target in targets { + let reference_grant = service + .registry + .entities() + .get(target) + .and_then(|entity| entity.access_profiles.get(context.selected_profile())) + .filter(|profile| profile.operations.contains(&Operation::Reference)); + let authorized = if let Some(profile) = reference_grant { + reference_grant_context(profile, claims) + } else { + let Some(route) = service.registry.routes().routes.iter().find(|route| { + route.entity_id == target + && route.operation == Operation::Get + && route.method == crate::model::HttpMethod::Get + }) else { + continue; + }; + let mut options = QueryOptions::default(); + options.parsed.access_profile = Some(context.selected_profile().to_owned()); + authorize_direct_route_mode(service, route, claims, &options, false) + .map(|surface| surface.context) + .map_err(drop) + }; + match authorized { + Ok(reference) => context = context.with_reference_context(target, reference), + // Without a context every reference to this type answers as a + // missing record would, so say why without naming any record. + Err(_) => tracing::warn!( + reason = "reference-target-unauthorized", + record_type = target, + access_profile = context.selected_profile(), + "this profile cannot read the referenced Record type under these claims, so a direct write naming one of its records answers as if the record were missing" + ), + } + } + context +} + +/// The caller's context under a `reference` grant, admitted as an explicit +/// selection of its profile on a route would be: the token reaches the +/// profile and carries the claims its row boundaries and task grant need. +/// The grant has no route, so no route lookup or field selection applies. +fn reference_grant_context( + profile: &AccessProfileSource, + claims: &VerifiedRequestClaims, +) -> Result { + if !claims.reaches_profile(&profile.id) { + return Err(()); + } + let row_boundaries = authorize_profile_claims(profile, claims).map_err(drop)?; + Ok(AuthorizedRequestContext::new( + claims.principal().map(str::to_owned), + claims.purpose().map(str::to_owned), + profile.id.clone(), + row_boundaries, + ) + .with_task_grant(task_grant_binding(profile, claims).map_err(drop)?) + .with_audit_context(claims) + .with_recipients(claims) + .with_access_reason_requirement(profile.require_access_reason)) +} + fn access_entry_for_route<'a>( service: &'a HttpService, route: &CompiledRoute, @@ -3211,8 +3467,9 @@ fn read_path_for_route<'a>( fn served_operation(service: &HttpService, route: &CompiledRoute) -> bool { match route.operation { // The ingestion-run surface serves an import grant; the route itself - // is never mounted and never listed as an operation. - Operation::Invoke | Operation::Start | Operation::Import => false, + // is never mounted and never listed as an operation. A reference + // grant has no route. + Operation::Invoke | Operation::Start | Operation::Import | Operation::Reference => false, Operation::Get | Operation::List => true, Operation::Lookup => true, Operation::Create => service.mutations.is_some(), @@ -5103,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()); @@ -5314,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 { @@ -5376,6 +5677,7 @@ fn operation_name(operation: Operation) -> &'static str { Operation::Snapshot => "snapshot", Operation::Import => "import", Operation::Start => "start", + Operation::Reference => "reference", } } @@ -6065,6 +6367,11 @@ fn attachment_slot_problem(problem: ProblemCode, slot: &str) -> Response { ) } +fn membership_precondition_problem(correlation: &RequestCorrelation) -> Response { + crate::correlation::record_refusal_check(FailedCheck::Membership, correlation); + precondition_failed() +} + fn mutation_problem(error: MutationError) -> Response { let check = error.failed_check(); let response = mutation_problem_response(error); @@ -6082,10 +6389,14 @@ fn mutation_problem_response(error: MutationError) -> Response { MutationError::InvalidRequestAt(location) => invalid_request_at(&location), MutationError::AuthorizationRefused(_) | MutationError::PreconditionFailed + | MutationError::MembershipPreconditionFailed | MutationError::ProposalTargetChanged | MutationError::FieldGuardFailed { .. } | MutationError::ProposalGuardFailed(_) | MutationError::TimerGenerationUnsupported => precondition_failed(), + MutationError::MembershipWriteOutsideBoundary => { + refusal_problem(ProblemCode::WriteOutsideBoundary, FailedCheck::Membership) + } MutationError::WriteOutsideBoundary => { refusal_problem(ProblemCode::WriteOutsideBoundary, FailedCheck::RowBoundary) } @@ -6093,10 +6404,20 @@ fn mutation_problem_response(error: MutationError) -> Response { fixed_problem(ProblemCode::MutationConflict) } MutationError::ProposalRejected => fixed_problem(ProblemCode::ProposalRejected), + MutationError::ProposalSubjectNotCaller => refusal_problem( + ProblemCode::ProposalSubjectNotCaller, + FailedCheck::Ownership, + ), + MutationError::ProposalSubjectChanged => fixed_problem(ProblemCode::ProposalSubjectChanged), + MutationError::ProposalMessageLimitReached => { + fixed_problem(ProblemCode::ProposalMessageLimitReached) + } MutationError::AttachmentSlotWriteOnce => { fixed_problem(ProblemCode::AttachmentSlotWriteOnce) } MutationError::AttachmentTooLarge => fixed_problem(ProblemCode::AttachmentTooLarge), + MutationError::FormUndeclared => fixed_problem(ProblemCode::ProposalFormUndeclared), + MutationError::FormLimitReached => fixed_problem(ProblemCode::ProposalFormLimitReached), MutationError::AttachmentLimitReached => fixed_problem(ProblemCode::AttachmentLimitReached), MutationError::AttachmentRequired { slot } => { attachment_slot_problem(ProblemCode::AttachmentRequired, &slot) @@ -6122,6 +6443,7 @@ fn mutation_problem_response(error: MutationError) -> Response { // the match stays exhaustive over the whole closed vocabulary. MutationError::Unavailable | MutationError::RetryableConflict + | MutationError::MembershipKeyDrift | MutationError::CommitUnresolved | MutationError::MigrationLockHeld | MutationError::PostureMismatch { .. } @@ -6158,8 +6480,10 @@ fn mutation_problem_response(error: MutationError) -> Response { fn mutation_problem_for_fields( error: MutationError, readable_fields: &BTreeSet, + correlation: &RequestCorrelation, ) -> Response { match error { + MutationError::MembershipPreconditionFailed => membership_precondition_problem(correlation), MutationError::InvalidTimerWindow { at_field, not_after_field, @@ -6363,7 +6687,7 @@ mod held_body_encryption_tests { secret ] }}, - "accessProfiles":{"caseworker": {"default":true,"principalClaim":"principal","requiredScopes":"unrestricted","permissions":{"records":[{ + "accessProfiles":{"caseworker": {"default":true,"principalClaim":"principal","requiredScopes":["records:write"],"permissions":{"records":[{ "recordType":"case","rowBoundaries":"unrestricted","operations":["get","list","create","patch"], "readableFields":["label","secret"],"writableFields":["label","secret"] }]}}} @@ -6797,6 +7121,17 @@ mod refusal_check_tests { use super::*; use registry_platform_authcommon::RefusalNote; + #[tokio::test] + async fn a_direct_reference_conflict_keeps_its_opaque_problem() { + let response = mutation_problem(MutationError::Conflict); + assert_eq!(response.status(), StatusCode::CONFLICT); + assert_eq!(noted(&response), None); + let body = to_bytes(response.into_body(), 4096).await.unwrap(); + let problem: Value = serde_json::from_slice(&body).unwrap(); + assert_eq!(problem["code"], "mutation.conflict"); + assert!(problem.get("fieldPath").is_none()); + } + fn noted(response: &Response) -> Option { response .extensions() @@ -6882,6 +7217,10 @@ mod refusal_check_tests { MutationError::WriteOutsideBoundary, FailedCheck::RowBoundary, ), + ( + MutationError::MembershipWriteOutsideBoundary, + FailedCheck::Membership, + ), ( MutationError::FieldGuardFailed { input: "input".to_owned(), @@ -6894,6 +7233,7 @@ mod refusal_check_tests { } for error in [ MutationError::PreconditionFailed, + MutationError::MembershipPreconditionFailed, MutationError::Conflict, MutationError::Unavailable, ] { diff --git a/crates/registry-breg/src/api/proposals.rs b/crates/registry-breg/src/api/proposals.rs index c560c9cabc..e5fb636dd3 100644 --- a/crates/registry-breg/src/api/proposals.rs +++ b/crates/registry-breg/src/api/proposals.rs @@ -5,12 +5,16 @@ use super::*; mod answers; +pub(super) mod messages; use crate::model::{ CompiledAction, CompiledActionExecution, CompiledActionRoute, CompiledProposalPermission, - CompiledRegistry, HttpMethod, ProposalOperation, + CompiledRegistry, HttpMethod, ProposalOperation, ProposalParty, }; use crate::postgres::{ProposalAuthority, ProposalAuthorityOperation, RowBoundaryContext}; pub(super) use answers::answer; +mod forms; +pub(super) use forms::add_form; +pub(crate) use forms::FormMutation; pub(super) fn proposal_problem(error: MutationError) -> Response { match error { @@ -47,7 +51,10 @@ pub(crate) struct ProposalMutationInput<'a> { pub executor_lease: Option, pub rebase_start_authority: Option<&'a ProposalAuthority>, pub attachment: Option, + pub form: Option>, pub answer: Option, + /// The text of a message written to the Proposal's thread. + pub message: Option, pub correlation: &'a RequestCorrelation, pub human_identity: Option<&'a registry_review_client::HumanIdentity>, pub claims: Option<&'a VerifiedRequestClaims>, @@ -283,8 +290,157 @@ pub(crate) fn authorize( selected: Option<&str>, operation: ProposalAuthorityOperation, proposal_id: Option, + parties: PartySelection, ) -> Option { - authorize_checked(registry, action, claims, selected, operation, proposal_id).ok() + authorize_checked( + registry, + action, + claims, + selected, + operation, + proposal_id, + parties, + ) + .ok() +} + +/// Which of a profile's Proposal entries may admit the caller. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub(crate) enum PartySelection { + /// Any entry that holds the operation: Start, and admission to a route + /// before any Proposal is read. The transaction still checks the party. + Any, + /// The entry bound to exactly this party, or to none. + Exact(Option), + /// The entry that governs the caller on one Proposal. An entry bound to + /// no party governs alone. Otherwise the owner entry governs a caller who + /// filed the Proposal, then the subject entry a caller who is its + /// subject; the governing entry alone decides the operation and every + /// projection. A caller who is neither is admitted by any entry holding + /// the operation and then refused as concealed. + Proposal { owner: bool, subject: bool }, +} + +/// The admission's human test: a verified person acting for no one else and +/// under no task grant. Only such a caller is ever matched as a subject. +pub(crate) fn acts_for_self(claims: &VerifiedRequestClaims) -> bool { + claims.actor_kind() == Some(registry_platform_oidc::ActorKind::Human) + && claims.actor_subject().is_none() + && claims.grant().is_none() +} + +pub(crate) fn select_proposal_grant<'a>( + proposal: &'a crate::model::CompiledProposalPolicy, + profile: &str, + operation: ProposalOperation, + parties: PartySelection, +) -> Option<&'a CompiledProposalPermission> { + let entries = proposal + .permissions + .iter() + .filter(|grant| grant.profile_id == profile) + .collect::>(); + let holds = |grant: &&&CompiledProposalPermission| grant.operations.contains(&operation); + match parties { + PartySelection::Any => entries.iter().find(holds).copied(), + PartySelection::Exact(party) => entries + .iter() + .filter(|grant| grant.party == party) + .find(holds) + .copied(), + PartySelection::Proposal { owner, subject } => { + match governing_entry(&entries, owner, subject) { + Some(grant) => holds(&&grant).then_some(grant), + None => entries.iter().find(holds).copied(), + } + } + } +} + +/// The entry of one profile that governs a caller on one Proposal: the entry +/// bound to no party, else the owner entry for its owner, else the subject +/// entry for its subject. +fn governing_entry<'a>( + entries: &[&'a CompiledProposalPermission], + owner: bool, + subject: bool, +) -> Option<&'a CompiledProposalPermission> { + let party = |party| { + entries + .iter() + .find(|grant| grant.party == Some(party)) + .copied() + }; + entries + .iter() + .find(|grant| grant.party.is_none()) + .copied() + .or_else(|| owner.then(|| party(ProposalParty::Owner)).flatten()) + .or_else(|| subject.then(|| party(ProposalParty::Subject)).flatten()) +} + +/// Whether the caller is the Proposal's subject and the subject entry that +/// governs them, in a profile they reach, does not hold `operation`. The +/// subject can already read the Proposal, so the refusal need not conceal it. +/// An owner's refusals stay concealed, as every other refusal after a +/// Proposal lookup is. +fn party_entry_lacks_operation( + action: &CompiledAction, + claims: &VerifiedRequestClaims, + selected: Option<&str>, + operation: ProposalAuthorityOperation, + parties: PartySelection, +) -> bool { + let ( + CompiledActionExecution::Proposal { proposal }, + ProposalAuthorityOperation::Lifecycle(operation), + PartySelection::Proposal { owner, subject }, + ) = (&action.execution, operation, parties) + else { + return false; + }; + let profiles = proposal + .permissions + .iter() + .map(|grant| grant.profile_id.as_str()) + .filter(|profile| selected.is_none_or(|selected| selected == *profile)) + .filter(|profile| claims.reaches_profile(profile)) + .collect::>(); + profiles.into_iter().any(|profile| { + let entries = proposal + .permissions + .iter() + .filter(|grant| grant.profile_id == profile) + .collect::>(); + governing_entry(&entries, owner, subject).is_some_and(|grant| { + grant.party == Some(ProposalParty::Subject) && !grant.operations.contains(&operation) + }) + }) +} + +/// Whether the subject entry still admits the caller to read the Proposal, +/// row boundaries and the transaction check included. A subject whose +/// target has left their reach is answered as a stranger is. +async fn subject_still_reads( + service: &HttpService, + mutations: &crate::postgres::PostgresRecordMutationService, + action: &CompiledAction, + claims: &VerifiedRequestClaims, + selected: Option<&str>, + id: Uuid, +) -> bool { + let Ok(reader) = authorize_checked( + &service.registry, + action, + claims, + selected, + ProposalAuthorityOperation::Lifecycle(ProposalOperation::Get), + Some(id), + PartySelection::Exact(Some(ProposalParty::Subject)), + ) else { + return false; + }; + mutations.proposal_visible(id, &reader).await.is_ok() } #[derive(Clone, Debug, Eq, PartialEq)] @@ -303,6 +459,7 @@ pub(crate) fn authorize_checked( selected: Option<&str>, operation: ProposalAuthorityOperation, proposal_id: Option, + parties: PartySelection, ) -> Result { let CompiledActionExecution::Proposal { proposal } = &action.execution else { return Err(ProposalAdmissionError::Refused(FailedCheck::Operation)); @@ -315,6 +472,7 @@ pub(crate) fn authorize_checked( profile, operation, proposal_id, + parties, ) .map_err(ProposalAdmissionError::Refused); } @@ -367,8 +525,15 @@ pub(crate) fn authorize_checked( let mut default_refusal = None; let mut first_refusal = None; for &candidate in &candidates { - match authorize_checked_profile(registry, action, claims, candidate, operation, proposal_id) - { + match authorize_checked_profile( + registry, + action, + claims, + candidate, + operation, + proposal_id, + parties, + ) { Ok(authority) => admitted.push(authority), Err(check) => { if default_profile_id == Some(candidate) { @@ -434,6 +599,7 @@ fn authorize_checked_profile( selected: &str, operation: ProposalAuthorityOperation, proposal_id: Option, + parties: PartySelection, ) -> Result { if !claims.reaches_profile(selected) { return Err(FailedCheck::AccessProfile); @@ -461,7 +627,7 @@ fn authorize_checked_profile( { return Err(FailedCheck::TaskGrantMissing); } - let (profile, targets, task_source, profile_kind) = match operation { + let (profile, party, targets, task_source, profile_kind) = match operation { ProposalAuthorityOperation::Start => { let grant = action .permissions @@ -492,20 +658,18 @@ fn authorize_checked_profile( .ok_or(FailedCheck::RowBoundary)?; ( grant.profile_id.as_str(), + None, targets, grant.task_grant.as_ref(), grant.actor_kind, ) } ProposalAuthorityOperation::Lifecycle(operation) => { - let grant = proposal - .permissions - .iter() - .find(|grant| selected == grant.profile_id && grant.operations.contains(&operation)) + let grant = select_proposal_grant(proposal, selected, operation, parties) .ok_or(FailedCheck::AccessProfile)?; if standing_agent && operation == ProposalOperation::Edit - && grant.ownership != Some(crate::model::ProposalOwnership::Caller) + && grant.party != Some(crate::model::ProposalParty::Owner) { return Err(FailedCheck::Operation); } @@ -540,6 +704,7 @@ fn authorize_checked_profile( .ok_or(FailedCheck::RowBoundary)?; ( grant.profile_id.as_str(), + grant.party, targets, grant.task_grant.as_ref(), grant.actor_kind, @@ -552,6 +717,7 @@ fn authorize_checked_profile( operation, claims.principal().ok_or(FailedCheck::TokenClaims)?, profile, + party, claims.purpose(), targets, ) @@ -566,19 +732,23 @@ fn authorize_checked_profile( // any kind, acting for no one else and under no task grant. A delegated // actor, a standing or task-granted agent and a service never receive // them, whatever their grant says. - authority.receives_review_answers = claims.actor_kind() - == Some(registry_platform_oidc::ActorKind::Human) - && claims.actor_subject().is_none() - && claims.grant().is_none() + authority.person = acts_for_self(claims); + authority.receives_review_answers = acts_for_self(claims) && task_source.is_none() && matches!( profile_kind, None | Some(crate::contract::ActorKindSource::Human) ); + authority.receives_form_values = authority.receives_review_answers; // Answering is the applicant's own act and takes the same human test. - // The Proposal document's `asks` member follows this admission. - if operation == ProposalAuthorityOperation::Lifecycle(ProposalOperation::Answer) - && !authority.receives_review_answers + // The Proposal document's `asks` member follows this admission. The + // message thread is one person's text shown to another, both ways. + if matches!( + operation, + ProposalAuthorityOperation::Lifecycle( + ProposalOperation::Answer | ProposalOperation::Message + ) + ) && !authority.receives_review_answers { return Err(FailedCheck::ActorKind); } @@ -638,25 +808,36 @@ pub(super) fn selected_profile(raw: Option<&str>) -> Result, ()> } fn review_status_options(raw: Option<&str>) -> Result<(Option, bool), ()> { - review_include_options(raw, "progress") + review_include_options(raw, &["progress"]) + .map(|(selected, included)| (selected, !included.is_empty())) } -fn review_include_options(raw: Option<&str>, include: &str) -> Result<(Option, bool), ()> { +/// The selected profile and the optional members a review read asks for: +/// one `include` parameter for each, each one of `allowed`, none repeated. +fn review_include_options( + raw: Option<&str>, + allowed: &[&'static str], +) -> Result<(Option, BTreeSet<&'static str>), ()> { let Some(raw) = raw else { - return Ok((None, false)); + return Ok((None, BTreeSet::new())); }; if raw.is_empty() || raw.len() > MAX_RAW_QUERY_BYTES { return Err(()); } let mut ordinary = Vec::new(); - let mut included = false; + let mut included = BTreeSet::new(); for pair in raw.split('&') { let (name, value) = pair.split_once('=').ok_or(())?; if percent_decode(name).map_err(|_| ())? == "include" { - if included || percent_decode(value).map_err(|_| ())? != include { + let value = percent_decode(value).map_err(|_| ())?; + let known = allowed + .iter() + .copied() + .find(|include| *include == value) + .ok_or(())?; + if !included.insert(known) { return Err(()); } - included = true; } else { ordinary.push(pair); } @@ -706,12 +887,22 @@ pub(super) async fn admitted_http_refusal( method: HttpMethod, correlation: &RequestCorrelation, response: Response, +) -> Response { + admitted_http_refusal_with(mutations, authority, method, correlation, || response).await +} + +pub(super) async fn admitted_http_refusal_with( + mutations: &crate::postgres::PostgresRecordMutationService, + authority: &ProposalAuthority, + method: HttpMethod, + correlation: &RequestCorrelation, + response: impl FnOnce() -> Response, ) -> Response { match mutations .record_proposal_http_refusal(authority, method, correlation) .await { - Ok(()) => response, + Ok(()) => response(), Err(_) => unavailable(), } } @@ -726,6 +917,7 @@ async fn known_action_refusal( method: HttpMethod, correlation: &RequestCorrelation, check: FailedCheck, + known_party: bool, ) -> Response { let profile = selected.filter(|profile| match operation { ProposalAuthorityOperation::Start => action.permissions.iter().any(|grant| { @@ -763,8 +955,13 @@ async fn known_action_refusal( ) .await { + // A party of the Proposal already knows it exists, so its refusal + // names the profile; anyone else is answered as concealed. Ok(()) => match operation { ProposalAuthorityOperation::Start => profile_not_authorized(check), + ProposalAuthorityOperation::Lifecycle(_) if known_party => { + profile_not_authorized(check) + } ProposalAuthorityOperation::Lifecycle(_) => concealed(FailedCheck::Visibility), }, Err(_) => unavailable(), @@ -837,6 +1034,7 @@ async fn ensure_proposal_route_admitted( selected, ProposalAuthorityOperation::Lifecycle(operation), None, + PartySelection::Any, ) .and_then(|authority| { if operation == ProposalOperation::Rebase { @@ -847,6 +1045,7 @@ async fn ensure_proposal_route_admitted( selected, ProposalAuthorityOperation::Start, None, + PartySelection::Any, ) } else { Ok(authority) @@ -954,14 +1153,19 @@ pub(super) async fn authorize_target<'a>( .proposal_route_target(id) .await .map_err(proposal_target_problem)?; - let Some((action, owner)) = target.and_then(|(action_id, owner)| { + let Some((action, owner, subject)) = target.and_then(|(action_id, owner, subject)| { service .registry .actions() .actions .iter() .find(|action| action.id == action_id) - .map(|action| (action, owner)) + // A Proposal whose Action declares no thread has no thread routes. + .filter(|action| { + operation != ProposalOperation::Message + || crate::mutation::thread_of(action).is_some() + }) + .map(|action| (action, owner, subject)) }) else { return Err(audited_proposal_route_refusal( service, @@ -976,6 +1180,7 @@ pub(super) async fn authorize_target<'a>( .await); }; let operation = ProposalAuthorityOperation::Lifecycle(operation); + let parties = mutations.party_selection(claims, &owner, subject.as_deref()); let authority = match authorize_checked( &service.registry, action, @@ -983,6 +1188,7 @@ pub(super) async fn authorize_target<'a>( selected, operation, Some(id), + parties, ) { Ok(authority) => authority, Err(error) => { @@ -999,6 +1205,8 @@ pub(super) async fn authorize_target<'a>( method, correlation, check, + party_entry_lacks_operation(action, claims, selected, operation, parties) + && subject_still_reads(service, mutations, action, claims, selected, id).await, ) .await); } @@ -1006,7 +1214,7 @@ pub(super) async fn authorize_target<'a>( // The task-context service is admitted by the exact accepted review // binding, independently of any caller-owned Get in the same grant. if operation != ProposalAuthorityOperation::Lifecycle(ProposalOperation::GetTaskGrantContext) - && !mutations.proposal_owner_matches(&authority, &owner) + && !mutations.proposal_party_matches(&authority, &owner, subject.as_deref()) { return Err(admitted_http_refusal( mutations, @@ -1055,6 +1263,7 @@ pub(super) async fn start( selected.as_deref(), ProposalAuthorityOperation::Start, None, + PartySelection::Any, ) { Ok(authority) => authority, Err(ProposalAdmissionError::Ambiguous(profiles)) => { @@ -1070,6 +1279,7 @@ pub(super) async fn start( HttpMethod::Post, &correlation, check, + false, ) .await; } @@ -1161,7 +1371,9 @@ pub(super) async fn start( executor_lease: None, rebase_start_authority: None, attachment: None, + form: None, answer: None, + message: None, correlation: &correlation, human_identity: claims.human_identity(), claims: Some(&claims), @@ -1174,6 +1386,9 @@ pub(super) async fn start( "", service.field_encryption.as_deref(), ), + Err(MutationError::MembershipPreconditionFailed) => { + membership_precondition_problem(&correlation) + } Err(error) => proposal_problem(error), } } @@ -1214,6 +1429,7 @@ pub(super) async fn get( .await { Ok((value, etag)) => json_response(value, Some(&etag)), + Err(MutationError::MembershipPreconditionFailed) => concealed(FailedCheck::Membership), Err(MutationError::PreconditionFailed) => concealed(FailedCheck::Visibility), Err(error) => proposal_target_problem(error), } @@ -1266,6 +1482,7 @@ pub(super) async fn submission( { Ok(Some(value)) => json_response(value, None), Ok(None) => fixed_problem(ProblemCode::ProposalSubmissionExpired), + Err(MutationError::MembershipPreconditionFailed) => concealed(FailedCheck::Membership), Err(MutationError::PreconditionFailed) => concealed(FailedCheck::Visibility), Err(error) => proposal_target_problem(error), } @@ -1323,6 +1540,7 @@ pub(super) async fn transition( selected.as_deref(), ProposalAuthorityOperation::Start, None, + PartySelection::Any, ) { Ok(authority) => Some(authority), Err(_) => { @@ -1497,7 +1715,9 @@ pub(super) async fn transition( executor_lease: None, rebase_start_authority: rebase_start_authority.as_ref(), attachment: None, + form: None, answer: None, + message: None, correlation: &correlation, human_identity: claims.human_identity(), claims: Some(&claims), @@ -1521,6 +1741,9 @@ pub(super) async fn transition( ) .await } + Err(MutationError::MembershipPreconditionFailed) => { + membership_precondition_problem(&correlation) + } Err(error) => proposal_target_problem(error), } } @@ -1562,6 +1785,7 @@ async fn guard_failure_response( &failure.record_id.to_string(), &BTreeSet::from([guard.field.clone()]), boundaries, + authority.target_membership(&guard.entity_id), correlation, ) .await; @@ -1655,6 +1879,7 @@ pub(super) async fn review_context_batch( profile.clone(), ProposalOperation::GetReviewContext, ReviewAnswers::Omitted, + ReviewMessages::Counts, correlation.clone(), ) .await; @@ -1699,6 +1924,7 @@ pub(super) async fn review_context( raw, ProposalOperation::GetReviewContext, ReviewAnswers::Served, + ReviewMessages::OnRequest, correlation, ) .await @@ -1718,6 +1944,7 @@ pub(super) async fn review_status( raw, ProposalOperation::GetReviewStatus, ReviewAnswers::Omitted, + ReviewMessages::Omitted, correlation, ) .await @@ -1816,6 +2043,7 @@ pub(super) async fn task_grant_context( }; let granted = proposal.permissions.iter().find(|permission| { permission.profile_id == authority.common.access_profile() + && permission.party == authority.party && permission.operations.contains(&operation) }); if !granted.is_some_and(|permission| { @@ -1868,6 +2096,7 @@ pub(super) async fn task_grant_context( ); response } + Err(MutationError::MembershipPreconditionFailed) => concealed(FailedCheck::Membership), Err(MutationError::PreconditionFailed) => concealed(FailedCheck::Visibility), Err(error) => proposal_target_problem(error), } @@ -1882,6 +2111,16 @@ enum ReviewAnswers { Omitted, } +/// What a review read serves of the message thread, to a caller whose +/// profile holds `message`. The inbox batch serves counts and never text. +#[derive(Clone, Copy, Eq, PartialEq)] +pub(super) enum ReviewMessages { + /// The text and links, when the read asks with `include=messages`. + OnRequest, + Counts, + Omitted, +} + #[allow(clippy::too_many_arguments)] async fn review_read( service: Arc, @@ -1890,6 +2129,7 @@ async fn review_read( raw: Option, operation: ProposalOperation, answers: ReviewAnswers, + messages: ReviewMessages, correlation: RequestCorrelation, ) -> Response { let Some(mutations) = &service.mutations else { @@ -1898,12 +2138,21 @@ async fn review_read( let Ok(id) = Uuid::parse_str(&id) else { return concealed(FailedCheck::Visibility); }; - let Ok((selected, included)) = (if operation == ProposalOperation::GetReviewStatus { + let Ok((selected, included, thread)) = (if operation == ProposalOperation::GetReviewStatus { review_status_options(raw.as_deref()) + .map(|(selected, included)| (selected, included, false)) } else if operation == ProposalOperation::GetReviewContext { - review_include_options(raw.as_deref(), "answers") + review_include_options(raw.as_deref(), &["answers", "messages"]).map( + |(selected, included)| { + ( + selected, + included.contains("answers"), + included.contains("messages"), + ) + }, + ) } else { - selected_profile(raw.as_deref()).map(|selected| (selected, false)) + selected_profile(raw.as_deref()).map(|selected| (selected, false, false)) }) else { return concealed(FailedCheck::Visibility); }; @@ -1922,6 +2171,23 @@ async fn review_read( Ok(admitted) => admitted, Err(response) => return response, }; + let thread_text = match messages { + ReviewMessages::OnRequest if thread => Some(true), + ReviewMessages::Counts => Some(false), + _ => None, + }; + if let Some(text) = thread_text { + authority.review_messages = authorize( + &service.registry, + action, + &claims, + Some(authority.common.access_profile()), + ProposalAuthorityOperation::Lifecycle(ProposalOperation::Message), + Some(id), + PartySelection::Exact(authority.party), + ) + .map(|thread| (Box::new(thread), text)); + } if answers == ReviewAnswers::Omitted || !included { authority.receives_review_answers = false; } @@ -1949,6 +2215,7 @@ async fn review_read( .await { Ok((value, etag)) => json_response(value, etag.as_deref()), + Err(MutationError::MembershipPreconditionFailed) => concealed(FailedCheck::Membership), Err(MutationError::PreconditionFailed) => concealed(FailedCheck::Visibility), Err(error) => proposal_target_problem(error), } @@ -1982,6 +2249,7 @@ pub(crate) fn review_record_authorities( use crate::contract::ProposalContextValueSource; let target = match source { ProposalContextValueSource::Input { .. } + | ProposalContextValueSource::AdditionalForm { .. } | ProposalContextValueSource::Additions { .. } | ProposalContextValueSource::Document { .. } => continue, ProposalContextValueSource::Record { input, .. } => { @@ -2050,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( @@ -2077,8 +2345,30 @@ pub(super) async fn list( selected.as_deref(), ProposalAuthorityOperation::Lifecycle(ProposalOperation::List), None, + PartySelection::Any, ) { - Ok(authority) => authorities.push(authority), + Ok(authority) => { + // A profile's other party entry lists the Proposals it + // governs, under its own projection. + if let Some(party) = authority.party { + let other = match party { + ProposalParty::Owner => ProposalParty::Subject, + ProposalParty::Subject => ProposalParty::Owner, + }; + if let Ok(sibling) = authorize_checked( + &service.registry, + action, + &claims, + Some(authority.common.access_profile()), + ProposalAuthorityOperation::Lifecycle(ProposalOperation::List), + None, + PartySelection::Exact(Some(other)), + ) { + authorities.push(sibling); + } + } + authorities.push(authority); + } Err(ProposalAdmissionError::Ambiguous(ids)) => { ambiguous_profiles.extend(ids); } @@ -2110,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.", ); } @@ -2126,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(()); @@ -2164,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, } } @@ -2186,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)); } @@ -2236,3 +2527,46 @@ fn parse_proposal_list_query(raw: Option<&str>) -> Result VerifiedRequestClaims { + VerifiedRequestClaims::authenticated_with_actor_kind( + "sub", + "subject-canary", + BTreeSet::new(), + None, + BTreeMap::new(), + registry_platform_oidc::ActorKind::Human, + ) + .unwrap() + } + + #[test] + fn only_a_person_acting_for_themselves_passes_the_human_test() { + assert!(acts_for_self(&person())); + // A delegated token carries the subject's principal for someone + // else: an agent or application acting in their name. + let delegated = person() + .with_contextual_authority( + Some(registry_platform_oidc::ActorKind::Human), + None, + Some("delegated-actor".to_owned()), + None, + BTreeMap::new(), + ) + .unwrap(); + assert!(!acts_for_self(&delegated)); + for kind in [ + registry_platform_oidc::ActorKind::Agent, + registry_platform_oidc::ActorKind::Service, + ] { + let claims = person() + .with_contextual_authority(Some(kind), None, None, None, BTreeMap::new()) + .unwrap(); + assert!(!acts_for_self(&claims), "{kind:?}"); + } + } +} diff --git a/crates/registry-breg/src/api/proposals/answers.rs b/crates/registry-breg/src/api/proposals/answers.rs index dbe61b6ddc..80317f10c1 100644 --- a/crates/registry-breg/src/api/proposals/answers.rs +++ b/crates/registry-breg/src/api/proposals/answers.rs @@ -41,19 +41,8 @@ pub(in crate::api) async fn answer( Err(response) => return response, }; if let Err(error) = mutations.proposal_visible(id, &authority).await { - return match error { - MutationError::PreconditionFailed | MutationError::AuthorizationRefused(_) => { - admitted_http_refusal( - mutations, - &authority, - HttpMethod::Post, - &correlation, - concealed(FailedCheck::Visibility), - ) - .await - } - error => proposal_problem(error), - }; + return visibility_refusal(mutations, &authority, HttpMethod::Post, &correlation, error) + .await; } let refusal = async { if !single_content_type(&headers, "application/json") { @@ -69,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; @@ -106,7 +104,9 @@ pub(in crate::api) async fn answer( executor_lease: None, rebase_start_authority: None, attachment: None, + form: None, answer: Some(AnswerMutation { ask_id, body }), + message: None, correlation: &correlation, human_identity: claims.human_identity(), claims: Some(&claims), @@ -119,6 +119,31 @@ pub(in crate::api) async fn answer( "", service.field_encryption.as_deref(), ), + Err(MutationError::MembershipPreconditionFailed) => concealed(FailedCheck::Membership), Err(error) => proposal_target_problem(error), } } + +/// The answer to a caller the Proposal is hidden from after admission: the +/// same concealed `404` as for an unknown Proposal, audited as a refusal. +pub(super) async fn visibility_refusal( + mutations: &crate::postgres::PostgresRecordMutationService, + authority: &ProposalAuthority, + method: HttpMethod, + correlation: &RequestCorrelation, + error: MutationError, +) -> Response { + match error { + MutationError::PreconditionFailed + | MutationError::AuthorizationRefused(_) + | MutationError::MembershipPreconditionFailed => { + let check = if matches!(error, MutationError::MembershipPreconditionFailed) { + FailedCheck::Membership + } else { + FailedCheck::Visibility + }; + admitted_http_refusal(mutations, authority, method, correlation, concealed(check)).await + } + error => proposal_problem(error), + } +} diff --git a/crates/registry-breg/src/api/proposals/forms.rs b/crates/registry-breg/src/api/proposals/forms.rs new file mode 100644 index 0000000000..7c0627340f --- /dev/null +++ b/crates/registry-breg/src/api/proposals/forms.rs @@ -0,0 +1,143 @@ +// SPDX-License-Identifier: Apache-2.0 +use super::*; + +pub(crate) struct FormMutation<'a> { + pub id: &'a str, + pub values: Map, +} + +#[derive(serde::Deserialize)] +#[serde(deny_unknown_fields)] +struct AddFormBody { + input: Map, +} + +pub(in crate::api) async fn add_form( + State(service): State>, + Path((id, form_id)): Path<(String, String)>, + Extension(correlation): Extension, + Authenticated(claims): Authenticated, + RawQuery(raw_query): RawQuery, + headers: HeaderMap, + body: Body, +) -> Response { + let Some(mutations) = &service.mutations else { + return concealed(FailedCheck::Visibility); + }; + let id = match Uuid::parse_str(&id) { + Ok(id) if !id.is_nil() => id, + _ => return concealed(FailedCheck::Visibility), + }; + let Ok(selected) = selected_profile(raw_query.as_deref()) else { + return concealed(FailedCheck::Visibility); + }; + let (action, authority) = match authorize_target( + &service, + mutations, + id, + &claims, + selected.as_deref(), + ProposalOperation::Add, + HttpMethod::Post, + &correlation, + ) + .await + { + Ok(admitted) => admitted, + Err(response) => return response, + }; + if let Err(error) = mutations.proposal_visible(id, &authority).await { + return answers::visibility_refusal( + mutations, + &authority, + HttpMethod::Post, + &correlation, + error, + ) + .await; + } + let request = async { + let CompiledActionExecution::Proposal { proposal } = &action.execution else { + return Err(concealed(FailedCheck::Visibility)); + }; + if !proposal.additional_forms.contains_key(&form_id) { + return Err(proposal_problem(MutationError::FormUndeclared)); + } + if !authority + .permission(proposal) + .is_some_and(|grant| grant.writable_forms.contains(&form_id)) + { + return Err(profile_not_authorized(FailedCheck::AccessProfile)); + } + if !single_content_type(&headers, "application/json") { + return Err(unsupported_media_type()); + } + let key = single_header(&headers, "idempotency-key") + .filter(|key| valid_idempotency_key(key)) + .ok_or_else(missing_idempotency_key)?; + let etag = single_header(&headers, "if-match") + .filter(|etag| valid_if_match(etag)) + .ok_or_else(precondition_required)?; + let bytes = bounded_body_to(body, 16_384) + .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)) + } + .await; + let (key, etag, values) = match request { + Ok(values) => values, + Err(response) => { + return admitted_http_refusal( + mutations, + &authority, + HttpMethod::Post, + &correlation, + response, + ) + .await + } + }; + match mutations + .proposal_mutation(ProposalMutationInput { + action_id: &action.id, + proposal_id: Some(id), + operation: ProposalAuthorityOperation::Lifecycle(ProposalOperation::Add), + authority: &authority, + idempotency_key: key, + expected_etag: Some(etag), + input: None, + submission_version: None, + effect_digest: None, + reason: None, + executor_lease: None, + rebase_start_authority: None, + attachment: None, + form: Some(FormMutation { + id: &form_id, + values, + }), + answer: None, + message: None, + correlation: &correlation, + human_identity: claims.human_identity(), + claims: Some(&claims), + }) + .await + { + Ok(outcome) => exact_mutation( + outcome.response(), + None, + "", + service.field_encryption.as_deref(), + ), + Err(MutationError::MembershipPreconditionFailed) => concealed(FailedCheck::Membership), + Err(error) => proposal_target_problem(error), + } +} diff --git a/crates/registry-breg/src/api/proposals/messages.rs b/crates/registry-breg/src/api/proposals/messages.rs new file mode 100644 index 0000000000..0fb53208fe --- /dev/null +++ b/crates/registry-breg/src/api/proposals/messages.rs @@ -0,0 +1,412 @@ +// SPDX-License-Identifier: Apache-2.0 +//! The Proposal message thread: write, page and mark read. A write takes the +//! same admission, ETag and receipt boundary as every Proposal command; the +//! side it is written from follows the admitting entry, never the caller. +use super::*; + +/// Admit the caller to the thread of Proposal `id`, and confirm the +/// Proposal is visible to them before any part of the request is read. +async fn admit( + service: &HttpService, + id: &str, + claims: &VerifiedRequestClaims, + selected: Result, ()>, + method: HttpMethod, + correlation: &RequestCorrelation, +) -> Result<(Uuid, CompiledAction, ProposalAuthority), Response> { + let Some(mutations) = &service.mutations else { + return Err(concealed(FailedCheck::Visibility)); + }; + let id = match Uuid::parse_str(id) { + Ok(id) if !id.is_nil() => id, + _ => return Err(concealed(FailedCheck::Visibility)), + }; + let selected = selected.map_err(|_| concealed(FailedCheck::Visibility))?; + let (action, authority) = authorize_target( + service, + mutations, + id, + claims, + selected.as_deref(), + ProposalOperation::Message, + method, + correlation, + ) + .await?; + // A caller the Proposal's row boundaries or memberships hide learns + // nothing from how the request is shaped: visibility comes first. + if let Err(error) = mutations.proposal_visible(id, &authority).await { + return Err( + answers::visibility_refusal(mutations, &authority, method, correlation, error).await, + ); + } + Ok((id, action.clone(), authority)) +} + +/// The answer to a thread command: the caller's Proposal document when their +/// profile holds `get`, otherwise the review context with the thread when it +/// holds `get-review-context`. +async fn caller_view( + service: Arc, + action: &CompiledAction, + id: Uuid, + claims: &VerifiedRequestClaims, + authority: &ProposalAuthority, + correlation: &RequestCorrelation, +) -> Response { + let Some(mutations) = &service.mutations else { + return concealed(FailedCheck::Visibility); + }; + let profile = authority.common.access_profile().to_owned(); + let holds = |operation| { + authorize( + &service.registry, + action, + claims, + Some(&profile), + ProposalAuthorityOperation::Lifecycle(operation), + Some(id), + PartySelection::Exact(authority.party), + ) + }; + if let Some(get) = holds(ProposalOperation::Get) { + return match mutations + .proposal_document(id, &get, claims, correlation) + .await + { + Ok((value, etag)) => json_response(value, Some(&etag)), + Err(MutationError::MembershipPreconditionFailed) => concealed(FailedCheck::Membership), + Err(MutationError::PreconditionFailed) => concealed(FailedCheck::Visibility), + Err(error) => proposal_target_problem(error), + }; + } + if holds(ProposalOperation::GetReviewContext).is_some() { + return review_read( + service.clone(), + id.to_string(), + claims.clone(), + Some(format!("accessProfile={profile}&include=messages")), + ProposalOperation::GetReviewContext, + ReviewAnswers::Omitted, + ReviewMessages::OnRequest, + correlation.clone(), + ) + .await; + } + StatusCode::NO_CONTENT.into_response() +} + +pub(in crate::api) async fn write( + State(service): State>, + Path(id): Path, + Extension(correlation): Extension, + Authenticated(claims): Authenticated, + RawQuery(raw_query): RawQuery, + headers: HeaderMap, + body: Body, +) -> Response { + let (id, action, authority) = match admit( + &service, + &id, + &claims, + selected_profile(raw_query.as_deref()), + HttpMethod::Post, + &correlation, + ) + .await + { + Ok(admitted) => admitted, + Err(response) => return response, + }; + let Some(mutations) = &service.mutations else { + return concealed(FailedCheck::Visibility); + }; + let refusal = async { + if !single_content_type(&headers, "application/json") { + return Err(unsupported_media_type()); + } + let key = single_header(&headers, "idempotency-key") + .filter(|key| valid_idempotency_key(key)) + .ok_or_else(missing_idempotency_key)?; + let etag = single_header(&headers, "if-match") + .filter(|etag| valid_if_match(etag)) + .ok_or_else(precondition_required)?; + let bytes = bounded_body_to(body, 16_384) + .await + .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"), + _ => return Err(invalid_request()), + }; + let text = text + .and_then(Value::as_str) + .filter(|text| crate::proposal_messages::valid_text(text)) + .ok_or_else(|| { + invalid_request_at( + &crate::problem_location::RequestLocation::proposal_message_text(), + ) + })?; + Ok((key, etag, text.to_owned())) + } + .await; + let (key, etag, text) = match refusal { + Ok(values) => values, + Err(response) => { + return admitted_http_refusal( + mutations, + &authority, + HttpMethod::Post, + &correlation, + response, + ) + .await + } + }; + let outcome = mutations + .proposal_mutation(ProposalMutationInput { + action_id: &action.id, + proposal_id: Some(id), + operation: ProposalAuthorityOperation::Lifecycle(ProposalOperation::Message), + authority: &authority, + idempotency_key: key, + expected_etag: Some(etag), + input: None, + submission_version: None, + effect_digest: None, + reason: None, + executor_lease: None, + rebase_start_authority: None, + attachment: None, + form: None, + answer: None, + message: Some(text), + correlation: &correlation, + human_identity: claims.human_identity(), + claims: Some(&claims), + }) + .await; + match outcome { + Ok(outcome) => exact_mutation( + outcome.response(), + None, + "", + service.field_encryption.as_deref(), + ), + Err(MutationError::MembershipPreconditionFailed) => concealed(FailedCheck::Membership), + Err(error) => proposal_target_problem(error), + } +} + +pub(in crate::api) async fn list( + State(service): State>, + Path(id): Path, + Extension(correlation): Extension, + Authenticated(claims): Authenticated, + RawQuery(raw_query): RawQuery, +) -> Response { + let (id, _, authority) = match admit( + &service, + &id, + &claims, + proposal_admission_profile(raw_query.as_deref()), + HttpMethod::Get, + &correlation, + ) + .await + { + Ok(admitted) => admitted, + Err(response) => return response, + }; + let Some(mutations) = &service.mutations else { + return concealed(FailedCheck::Visibility); + }; + let (before, limit) = match page_inputs(raw_query.as_deref()) { + Ok(page) => page, + Err(error) => { + return admitted_http_refusal( + mutations, + &authority, + HttpMethod::Get, + &correlation, + error.problem(), + ) + .await + } + }; + match mutations + .proposal_messages_page(id, &authority, before, limit, &correlation) + .await + { + Ok(value) => json_response(value, None), + Err(MutationError::MembershipPreconditionFailed) => concealed(FailedCheck::Membership), + Err(MutationError::PreconditionFailed) => concealed(FailedCheck::Visibility), + Err(error) => proposal_target_problem(error), + } +} + +/// 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, + Extension(correlation): Extension, + Authenticated(claims): Authenticated, + RawQuery(raw_query): RawQuery, + headers: HeaderMap, + body: Body, +) -> Response { + let (id, action, authority) = match admit( + &service, + &id, + &claims, + selected_profile(raw_query.as_deref()), + HttpMethod::Post, + &correlation, + ) + .await + { + Ok(admitted) => admitted, + Err(response) => return response, + }; + let Some(mutations) = &service.mutations else { + return concealed(FailedCheck::Visibility); + }; + let through = async { + if !single_content_type(&headers, "application/json") { + return Err(unsupported_media_type()); + } + let bytes = bounded_body_to(body, 1024) + .await + .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 + .get("through") + .and_then(Value::as_str) + .and_then(|id| Uuid::parse_str(id).ok()) + .ok_or_else(|| { + invalid_request_at( + &crate::problem_location::RequestLocation::proposal_message_through(), + ) + }), + _ => Err(invalid_request()), + } + } + .await; + let through = match through { + Ok(through) => through, + Err(response) => { + return admitted_http_refusal( + mutations, + &authority, + HttpMethod::Post, + &correlation, + response, + ) + .await + } + }; + // A caller without Get is answered from the review context, or with the + // thread alone while none is readable. + let thread_view = authorize( + &service.registry, + &action, + &claims, + Some(authority.common.access_profile()), + ProposalAuthorityOperation::Lifecycle(ProposalOperation::Get), + Some(id), + PartySelection::Exact(authority.party), + ) + .is_none(); + match mutations + .proposal_mark_messages_read(id, &authority, through, thread_view, &correlation) + .await + { + Ok(Some(thread)) => return json_response(thread, None), + Ok(None) => {} + Err(MutationError::MembershipPreconditionFailed) => { + return concealed(FailedCheck::Membership) + } + Err(MutationError::PreconditionFailed) => return concealed(FailedCheck::Visibility), + Err(error) => return proposal_target_problem(error), + } + caller_view( + service.clone(), + &action, + id, + &claims, + &authority, + &correlation, + ) + .await +} diff --git a/crates/registry-breg/src/api/tests/immediate_action_tests.rs b/crates/registry-breg/src/api/tests/immediate_action_tests.rs index 15d4d7ed35..e48a5d814a 100644 --- a/crates/registry-breg/src/api/tests/immediate_action_tests.rs +++ b/crates/registry-breg/src/api/tests/immediate_action_tests.rs @@ -297,7 +297,7 @@ async fn proposal_task_scopes_and_standing_agent_draft_and_context_permissions_a let mut task_profile = json!({"id":"task-proposer","principalClaim":"registry_principal","actorKind":"agent","requesterClients":["agent-client"], "requiredScopes":["case.rename"],"requiredPurposes":["case-management"],"taskGrant":{"sourceIssuer":"https://casework.example"}, "permissions":{"actions":[{"action":"propose-rename","operations":["start"],"targets":[{"recordType":"case","rowBoundaries":[{"field":"region","claim":"grantRegion","operator":"equals"}]}]}], - "proposals":[{"action":"propose-rename","operations":["get","list","edit","submit","revise","cancel","apply","rebase","retry","get-review-status"],"ownership":"caller", + "proposals":[{"action":"propose-rename","operations":["get","list","edit","submit","revise","cancel","apply","rebase","retry","get-review-status"],"party":"owner", "readableInputs":["case-ref","case-label"], "targets":[{"recordType":"case","rowBoundaries":[{"field":"region","claim":"grantRegion","operator":"equals"}]}]}]}}); project @@ -361,7 +361,15 @@ async fn proposal_task_scopes_and_standing_agent_draft_and_context_permissions_a .await .unwrap(); let admit = |claims: &VerifiedRequestClaims, profile: &str, operation, id| { - super::super::proposals::authorize(®istry, action, claims, Some(profile), operation, id) + super::super::proposals::authorize( + ®istry, + action, + claims, + Some(profile), + operation, + id, + super::super::proposals::PartySelection::Any, + ) }; assert!(admit( &start, @@ -572,6 +580,7 @@ fn delegated_standing_agent_reads_only_its_bounded_review_context() { Some("casework-source-reader"), ProposalAuthorityOperation::Lifecycle(operation), Some(Uuid::parse_str("00000000-0000-4000-8000-000000000001").unwrap()), + super::super::proposals::PartySelection::Any, ) }; let authority = admit(&delegated, ProposalOperation::GetReviewContext) @@ -1390,7 +1399,7 @@ async fn proposal_metadata_roundtrips_exact_profile_inventory_and_document_requi let proposals = if operations.as_array().unwrap().is_empty() { json!([]) } else { - json!([{"action":action,"operations":operations,"ownership":"caller","targets":targets, + json!([{"action":action,"operations":operations,"party":"owner","targets":targets, "readableInputs":readable,"readableAttachments":slots}]) }; project.access_profiles.push(serde_json::from_value(json!({ @@ -1499,6 +1508,147 @@ async fn proposal_metadata_roundtrips_exact_profile_inventory_and_document_requi ); } +/// Each party entry is its own inventory entry, every entry names the inputs +/// it may write (#2720), and a reader's Action description keeps the effects +/// on Record types it can see (#2719). +#[tokio::test] +async fn proposal_metadata_serves_party_entries_writable_inputs_and_reader_effects() { + use registry_breg_client::BRegMetadata; + use tower::ServiceExt; + + let source = json!({ + "apiVersion":"id.registrystack.org/formats/breg/project/v1alpha1","kind":"BRegProject", + "project":{"id":"party-metadata","version":"1","defaultLanguage":"en","canonicalBaseIri":"https://party-metadata.example.test"}, + "datasets":{"licences": {}}, + "recordTypes":{ + "licence": {"route":"licences","primaryDataset":"licences","mutationMode":"mutable","classification":"internal", + "fields":[ + {"id":"holder","type":"string","maximumLength":64,"required":true,"classification":"internal"}, + {"id":"statement","type":"string","maximumLength":64,"required":false,"classification":"internal"}]}, + "ledger": {"route":"ledger","primaryDataset":"licences","mutationMode":"mutable","classification":"internal", + "fields":[{"id":"holder","type":"string","maximumLength":64,"required":true,"classification":"internal"}]}}, + "actions":{ + "apply-for-licence": {"execution":{"mode":"proposal","proposal":{ + "review":{"type":"none"},"application":{"mode":"manual"},"retention":{"mode":"retain"}, + "subject":{"input":"holder"}}}, + "inputs":[ + {"id":"holder","type":"string","maximumLength":64,"required":true,"classification":"internal"}, + {"id":"statement","type":"string","maximumLength":64,"required":false,"classification":"internal"}], + "plan":{"type":"fixed","effects":[ + {"id":"issued","target":{"recordType":"licence"},"operation":"create", + "set":{"holder":{"fromInput":"holder"},"statement":{"fromInput":"statement"}}}, + {"id":"logged","target":{"recordType":"ledger"},"operation":"create", + "set":{"holder":{"fromInput":"holder"}}}]}}}, + "accessProfiles":{ + "citizen": {"principalClaim":"registry_principal","requiredScopes":["licence:self"],"actorKind":"human", + "permissions":{ + "actions":[{"action":"apply-for-licence","operations":["start"],"targets":[ + {"recordType":"licence","rowBoundaries":"unrestricted"},{"recordType":"ledger","rowBoundaries":"unrestricted"}]}], + "proposals":[ + {"action":"apply-for-licence","party":"owner","operations":["get","list","edit","submit","cancel"], + "readableInputs":["holder","statement"],"writableInputs":["statement"],"targets":[ + {"recordType":"licence","rowBoundaries":"unrestricted"},{"recordType":"ledger","rowBoundaries":"unrestricted"}]}, + {"action":"apply-for-licence","party":"subject","operations":["get","list","cancel"], + "readableInputs":["holder"],"targets":[ + {"recordType":"licence","rowBoundaries":"unrestricted"},{"recordType":"ledger","rowBoundaries":"unrestricted"}]}]}}, + "desk": {"principalClaim":"registry_principal","requiredScopes":["licence:desk"],"actorKind":"human", + "permissions":{"proposals":[ + {"action":"apply-for-licence","operations":["get","list","edit","submit"], + "submitsFor":"anyone","readableInputs":["holder","statement"],"targets":[ + {"recordType":"licence","rowBoundaries":"unrestricted"},{"recordType":"ledger","rowBoundaries":"unrestricted"}]}]}}, + "reader": {"principalClaim":"registry_principal","requiredScopes":["licence:read"],"actorKind":"human", + "permissions":{ + "records":[{"recordType":"licence","operations":["get"],"readableFields":["holder"],"rowBoundaries":"unrestricted"}], + "proposals":[{"action":"apply-for-licence","operations":["get"],"readableInputs":["holder"],"targets":[ + {"recordType":"licence","rowBoundaries":"unrestricted"},{"recordType":"ledger","rowBoundaries":"unrestricted"}]}]}}} + }); + let project = crate::contract::parse_project_json(&serde_json::to_vec(&source).unwrap()) + .expect("party metadata project parses"); + let registry = Arc::new( + compile_project(&project, &[], CompileProfile::Authoring).expect("party metadata compiles"), + ); + let service = Arc::new(service_for(registry, true)); + let document = |scope: &'static str, profile: &'static str| { + let service = service.clone(); + async move { + let mut request = axum::http::Request::builder() + .uri(format!("/v1/registry?accessProfile={profile}")) + .body(Body::empty()) + .unwrap(); + request.extensions_mut().insert( + VerifiedRequestClaims::authenticated_with_actor_kind( + "registry_principal", + "person-canary", + BTreeSet::from([scope.to_owned()]), + None, + BTreeMap::new(), + registry_platform_oidc::ActorKind::Human, + ) + .unwrap(), + ); + let response = super::super::router(service) + .oneshot(request) + .await + .unwrap(); + response_json(response).await + } + }; + + let citizen = document("licence:self", "citizen").await; + let entries = citizen["proposals"]["actions"].as_array().unwrap(); + assert_eq!(entries.len(), 2, "{citizen}"); + let owner = entries + .iter() + .find(|entry| entry["party"] == "owner") + .unwrap(); + let subject = entries + .iter() + .find(|entry| entry["party"] == "subject") + .unwrap(); + assert_eq!(owner["readableInputs"], json!(["holder", "statement"])); + assert_eq!(owner["writableInputs"], json!(["statement"])); + assert_eq!(subject["readableInputs"], json!(["holder"])); + assert_eq!(subject["writableInputs"], json!([])); + let action = &citizen["actions"][0]; + assert_eq!(action["subject"], json!({"input":"holder"})); + assert_eq!(action["writableInputs"], json!(["statement"])); + let metadata = BRegMetadata::from_slice(&serde_json::to_vec(&citizen).unwrap()).unwrap(); + let inventory = metadata.proposal_actions(); + assert_eq!(inventory.len(), 2); + let parsed_subject = inventory + .iter() + .find(|entry| entry.party() == Some(registry_breg_client::BRegProposalPartyRole::Subject)) + .unwrap(); + assert_eq!(parsed_subject.writable_inputs(), Some(&[][..])); + assert_eq!(metadata.actions()[0].subject_input(), Some("holder")); + + // A grant without the list writes every declared input. + let desk = document("licence:desk", "desk").await; + let entry = &desk["proposals"]["actions"][0]; + assert!(entry.get("party").is_none()); + assert_eq!(entry["writableInputs"], json!(["holder", "statement"])); + + // A reader writes nothing and keeps the effects on Record types it reads. + let reader = document("licence:read", "reader").await; + assert_eq!( + reader["proposals"]["actions"][0]["writableInputs"], + json!([]) + ); + let action = &reader["actions"][0]; + assert_eq!(action["routes"], json!({})); + assert_eq!(action["subject"], json!({"input":"holder"})); + assert_eq!( + action["resultEffects"], + json!([{"effect":"issued","recordType":"licence","operation":"create"}]), + "{action}" + ); + assert_eq!(action["writableInputs"], json!([])); + let metadata = BRegMetadata::from_slice(&serde_json::to_vec(&reader).unwrap()).unwrap(); + assert_eq!(metadata.actions()[0].inputs().len(), 1); + assert_eq!(metadata.actions()[0].inputs()[0].identifier(), "holder"); + assert_eq!(metadata.actions()[0].subject_input(), Some("holder")); +} + async fn response_json(response: Response) -> Value { assert_eq!(response.status(), StatusCode::OK); let bytes = to_bytes(response.into_body(), 1024 * 1024).await.unwrap(); @@ -1995,6 +2145,7 @@ async fn task_granted_proposal_start_binds_the_grant_to_the_request_principal_an Some("task-proposer"), ProposalAuthorityOperation::Start, None, + super::super::proposals::PartySelection::Any, ) }; assert!(admit(&matched).is_some_and(|authority| authority.task_grant.is_some())); @@ -2030,6 +2181,7 @@ async fn task_review_record_reads_bind_the_grant_to_the_request_principal_and_pu Some("task-reviewer"), ProposalAuthorityOperation::Lifecycle(operation), Some(BOUND_GRANT_PROPOSAL_ID), + super::super::proposals::PartySelection::Any, ) }; let authority = admit(&matched).expect("the matching grant opens the review context"); diff --git a/crates/registry-breg/src/artifacts.rs b/crates/registry-breg/src/artifacts.rs index 8c3c41a63b..27b567b81e 100644 --- a/crates/registry-breg/src/artifacts.rs +++ b/crates/registry-breg/src/artifacts.rs @@ -15,14 +15,14 @@ use crate::diagnostics::Diagnostic; use crate::generated_ddl::DdlInventory; use crate::manifest_adapter::project_manifest_artifacts; use crate::model::{ - ActionRouteKind, CompiledAccessInventory, CompiledAction, CompiledActionInput, - CompiledActionInventory, CompiledActionRoute, CompiledEntity, CompiledEventDeliveryInventory, - CompiledManifestProjection, CompiledMetadataInventory, CompiledModuleIdentity, - CompiledPlanEffect, CompiledPlanMutation, CompiledPlanValue, CompiledQueryInventory, - CompiledQueryKind, CompiledQueryOperation, CompiledQueryTemporalBinding, - CompiledQueryTemporalSemantics, CompiledQueryTemporalValueKind, CompiledRecipients, - CompiledRevisionKind, CompiledRoute, CompiledRouteInventory, CompiledStatisticalDataset, - DisclosureWithhold, HttpMethod, + ActionRouteKind, CompiledAccessInventory, CompiledAction, CompiledActionExecution, + CompiledActionInput, CompiledActionInventory, CompiledActionRoute, CompiledEntity, + CompiledEventDeliveryInventory, CompiledManifestProjection, CompiledMetadataInventory, + CompiledModuleIdentity, CompiledPlanEffect, CompiledPlanMutation, CompiledPlanValue, + CompiledQueryInventory, CompiledQueryKind, CompiledQueryOperation, + CompiledQueryTemporalBinding, CompiledQueryTemporalSemantics, CompiledQueryTemporalValueKind, + CompiledRecipients, CompiledRevisionKind, CompiledRoute, CompiledRouteInventory, + CompiledStatisticalDataset, DisclosureWithhold, HttpMethod, }; use crate::physical_names::{hex_prefix, PhysicalNameInventory}; use crate::record_profile::{link_header_value, CONTEXT_IDENTIFIER, PROFILE_IDENTIFIER}; @@ -649,7 +649,7 @@ pub fn inspect_action(action: &CompiledAction) -> Value { value }) .collect::>(); - json!({ + let mut inspection = json!({ "id": action.id, "apiName": action.api_name, "revision": action.definition_revision, "display": action.display, "migrationReviewRevision": crate::immediate_actions::migration_review_revision(action), @@ -662,7 +662,49 @@ pub fn inspect_action(action: &CompiledAction) -> Value { "bounds": {"maximumTargets": action.maximum_targets, "maximumFieldMutations": action.maximum_field_mutations, "maximumSnapshotBytes": action.maximum_snapshot_bytes}, - }) + }); + if let CompiledActionExecution::Proposal { proposal } = &action.execution { + if !proposal.additional_forms.is_empty() { + let contracts: Map<_, _> = proposal + .additional_forms + .iter() + .map(|(id, form)| { + ( + id.clone(), + additional_form_contract(&action.id, id, &form.inputs), + ) + }) + .collect(); + inspection["additionalFormContracts"] = Value::Object(contracts); + } + } + inspection +} + +pub(crate) fn additional_form_contract( + action_id: &str, + form_id: &str, + inputs: &[CompiledActionInput], +) -> Value { + let mut inputs: Vec<_> = inputs.iter().collect(); + inputs.sort_by(|left, right| left.api_name.cmp(&right.api_name)); + let mut schema = action_input_properties_schema(inputs.iter().copied(), &[], false); + schema["minProperties"] = json!(1); + let fields = inputs + .iter() + .map(|input| { + json!({ + "id": input.id, + "apiName": input.api_name, + "fieldType": input.field_type, + "classification": input.classification, + }) + }) + .collect::>(); + let contract = json!({"actionId":action_id,"formId":form_id,"fields":fields,"schema":schema}); + let canonical = canonicalize_json(&contract).expect("compiled additional form canonicalizes"); + let digest = registry_review_protocol::ContentDigest::for_bytes(&canonical); + json!({"digest":digest,"schema":schema}) } fn inspect_scripted_plan(plan: &crate::model::CompiledPlanFunction) -> Value { @@ -1091,7 +1133,14 @@ pub(crate) fn openapi_action_response_schema( selected_result_effects: Option<&BTreeSet>, ) -> Value { if let crate::model::CompiledActionExecution::Proposal { proposal } = &action.execution { - return proposal_schema_with_additions(proposal.additions.is_some()); + let mut schema = proposal_schema_with_additions(proposal.additions.is_some()); + if !proposal.additional_forms.is_empty() { + append_proposal_forms_schema(&mut schema); + } + if proposal.messages.is_some() { + schema["properties"]["messages"] = proposal_artifacts::proposal_messages_schema(false); + } + return schema; } let result_shapes = action_response_result_shapes(action, selected_result_effects); let results_schema = match result_shapes.as_slice() { @@ -1459,6 +1508,19 @@ pub(crate) fn public_action_metadata_entry( } }); if let crate::model::CompiledActionExecution::Proposal { proposal } = &action.execution { + if let Some(subject) = &proposal.subject { + metadata["subject"] = json!({"input": subject.input}); + } + // The inputs the selected profile's draft may set, from the entry + // that governs a draft it starts. + if let Some(profile) = selected_profile { + if let Some(grant) = proposal.permissions.iter().find(|grant| { + grant.profile_id == profile + && matches!(grant.party, None | Some(crate::model::ProposalParty::Owner)) + }) { + metadata["writableInputs"] = json!(proposal_writable_inputs(action, grant)); + } + } // Callers learn only whether a request is reviewed and whether an // accepted request is applied automatically. The review authority, // source, policy selection and attempt limit stay in the build-time @@ -1498,9 +1560,63 @@ pub(crate) fn public_action_metadata_entry( .remove("invoke"); metadata["routes"]["start"] = start; } + if let (Some(profile), CompiledActionExecution::Proposal { proposal }) = + (selected_profile, &action.execution) + { + if let Some(thread) = proposal.messages.filter(|_| { + proposal.permissions.iter().any(|grant| { + grant.profile_id == profile + && grant + .operations + .contains(&crate::model::ProposalOperation::Message) + }) + }) { + metadata["messages"] = + json!({"maximumCount":thread.maximum_count,"maximumTextBytes":2000}); + } + let forms = proposal.additional_forms.iter().filter(|(id, _)| { + proposal.permissions.iter().any(|grant| { + grant.profile_id == profile + && (grant.readable_forms.contains(*id) || grant.writable_forms.contains(*id)) + }) + }).map(|(id, form)| { + (id.clone(), json!({"inputs":form.inputs.iter().map(|input|action_input_metadata(input,false)).collect::>()})) + }).collect::>(); + if !forms.is_empty() { + metadata["additionalForms"] = Value::Object(forms); + } + } metadata } +/// The inputs a Proposal grant may set: its `writableInputs`, every declared +/// input when it names none, and none when it can neither start the Action +/// nor Edit, Revise or Rebase. +pub(crate) fn proposal_writable_inputs( + action: &CompiledAction, + grant: &crate::model::CompiledProposalPermission, +) -> Vec { + use crate::model::ProposalOperation; + let starts = grant.party != Some(crate::model::ProposalParty::Subject) + && action.permissions.iter().any(|permission| { + permission.profile_id == grant.profile_id + && permission.operations.contains(&Operation::Start) + }); + let edits = grant.operations.iter().any(|operation| { + matches!( + operation, + ProposalOperation::Edit | ProposalOperation::Revise | ProposalOperation::Rebase + ) + }); + if !(starts || edits) { + return Vec::new(); + } + match &grant.writable_inputs { + Some(writable) => writable.iter().cloned().collect(), + None => action.inputs.iter().map(|input| input.id.clone()).collect(), + } +} + /// Shared schema for the distinct Proposal resource, never a Record envelope. pub fn proposal_apply_input_schema() -> Value { json!({"type":"object","additionalProperties":false, @@ -1525,6 +1641,7 @@ pub fn proposal_schema() -> Value { "application":proposal_application_schema(), "applicationStatus":proposal_application_status_schema(), "turn":{"enum":["party","official","nobody"]}, + "partyRole":{"enum":["owner","subject"]}, "decision":proposal_decision_schema(), "asks":proposal_asks_schema(false), "handoffRefusal":proposal_handoff_refusal_schema(), @@ -1545,9 +1662,12 @@ pub(crate) fn proposal_asks_schema(review: bool) -> Value { let uuid = json!({"type":"string","format":"uuid"}); let instant = json!({"type":"string","format":"date-time"}); let text = json!({"type":"string","minLength":1,"maxLength":2000}); - let wants = json!({"type":"array","maxItems":8,"uniqueItems":true,"items":{ - "type":"object","additionalProperties":false,"required":["kind"], - "properties":{"kind":{"enum":["answer","document"]}}}}); + let wants = json!({"type":"array","maxItems":8,"uniqueItems":true,"items":{"oneOf":[ + {"type":"object","additionalProperties":false,"required":["kind"], + "properties":{"kind":{"enum":["answer","document"]}}}, + {"type":"object","additionalProperties":false,"required":["kind","form"], + "properties":{"kind":{"const":"form"},"form":{"type":"string","pattern":"^[a-z][a-z0-9_-]{0,63}$"}}} + ]}}); let mut answer = json!({"type":"object","additionalProperties":false, "required":["answeredAt"],"properties":{"text":text,"answeredAt":instant}}); let mut properties = json!({"id":uuid,"text":text,"wants":wants, @@ -1555,6 +1675,8 @@ pub(crate) fn proposal_asks_schema(review: bool) -> Value { let mut required = vec!["id", "text", "wants", "askedAt", "state"]; if review { answer["required"] = json!(["documents", "answeredAt"]); + answer["properties"]["formEntries"] = + json!({"type":"array","maxItems":32,"items":proposal_form_entry_schema(false)}); answer["properties"]["documents"] = json!({"type":"array","maxItems":32,"items":{ "type":"object","additionalProperties":false, "required":["id","sha256","contentType","byteSize","verificationStatus"], @@ -1565,6 +1687,8 @@ pub(crate) fn proposal_asks_schema(review: bool) -> Value { "properties":{"method":{"const":"GET"},"operation":{"const":"get-review-context"},"accessProfile":{"type":"string"},"path":{"type":"string"}}}}}}); } else { answer["required"] = json!(["additions", "answeredAt"]); + answer["properties"]["formEntries"] = + json!({"type":"array","maxItems":32,"uniqueItems":true,"items":uuid}); answer["properties"]["additions"] = json!({"type":"array","maxItems":32,"uniqueItems":true,"items":uuid}); required.push("links"); @@ -1576,6 +1700,45 @@ pub(crate) fn proposal_asks_schema(review: bool) -> Value { json!({"type":"array","maxItems":crate::contract::MAX_MIRRORED_REVIEW_ASKS,"items":{"type":"object","additionalProperties":false,"required":required,"properties":properties}}) } +fn proposal_form_entry_schema(applicant: bool) -> Value { + let mut schema = json!({ + "type":"object","additionalProperties":false,"required":["id","addedAt"], + "oneOf":[{"required":["input"],"not":{"required":["contractChanged"]}}, + {"required":["contractChanged"],"not":{"required":["input"]}}], + "properties":{ + "id":{"type":"string","format":"uuid"},"addedAt":{"type":"string","format":"date-time"}, + "input":{"type":"object","minProperties":1,"maxProperties":16}, + "contractChanged":{"const":true} + } + }); + if applicant { + schema["required"] + .as_array_mut() + .expect("required members") + .push(json!("submissionVersion")); + schema["properties"]["submissionVersion"] = + json!({"type":"integer","minimum":1,"maximum":u32::MAX}); + } + schema +} + +pub(crate) fn append_proposal_forms_schema(schema: &mut Value) { + schema["properties"]["formEntryId"] = json!({"type":"string","format":"uuid"}); + schema["properties"]["additionalForms"] = json!({"type":"object","maxProperties":8, + "additionalProperties":{"type":"object","additionalProperties":false,"required":["id","maximumCount"], + "anyOf":[{"required":["items"]},{"required":["links"]}], + "properties":{"id":{"type":"string"},"maximumCount":{"type":"integer","minimum":1,"maximum":32}, + "items":{"type":"array","maxItems":32,"items":proposal_form_entry_schema(true)}, + "links":{"type":"object","additionalProperties":false,"properties":{"add":{ + "type":"object","additionalProperties":false,"required":["method","path","accessProfile","operation","ifMatch","availability"], + "properties":{"method":{"const":"POST"},"operation":{"const":"add"},"path":{"type":"string"}, + "accessProfile":{"type":"string"},"ifMatch":{"type":"string"},"availability":availability_schema()} + }}} + } + } + }); +} + pub(crate) fn proposal_schema_with_additions(enabled: bool) -> Value { let mut schema = proposal_schema(); if enabled { @@ -2454,7 +2617,7 @@ fn openapi_document(input: OpenApiDocumentInput<'_>) -> Result) -> &'static str { Operation::Import => { unreachable!("import routes are served only by the ingestion-run surface") } + Operation::Reference => unreachable!("a reference grant has no route"), } } @@ -3254,6 +3418,14 @@ fn operation_parameters( json!({"type": "string", "minLength": 1, "maxLength": 256, "pattern": "^[\\x21-\\x2B\\x2D-\\x3A\\x3C-\\x7E]+$"}), "Idempotency key bound to method, route, caller, target record, package revision, request body, and response field set.", )); + if route.operation == Operation::Batch { + parameters.push(header_parameter( + "Registry-Access-Reason", + false, + json!({"type": "string", "minLength": 1, "maxLength": 684, "pattern": "^[A-Za-z0-9_-]+$"}), + "Access reason as unpadded base64url UTF-8. Supply it when the selected Batch profile requires a reason or a Batch item names a reference whose target grant requires one.", + )); + } if matches!(route.operation, Operation::Patch | Operation::Tombstone) { parameters.push(header_parameter( "If-Match", @@ -3268,6 +3440,7 @@ fn operation_parameters( Operation::Import => { unreachable!("import routes are served only by the ingestion-run surface") } + Operation::Reference => unreachable!("a reference grant has no route"), } parameters } @@ -3324,11 +3497,11 @@ fn read_query_parameters( if route.query_kind == Some(CompiledQueryKind::AsOf) { parameters.push(query_parameter( "asOf", - true, + false, false, temporal_value_schema(route, query, access_profiles) .expect("as-of routes have a compiled temporal binding"), - "The date to read on a date interval, or a strict UTC RFC3339 instant on a timestamp interval.", + "Required on the first page: a date on a date interval or a strict UTC RFC3339 instant on a timestamp interval. Omit on continuation requests, which carry only cursor and the applicable access profile.", )); } if query_profiles_for_route(route, query, access_profiles) @@ -3433,7 +3606,7 @@ fn operation_request_body(spec: OpenApiOperationSpec<'_>) -> 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, @@ -3464,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 @@ -3476,6 +3649,7 @@ fn operation_request_body(spec: OpenApiOperationSpec<'_>) -> Option { Operation::Import => { unreachable!("import routes are served only by the ingestion-run surface") } + Operation::Reference => unreachable!("a reference grant has no route"), } } @@ -3486,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}} }) } @@ -3497,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, )) } @@ -3513,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, ) } @@ -3527,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", @@ -3539,7 +3713,7 @@ fn batch_input_schema( create_data_schema, maximum_items, allow_create, - allow_patch, + patch_schema, ) } }) @@ -3551,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 { @@ -3565,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, @@ -3574,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, } })); } @@ -3628,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 { @@ -3728,6 +3983,7 @@ fn operation_responses(spec: OpenApiOperationSpec<'_>) -> Value { Operation::Import => { unreachable!("import routes are served only by the ingestion-run surface") } + Operation::Reference => unreachable!("a reference grant has no route"), Operation::Invoke | Operation::Start => success_response( "Action accepted", StatusResponseHeaders::ActionMutation, @@ -4486,7 +4742,8 @@ fn operation_may_refuse_write(spec: OpenApiOperationSpec<'_>) -> bool { .entity .access_profiles .get(profile_id) - .is_some_and(|profile| !profile.row_boundaries.is_empty()); + .is_some_and(|profile| !profile.row_boundaries.is_empty()) + || !crate::membership::boundaries(spec.entity, profile_id).is_empty(); let disclosure = crate::disclosure::plan(spec.entity, profile_id); let disclosure_refuses = if spec.route.operation == Operation::Create { disclosure @@ -4936,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() } @@ -5180,7 +5441,7 @@ fn query_kind_name(kind: CompiledQueryKind) -> &'static str { } } -fn operation_name(operation: Operation) -> &'static str { +pub(crate) fn operation_name(operation: Operation) -> &'static str { match operation { Operation::Create => "create", Operation::Get => "get", @@ -5194,6 +5455,7 @@ fn operation_name(operation: Operation) -> &'static str { Operation::Invoke => "invoke", Operation::Start => "start", Operation::Import => "import", + Operation::Reference => "reference", } } diff --git a/crates/registry-breg/src/audit.rs b/crates/registry-breg/src/audit.rs index dc7c4d8b16..3af0ff5fd2 100644 --- a/crates/registry-breg/src/audit.rs +++ b/crates/registry-breg/src/audit.rs @@ -743,7 +743,7 @@ fn proposal_pre_io_record( let allowed = match event.method { HttpMethod::Get => matches!( operation, - "get" | "list" | "get-review-context" | "get-review-status" + "get" | "list" | "get-review-context" | "get-review-status" | "message" ), HttpMethod::Post => matches!( operation, @@ -758,6 +758,7 @@ fn proposal_pre_io_record( | "cancel" | "apply" | "get-task-grant-context" + | "message" ), HttpMethod::Patch | HttpMethod::Delete => operation == "edit", }; diff --git a/crates/registry-breg/src/auth.rs b/crates/registry-breg/src/auth.rs index 2ad4ae9b66..ec3827682a 100644 --- a/crates/registry-breg/src/auth.rs +++ b/crates/registry-breg/src/auth.rs @@ -381,6 +381,7 @@ pub(crate) fn compiled_profile_facts( .row_boundaries .iter() .any(|boundary| claim_is_principal(&boundary.claim, principal)) + || !target.membership_boundaries.is_empty() }); entry.has_subject_row_rule |= subject_row; entry.reads_principal |= subject_row; @@ -393,12 +394,13 @@ pub(crate) fn compiled_profile_facts( for grant in &proposal.permissions { let entry = facts.entry(grant.profile_id.clone()).or_default(); let principal = grant.principal_claim.as_deref(); - let subject_row = grant.ownership == Some(crate::model::ProposalOwnership::Caller) + let subject_row = grant.party.is_some() || grant.targets.iter().any(|target| { target .row_boundaries .iter() .any(|boundary| claim_is_principal(&boundary.claim, principal)) + || !target.membership_boundaries.is_empty() }); entry.has_subject_row_rule |= subject_row; entry.reads_principal |= subject_row; diff --git a/crates/registry-breg/src/authoring_integrity.rs b/crates/registry-breg/src/authoring_integrity.rs index 0ca260d7c9..2fab0104ea 100644 --- a/crates/registry-breg/src/authoring_integrity.rs +++ b/crates/registry-breg/src/authoring_integrity.rs @@ -581,6 +581,27 @@ fn action_integrity( add_collisions(document, errors, "breg.action-effect.id-collision", &values); } if let ActionExecutionSource::Proposal { proposal } = &action.execution { + let forms = format!("{base}/execution/proposal/additionalForms"); + let form_ids: Vec<_> = proposal + .additional_forms + .keys() + .map(|id| (id.clone(), keyed_pointer(&forms, id))) + .collect(); + add_key_collisions( + document, + errors, + "breg.additional-form.id-collision", + &form_ids, + ); + for (id, form) in &proposal.additional_forms { + let inputs = format!("{}/inputs", keyed_pointer(&forms, id)); + add_collisions( + document, + errors, + "breg.additional-form-input.id-collision", + &indexed_ids(&inputs, &form.inputs, |input| &input.id), + ); + } for (code, values) in [ ( "breg.attachment.id-lookalike", @@ -757,7 +778,7 @@ pub(crate) fn project_diagnostics( ), ), ( - "breg.manifest.entity-id-collision", + "breg.manifest.record-type-id-collision", indexed_ids(&format!("{base}/entities"), &projection.entities, |item| { &item.id }), @@ -1040,7 +1061,7 @@ fn add_project_display_warnings( .collect::>(), ), ( - "breg.manifest-entity.duplicate-title", + "breg.manifest-record-type.duplicate-title", "manifest entities", projection .entities diff --git a/crates/registry-breg/src/compiler.rs b/crates/registry-breg/src/compiler.rs index d01c7cad6b..973668e52b 100644 --- a/crates/registry-breg/src/compiler.rs +++ b/crates/registry-breg/src/compiler.rs @@ -119,9 +119,8 @@ pub const HOOK_BACKOFF_MULTIPLIER: u8 = 2; /// ingestion errors map onto, and the shared admission envelope every /// secured route answers with (the bearer refusal, the authorization /// concealment, and the audit-gated unavailability). The OpenAPI builder -/// publishes exactly these sets, and the ingestion contract test holds the -/// published document to them, so the catalogue cannot drift from what the -/// routes can actually answer. +/// publishes these sets and adds the reason refusal for Batch grants that +/// require it. The ingestion contract tests hold the document to both rules. #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum IngestionApiOperation { CreateRun, @@ -157,7 +156,7 @@ impl IngestionApiOperation { } } - /// Every problem response the operation can answer with. + /// The problem responses independent of the selected grant's reason requirement. #[must_use] pub const fn problem_codes(self) -> &'static [crate::problem::ProblemCode] { match self { @@ -245,6 +244,33 @@ pub fn compile_project_with_assets( modules: &[RegistryModule], assets: &[ModuleAssetSource], profile: CompileProfile, +) -> Result { + compile_with_reference_target_requirement(project, modules, assets, profile, true) +} + +/// Reconstruct the schema of a verified predecessor for migration rehearsal. +/// A v0.51.0 package can declare writable references without target grants. +#[cfg(feature = "tooling")] +pub(crate) fn compile_verified_predecessor_for_rehearsal( + project: &RegistryProject, + modules: &[RegistryModule], + assets: &[ModuleAssetSource], +) -> Result { + compile_with_reference_target_requirement( + project, + modules, + assets, + CompileProfile::Production, + false, + ) +} + +fn compile_with_reference_target_requirement( + project: &RegistryProject, + modules: &[RegistryModule], + assets: &[ModuleAssetSource], + profile: CompileProfile, + require_reference_target_grants: bool, ) -> Result { let mut diagnostics = Vec::new(); let mut findings = Vec::new(); @@ -340,7 +366,18 @@ pub fn compile_project_with_assets( &mut diagnostics, ); crate::access::validate_access_requirements(&sources, &mut diagnostics); - crate::membership::validate(&sources, &mut diagnostics); + crate::access::validate_reference_targets( + &sources, + require_reference_target_grants, + &mut diagnostics, + ); + crate::membership::validate(project, &action_sources, &sources, &mut diagnostics); + crate::proposal_subject::validate_field_writes( + project, + &action_sources, + &sources, + &mut diagnostics, + ); crate::consent::validate(project, &sources, &mut diagnostics); crate::event_record::validate(&sources, &mut diagnostics); findings.extend(crate::access::access_findings(&sources)); @@ -378,6 +415,13 @@ pub fn compile_project_with_assets( "relationship compilation", ) })?; + crate::membership::compile(&mut entities).map_err(|errors| { + stopped_compile_failure( + CompileFailure::from_errors(errors), + &findings, + "membership compilation", + ) + })?; let statistical_datasets = statistics::compile(project, &entities).map_err(|errors| { stopped_compile_failure( CompileFailure::from_errors(errors), @@ -406,7 +450,6 @@ pub fn compile_project_with_assets( &entities, )); crate::external_views::mark_link_fields(&external_views, &mut entities, &mut physical_names); - crate::membership::compile(&mut entities); let recipients = crate::consent::compile(project, &sources, &mut entities); crate::event_record::compile(&sources, &mut entities); let timer_actions = sources @@ -2020,7 +2063,7 @@ fn validate_cross_file_duplicate_display_labels( &distributions, ), ( - "breg.manifest-entity.duplicate-title", + "breg.manifest-record-type.duplicate-title", "manifest entities", &entities, ), @@ -2648,7 +2691,7 @@ fn validate_manifest_projection( let path = format!("project.recordTypes[{}].primaryDataset", entity.id); let Some(dataset_id) = entity.primary_dataset.as_deref() else { errors.push(Diagnostic::error( - "breg.manifest-projection.entity-primary-dataset-required", + "breg.manifest-projection.record-type-primary-dataset-required", path, "every exposed entity must name one primaryDataset", )); @@ -2659,7 +2702,7 @@ fn validate_manifest_projection( } if !datasets.contains_key(dataset_id) { errors.push(Diagnostic::error( - "breg.manifest-projection.entity-dataset-dangling", + "breg.manifest-projection.record-type-dataset-dangling", path, "entity primaryDataset must reference manifestProjection.datasets[]", )); @@ -2670,7 +2713,7 @@ fn validate_manifest_projection( for (index, dataset) in projection.datasets.iter().enumerate() { if !members.contains_key(dataset.id.as_str()) { errors.push(Diagnostic::error( - "breg.manifest-projection.dataset-entities-empty", + "breg.manifest-projection.dataset-record-types-empty", format!("project.manifestProjection.datasets[{index}]"), "every dataset must contain at least one exposed entity", )); @@ -2817,7 +2860,7 @@ fn validate_manifest_projection( let path = format!("project.manifestProjection.entities[{}]", metadata.id); if !entity_ids.insert(metadata.id.as_str()) { errors.push(Diagnostic::error( - "breg.manifest-projection.entity-duplicate", + "breg.manifest-projection.record-type-duplicate", path, "Registry Manifest entity metadata must be unique", )); @@ -2825,7 +2868,7 @@ fn validate_manifest_projection( } let Some((entity, visible_fields)) = visible.get(metadata.id.as_str()) else { errors.push(Diagnostic::error( - "breg.manifest-projection.entity-not-visible", + "breg.manifest-projection.record-type-not-visible", path, "Registry Manifest metadata may describe only an entity visible through the selected access profile", )); @@ -3425,7 +3468,15 @@ pub fn module_digest(module: &RegistryModule) -> String { } pub fn module_digest_with_assets(module: &RegistryModule, assets: &[ModuleAssetSource]) -> String { - let mut value = serde_json::to_value(module).expect("module serializes"); + let value = serde_json::to_value(module).expect("module serializes"); + module_source_digest(&module.id, value, assets) +} + +pub(crate) fn module_source_digest( + id: &str, + mut value: serde_json::Value, + assets: &[ModuleAssetSource], +) -> String { // Both module digest domains use the sealed Action Plan vocabulary. // Project and module authoring use the current names independently. let members = value @@ -3447,7 +3498,7 @@ pub fn module_digest_with_assets(module: &RegistryModule, assets: &[ModuleAssetS let bytes = canonicalize_json(&value).expect("module canonicalizes"); let mut module_assets = assets .iter() - .filter(|asset| asset.module.as_deref() == Some(module.id.as_str())) + .filter(|asset| asset.module.as_deref() == Some(id)) .collect::>(); if module_assets.is_empty() { let digest = Sha256::digest(bytes); @@ -4218,7 +4269,12 @@ pub(crate) fn expand_project_access( required_filters: grant.required_filters.clone(), spatial_queries: grant.spatial_queries.clone(), row_boundaries: grant.row_boundaries.clone(), - membership_boundaries: grant.membership_boundaries.clone(), + membership_boundaries: grant + .membership_row_boundaries + .iter() + .cloned() + .map(crate::contract::MembershipBoundarySource::Declared) + .collect(), require_consent: grant.require_consent.clone(), lookups: grant.lookups.clone(), read_paths: grant.read_paths.clone(), @@ -4252,7 +4308,14 @@ fn resolve_readable_fields( for profile in &mut profiles { let consent_scope = (!profile.require_consent.is_empty()) .then(|| format!("recordTypes[id={id}].accessProfiles[id={}]", profile.id)); - if let Some(ceiling) = profile.readable_fields_ceiling.take() { + // Reference exclusivity checks the authored selection even when it + // would select no fields. + let ceiling = if profile.operations.contains(&Operation::Reference) { + None + } else { + profile.readable_fields_ceiling.take() + }; + if let Some(ceiling) = ceiling { if let Some(path) = &consent_scope { errors.push(consent_ceiling_refusal(format!("{path}.readableFields"))); } @@ -4443,7 +4506,7 @@ fn validate_entities( nonempty( &entity.primary_dataset, "recordTypes[].primaryDataset", - "breg.manifest-projection.entity-primary-dataset-required", + "breg.manifest-projection.record-type-primary-dataset-required", errors, ); validate_id(&entity.route, "recordTypes[].route", errors); @@ -6030,6 +6093,62 @@ fn reaches<'a>( .any(|(_, next)| reaches(next, target, edges, visited)) } +/// Whether a `reference` grant carries only what it may: the operation, the +/// rows it may name (row boundaries and membership entries), and the members +/// its profile sets for every grant. Every member is named, so a member added +/// later must be placed on one side before this compiles. +fn reference_grant_is_bare(access: &AccessProfileSource) -> bool { + let AccessProfileSource { + // Profile members, the same on every grant of the profile. + id: _, + display: _, + default: _, + actor_kind: _, + requester_clients: _, + task_grant: _, + principal_claim: _, + required_scopes: _, + required_purposes: _, + require_access_reason: _, + // The rows a write may name. + row_boundaries: _, + membership_boundaries: _, + operations, + // Everything below serves or shapes a read or a write. + readable_fields, + readable_fields_ceiling, + readable_attachments, + writable_fields, + filterable_fields, + required_filters, + sortable_fields, + spatial_queries, + require_consent, + lookups, + read_paths, + allow_count, + revision_access, + provenance_fields, + allow_data_export, + } = access; + operations.len() == 1 + && readable_fields.is_empty() + && readable_fields_ceiling.is_none() + && readable_attachments.is_empty() + && writable_fields.is_empty() + && filterable_fields.is_empty() + && required_filters.is_empty() + && sortable_fields.is_empty() + && spatial_queries.is_none() + && require_consent.is_empty() + && lookups.is_empty() + && read_paths.is_empty() + && !allow_count + && !revision_access + && provenance_fields.is_empty() + && !allow_data_export +} + /// An `import` grant creates records only through a durable ingestion run, /// so it needs the entity's chunk bounds and no raw batch grant beside it on /// the entity: a batch grant would write the same records outside any import @@ -6124,6 +6243,16 @@ fn validate_profiles( if access.operations.contains(&Operation::Import) { validate_import_grant(entity, access, errors); } + if access.operations.contains(&Operation::Reference) && !reference_grant_is_bare(access) { + errors.push(Diagnostic::error( + "breg.access-profile.reference-exclusive", + format!( + "recordTypes[id={}].accessProfiles[id={}].operations", + entity.id, access.id + ), + "a reference grant lets the profile's direct writes name records of this Record type and nothing else: grant no other operation, field, read path, lookup, filter, count, revision, export or spatial access beside it", + )); + } if access.operations.contains(&Operation::Batch) && !access .operations @@ -8384,6 +8513,7 @@ fn compile_entities( batch: source.batch.clone(), classification: source.classification, access_requirements: source.access_requirements.clone(), + membership: source.membership.clone(), access_log: source.access_log.clone(), disclosure_conditions: disclosure::compile_conditions(source), geojson: source @@ -9409,6 +9539,7 @@ fn route_shape(entity: &CompiledEntity, operation: Operation) -> (HttpMethod, St Operation::Invoke | Operation::Start => { unreachable!("Actions use compiled action metadata") } + Operation::Reference => unreachable!("a reference grant has no route"), } } @@ -9469,6 +9600,7 @@ pub(crate) fn operation_id(operation: Operation) -> &'static str { Operation::Invoke => "invoke", Operation::Start => "start", Operation::Import => "import", + Operation::Reference => "reference", } } diff --git a/crates/registry-breg/src/compiler/disclosure/reach.rs b/crates/registry-breg/src/compiler/disclosure/reach.rs index 34346cdebf..20bd2c26b3 100644 --- a/crates/registry-breg/src/compiler/disclosure/reach.rs +++ b/crates/registry-breg/src/compiler/disclosure/reach.rs @@ -12,8 +12,7 @@ use std::collections::{BTreeMap, BTreeSet}; use crate::contract::{ AccessProfileSource, BoundaryOperator, DerivedSource, DisclosureConditionSource, - DisclosureWithholdSource, EntitySource, Operation, RowBoundarySource, TimerPredicateSource, - UniqueSet, + DisclosureWithholdSource, EntitySource, Operation, TimerPredicateSource, UniqueSet, }; use crate::diagnostics::Diagnostic; use crate::external_views::CompiledExternalViews; @@ -139,7 +138,7 @@ pub(super) fn validate_boundaries( if profile .membership_boundaries .iter() - .any(|boundary| boundary.field == *field) + .any(|boundary| boundary.field() == field) { refuse( errors, @@ -587,7 +586,9 @@ fn reads_derived_from( ) } -/// The profile's grant on `source`, when it reads rows. +/// The profile's grant on `source`, when it reads rows. A reference grant +/// holds the row policy only for a write's reach check and reads no field, +/// so derived SQL needs a grant that reads. fn reading_grant<'a>( source: &'a EntitySource, reader: &DerivedReader<'_>, @@ -596,15 +597,20 @@ fn reading_grant<'a>( .access_profiles .iter() .find(|grant| grant.id == reader.request_grant.id) - .filter(|grant| crate::generated_ddl::grant_reads_rows(grant.operations.as_set())) + .filter(|grant| { + crate::generated_ddl::grant_reads_rows(grant.operations.as_set()) + && !grant + .operations + .contains(&crate::contract::Operation::Reference) + }) } -fn backticked<'a>(values: impl IntoIterator) -> String { +fn backticked(values: impl IntoIterator + Ord>) -> String { values .into_iter() .collect::>() .into_iter() - .map(|value| format!("`{value}`")) + .map(|value| format!("`{}`", value.as_ref())) .collect::>() .join(", ") } @@ -643,7 +649,7 @@ fn withheld_source_rows( }; if !grant.membership_boundaries.is_empty() { found.push(( - source_path("membershipBoundaries"), + source_path("rowBoundaries"), format!( "{reads}, and its grant on `{source}` requires a membership through {through}, so its derived values leave out the `{source}` rows the caller holds no such membership for", source = source.id, @@ -651,7 +657,7 @@ fn withheld_source_rows( grant .membership_boundaries .iter() - .map(|boundary| &boundary.membership_entity) + .map(crate::contract::MembershipBoundarySource::record_type) ), ), )); @@ -689,7 +695,7 @@ fn unlinked_source_rows( "{reads}, and a subquery that refers to no column of the row reads every `{source}` row the profile sees, which its grant on `{source}` bounds by {boundaries}, so its derived values cover only those rows, not every `{source}` row", reads = reads_derived_from(owner, source, reader), source = source.id, - boundaries = describe_row_boundaries(&grant.row_boundaries), + boundaries = describe_row_boundaries(grant), ), )) } @@ -746,7 +752,7 @@ fn derived_source_refusal( format!( "{reads}, but the profile cannot read `{source}` rows, {missed}: {rewrite}grant it `get` on `{source}`, with only {readable} readable and the row boundaries {boundaries} of its grant on `{request_entity}`", source = source.id, - boundaries = describe_row_boundaries(&request.row_boundaries), + boundaries = describe_row_boundaries(request), readable = readable, rewrite = rewrite, ), @@ -784,10 +790,15 @@ fn derived_source_refusal( code, source_path("rowBoundaries"), format!( - "{reads}, but its grant on `{source}` is bounded by {source_rows} and its grant on `{request_entity}` by {request_rows}, {missed}: {rewrite}bound the grant on `{source}` by {request_rows} too, on fields that hold the same values", + "{reads}, but its grant on `{source}` is bounded by {source_rows} and its grant on `{request_entity}` by {request_rows}, {missed}: {rewrite}{fix}", + fix = if request.membership_boundaries.is_empty() { + format!("bound the grant on `{}` by {request_rows} too, on fields that hold the same values", source.id, request_rows = describe_row_boundaries(request)) + } else { + "align the claim boundaries on fields that hold the same values while retaining the required membership restrictions, or do not grant the derived field".to_owned() + }, source = source.id, - source_rows = describe_row_boundaries(&grant.row_boundaries), - request_rows = describe_row_boundaries(&request.row_boundaries), + source_rows = describe_row_boundaries(grant), + request_rows = describe_row_boundaries(request), rewrite = rewrite, ), )); @@ -828,11 +839,12 @@ fn derived_source_refusal( None } -fn describe_row_boundaries(boundaries: &[RowBoundarySource]) -> String { - if boundaries.is_empty() { +fn describe_row_boundaries(grant: &crate::contract::AccessProfileSource) -> String { + if grant.row_boundaries.is_empty() && grant.membership_boundaries.is_empty() { return "`unrestricted`".to_owned(); } - boundaries + grant + .row_boundaries .iter() .map(|boundary| { let operator = match boundary.operator { @@ -841,6 +853,13 @@ fn describe_row_boundaries(boundaries: &[RowBoundarySource]) -> String { }; format!("`{}` {operator} claim `{}`", boundary.field, boundary.claim) }) + .chain(grant.membership_boundaries.iter().map(|boundary| { + format!( + "`{}` requires membership through `{}`", + boundary.field(), + boundary.record_type() + ) + })) .collect::>() .join(" and ") } diff --git a/crates/registry-breg/src/compiler/review_context.rs b/crates/registry-breg/src/compiler/review_context.rs index 384238cfaa..9bf4565db7 100644 --- a/crates/registry-breg/src/compiler/review_context.rs +++ b/crates/registry-breg/src/compiler/review_context.rs @@ -51,6 +51,27 @@ pub fn compile_schema_from_parts( let mut bindings = Map::new(); for (name, projection) in &context.fields { let (schema, classification, binding) = match projection { + ProposalContextValueSource::AdditionalForm { form } => { + let declared = proposal.additional_forms.get(form).ok_or_else(&invalid)?; + let contract = + crate::artifacts::additional_form_contract(&action.id, form, &declared.inputs); + let classification = declared + .inputs + .iter() + .map(|input| input.classification) + .max() + .ok_or_else(&invalid)?; + ( + json!({"type":"array","maxItems":32,"items":{ + "type":"object","additionalProperties":false, + "required":["id","addedAt","input"], + "properties":{"id":{"type":"string","format":"uuid"},"addedAt":{"type":"string","format":"date-time"}, + "input":contract["schema"]} + }}), + classification, + json!({"kind":"additional-form","form":form,"contractDigest":contract["digest"]}), + ) + } ProposalContextValueSource::Additions { slot } => { let declared = proposal .additions diff --git a/crates/registry-breg/src/compiler/statistics.rs b/crates/registry-breg/src/compiler/statistics.rs index c885ffb1e3..dcf83862a5 100644 --- a/crates/registry-breg/src/compiler/statistics.rs +++ b/crates/registry-breg/src/compiler/statistics.rs @@ -1596,17 +1596,16 @@ fn validate_publisher_independence( ), )); } - let violation = if !grant.row_boundaries.is_empty() { - Some("rowBoundaries") - } else if !grant.membership_boundaries.is_empty() { - Some("membershipBoundaries") - } else if !grant.required_purposes.is_empty() { - Some("requiredPurposes") - } else if !grant.require_consent.is_empty() { - Some("requireConsent") - } else { - None - }; + let violation = + if !grant.row_boundaries.is_empty() || !grant.membership_boundaries.is_empty() { + Some("rowBoundaries") + } else if !grant.required_purposes.is_empty() { + Some("requiredPurposes") + } else if !grant.require_consent.is_empty() { + Some("requireConsent") + } else { + None + }; if let Some(member) = violation { errors.push(error( &holder.independence_code("caller-dependent"), diff --git a/crates/registry-breg/src/contract.rs b/crates/registry-breg/src/contract.rs index 9cef24b166..5a465d998b 100644 --- a/crates/registry-breg/src/contract.rs +++ b/crates/registry-breg/src/contract.rs @@ -633,8 +633,28 @@ pub struct ProposalPolicySource { pub attachments: Vec, #[serde(default, skip_serializing_if = "Option::is_none")] pub additions: Option, + /// Typed information a reviewed Proposal can declare separately from its Action inputs. + #[serde( + default, + deserialize_with = "local_id_map", + skip_serializing_if = "BTreeMap::is_empty" + )] + #[cfg_attr( + feature = "schema", + schemars( + schema_with = "local_id_map_schema::", + extend("maxProperties" = MAXIMUM_ADDITIONAL_FORMS) + ) + )] + pub additional_forms: BTreeMap, #[serde(default)] pub review_context: Option, + /// The person the Proposal is about, frozen at its first Submit. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub subject: Option, + /// One message thread between the party and the office. Presence opens it. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub messages: Option, /// Post-commit observers of the fixed, value-free Proposal lifecycle event. #[serde( default, @@ -644,6 +664,56 @@ pub struct ProposalPolicySource { pub hooks: Vec, } +pub(crate) const MAXIMUM_ADDITIONAL_FORMS: usize = 8; +pub(crate) const MAXIMUM_ADDITIONAL_FORM_INPUTS: usize = 16; +#[cfg(feature = "schema")] +const UNSUPPORTED_ADDITIONAL_FORM_TYPES: [&str; 5] = [ + "reference", + "crs84-point", + "crs84-polygon", + "structured", + "vocabulary-code", +]; + +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields, rename_all = "camelCase")] +pub struct AdditionalFormSource { + #[serde(default = "default_additional_form_count")] + #[cfg_attr(feature = "schema", schemars(range(min = 1, max = 32)))] + pub maximum_count: u8, + #[cfg_attr( + feature = "schema", + schemars(schema_with = "additional_form_inputs_schema") + )] + pub inputs: Vec, +} + +fn default_additional_form_count() -> u8 { + 8 +} + +#[cfg(feature = "schema")] +fn additional_form_inputs_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema { + schemars::json_schema!({ + "type": "array", + "minItems": 1, + "maxItems": MAXIMUM_ADDITIONAL_FORM_INPUTS, + "items": { + "unevaluatedProperties": false, + "allOf": [ + generator.subschema_for::(), + { + "type": "object", + "required": ["type"], + "properties": {"type": {"not": {"enum": UNSUPPORTED_ADDITIONAL_FORM_TYPES}}}, + "not": {"required": ["pattern"]} + } + ] + } + }) +} + #[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] #[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] #[serde(deny_unknown_fields, rename_all = "camelCase")] @@ -673,6 +743,7 @@ pub enum ProposalEventTransition { Asked, Answered, Added, + Messaged, Started, Edited, Submitted, @@ -691,6 +762,7 @@ impl ProposalEventTransition { Self::Asked => "asked", Self::Answered => "answered", Self::Added => "added", + Self::Messaged => "messaged", Self::Started => "started", Self::Edited => "edited", Self::Submitted => "submitted", @@ -801,6 +873,11 @@ pub struct ProposalReviewContextSource { )] #[cfg_attr(feature = "schema", schemars(!remote, tag = "type"))] pub enum ProposalContextValueSource { + AdditionalForm { + #[serde(deserialize_with = "local_id")] + #[cfg_attr(feature = "schema", schemars(with = "LocalId"))] + form: String, + }, Additions { #[serde(deserialize_with = "local_id")] #[cfg_attr(feature = "schema", schemars(with = "LocalId"))] @@ -853,6 +930,7 @@ pub enum ProposalOperation { GetReviewContext, GetTaskGrantContext, GetApplicationActor, + Message, } impl ProposalOperation { pub const fn as_str(self) -> &'static str { @@ -872,14 +950,55 @@ impl ProposalOperation { Self::GetReviewContext => "get-review-context", Self::GetTaskGrantContext => "get-task-grant-context", Self::GetApplicationActor => "get-application-actor", + Self::Message => "message", } } } #[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] #[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "kebab-case")] -pub enum ProposalOwnership { - Caller, +pub enum ProposalParty { + /// The caller who filed the Proposal. + Owner, + /// The person the Proposal is about, frozen at its first Submit. + Subject, +} +/// Whom a Submit may name as the Proposal's subject. Absent means only the +/// submitter themselves. +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "kebab-case")] +pub enum ProposalSubmitsFor { + Anyone, +} +/// Where a Proposal's subject comes from: an Action input, or a field of the +/// Record a reference input names. +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields, rename_all = "camelCase")] +pub struct ProposalSubjectSource { + pub input: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub field: Option, +} +/// The message thread on each Proposal of an Action. It needs no review. +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields, rename_all = "camelCase")] +pub struct ProposalMessagesSource { + /// The most messages each side, the party and the office, writes on one + /// Proposal's thread. + #[serde(default = "default_proposal_message_count")] + #[cfg_attr( + feature = "schema", + schemars(with = "BoundedU32<1, { MAX_PROPOSAL_MESSAGE_COUNT }>") + )] + pub maximum_count: u32, +} +/// The most messages an Action may allow each side on one Proposal. +pub const MAX_PROPOSAL_MESSAGE_COUNT: u32 = 1000; +fn default_proposal_message_count() -> u32 { + 200 } #[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] #[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] @@ -891,8 +1010,12 @@ pub struct ProposalPermissionSource { #[serde(default, skip_serializing_if = "is_false")] pub readable_review_progress: bool, pub operations: UniqueSet, - #[serde(default)] - pub ownership: Option, + /// Binds the grant to one party of each Proposal. Absent grants are not + /// bound to a party, as a reviewer's or officer's are. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub party: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub submits_for: Option, #[serde(default)] pub targets: Vec, #[serde(default)] @@ -903,26 +1026,33 @@ pub struct ProposalPermissionSource { pub readable_attachments: UniqueSet, #[serde(default)] pub writable_attachments: UniqueSet, + #[serde(default, skip_serializing_if = "UniqueSet::is_empty")] + pub readable_forms: UniqueSet, + #[serde(default, skip_serializing_if = "UniqueSet::is_empty")] + pub writable_forms: UniqueSet, /// Action inputs this grant may set. Absent leaves every declared input writable. #[serde(default, skip_serializing_if = "Option::is_none")] pub writable_inputs: Option>, } #[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[cfg_attr( + feature = "schema", + schemars(with = "sentinel::AuthoredTargetPermission") +)] #[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] -#[serde(deny_unknown_fields, rename_all = "camelCase")] +#[serde( + try_from = "sentinel::AuthoredTargetPermission", + into = "sentinel::AuthoredTargetPermission" +)] pub struct ProposalTargetPermissionSource { pub record_type: String, - #[serde( - deserialize_with = "sentinel::row_boundaries", - serialize_with = "sentinel::serialize_row_boundaries" - )] - #[cfg_attr(feature = "schema", schemars(with = "sentinel::RowBoundaries"))] pub row_boundaries: Vec, + pub membership_row_boundaries: Vec, } /// A reusable list of row boundaries, written under `rowBoundarySets`. #[derive(Clone, Debug, Eq, PartialEq)] -pub struct RowBoundarySetSource(pub Vec); +pub struct RowBoundarySetSource(Vec); impl<'de> Deserialize<'de> for RowBoundarySetSource { fn deserialize>(deserializer: D) -> Result { @@ -941,7 +1071,7 @@ impl schemars::JsonSchema for RowBoundarySetSource { } fn json_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema { - generator.subschema_for::, sentinel::RowBoundarySetRows>>() + generator.subschema_for::, sentinel::RowBoundarySetRows>>() } } @@ -2117,6 +2247,8 @@ pub struct EntitySource { /// Write-once file slots filled by immediate Action create effects. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub attachments: Vec, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub membership: Option, /// Mandatory request-access requirements checked against every profile, including module contributions. #[serde( default, @@ -5462,7 +5594,7 @@ pub struct AccessProfileSource { pub sortable_fields: UniqueSet, #[serde(default, skip_serializing_if = "Option::is_none")] pub spatial_queries: Option, - /// Compiled row reach; an empty array permits every row, as the authored `unrestricted` does. + /// Compiled claim boundaries. An empty array imposes no claim restriction. pub row_boundaries: Vec, /// Current active membership required for each stored reference key. #[serde(default, skip_serializing_if = "Vec::is_empty")] @@ -5515,6 +5647,10 @@ pub enum Operation { /// for the entity and profile. It declares no item route and no raw batch /// route, and change control does not count it as a direct write. Import, + /// Let the profile's direct writes name records of this Record type, and + /// nothing else. A write naming a record reads it under this grant's row + /// reach; the grant serves no route and reads no field. + Reference, } #[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] @@ -5551,13 +5687,69 @@ pub struct RowBoundarySource { pub operator: BoundaryOperator, } -/// A one-hop current membership requirement, combined with every other row boundary. -/// The root field and membership key must reference the same entity. The active -/// field is Boolean, and principalField matches the profile's verified principal. +/// Stored fields that establish a current membership fact. #[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] #[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] #[serde(deny_unknown_fields, rename_all = "camelCase")] -pub struct MembershipBoundarySource { +pub struct MembershipDeclarationSource { + #[serde(deserialize_with = "local_id")] + #[cfg_attr(feature = "schema", schemars(with = "LocalId"))] + pub key: String, + #[serde(deserialize_with = "local_id")] + #[cfg_attr(feature = "schema", schemars(with = "LocalId"))] + pub principal: String, + #[serde(deserialize_with = "local_id")] + #[cfg_attr(feature = "schema", schemars(with = "LocalId"))] + pub active: String, +} + +/// A membership check on one field of the protected Record type. +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields, rename_all = "camelCase")] +pub struct MembershipRowBoundarySource { + #[serde(deserialize_with = "local_id")] + #[cfg_attr(feature = "schema", schemars(with = "LocalId"))] + pub field: String, + #[serde(deserialize_with = "local_id")] + #[cfg_attr(feature = "schema", schemars(with = "LocalId"))] + pub membership: String, +} + +/// Membership entries in the normalized profile, before and after expansion. +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[cfg_attr( + feature = "schema", + schemars(with = "ExpandedMembershipBoundarySource") +)] +#[derive(Clone, Debug, Eq, PartialEq)] +pub enum MembershipBoundarySource { + Expanded(ExpandedMembershipBoundarySource), + Declared(MembershipRowBoundarySource), +} + +impl Serialize for MembershipBoundarySource { + fn serialize(&self, serializer: S) -> Result { + match self { + Self::Expanded(boundary) => boundary.serialize(serializer), + Self::Declared(_) => Err(serde::ser::Error::custom( + "a compiled access profile requires expanded membership entries", + )), + } + } +} + +impl<'de> Deserialize<'de> for MembershipBoundarySource { + fn deserialize>(deserializer: D) -> Result { + ExpandedMembershipBoundarySource::deserialize(deserializer).map(Self::Expanded) + } +} + +/// Logical membership fields carried in the compiled profile and inventory. +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields, rename_all = "camelCase")] +pub struct ExpandedMembershipBoundarySource { pub field: String, #[serde(rename = "membershipRecordType")] pub membership_entity: String, @@ -5566,6 +5758,32 @@ pub struct MembershipBoundarySource { pub active_field: String, } +impl MembershipBoundarySource { + pub(crate) fn record_type(&self) -> &str { + match self { + Self::Expanded(boundary) => &boundary.membership_entity, + Self::Declared(boundary) => &boundary.membership, + } + } + + pub(crate) fn field(&self) -> &str { + match self { + Self::Expanded(boundary) => &boundary.field, + Self::Declared(boundary) => &boundary.field, + } + } + + pub(crate) fn entry(&self) -> MembershipRowBoundarySource { + match self { + Self::Expanded(boundary) => MembershipRowBoundarySource { + field: boundary.field.clone(), + membership: boundary.membership_entity.clone(), + }, + Self::Declared(boundary) => boundary.clone(), + } + } +} + /// Compile-time requirements, not grants. Profiles must explicitly satisfy them. /// /// This is the form the compiler holds and compiled artifacts carry, where an @@ -6031,12 +6249,9 @@ pub struct EntityPermissionSource { pub sortable_fields: UniqueSet, #[serde(skip_serializing_if = "Option::is_none")] pub spatial_queries: Option, - /// Row reach, written as `unrestricted` when it holds no boundary. - #[serde(serialize_with = "sentinel::serialize_row_boundaries")] + /// Row reach, written as unrestricted when both lists are empty. pub row_boundaries: Vec, - /// Current active membership required for each stored reference key. - #[serde(skip_serializing_if = "Vec::is_empty")] - pub membership_boundaries: Vec, + pub membership_row_boundaries: Vec, /// Current subject-issued consent required for each row, ANDed. #[serde(skip_serializing_if = "Vec::is_empty")] pub require_consent: Vec, @@ -6126,18 +6341,19 @@ pub struct ReadPathPermissionSource> { } #[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[cfg_attr( + feature = "schema", + schemars(with = "sentinel::AuthoredTargetPermission") +)] #[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] -#[serde(deny_unknown_fields, rename_all = "camelCase")] +#[serde( + try_from = "sentinel::AuthoredTargetPermission", + into = "sentinel::AuthoredTargetPermission" +)] pub struct ActionTargetPermissionSource { - #[serde(rename = "recordType")] pub entity: String, - /// Row reach: `unrestricted`, or a list of at least one row boundary. - #[serde( - deserialize_with = "sentinel::row_boundaries", - serialize_with = "sentinel::serialize_row_boundaries" - )] - #[cfg_attr(feature = "schema", schemars(with = "sentinel::RowBoundaries"))] pub row_boundaries: Vec, + pub membership_row_boundaries: Vec, } #[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] @@ -6227,7 +6443,7 @@ const HANDLER_TYPE_REPLACEMENT: &str = const CHANGE_REQUEST_REPLACEMENT: &str = "Declare one Action with `execution.mode: proposal` and its `execution.proposal` review, application and retention policy. Proposal state is owned by the Action, not a Record type. See https://docs.registrystack.org/configure/breg-proposals/."; const CHANGE_CONTROL_REPLACEMENT: &str = "Replace `changeControl.requiredFor` with `mutationPolicy`, setting each governed operation (`create`, `patch`, or `tombstone`) to `proposal-required`. Declare Actions with `execution.mode: proposal` for those writes; keep their review and application policy under `execution.proposal`. See https://docs.registrystack.org/configure/breg-proposals/."; -const REQUEST_VISIBILITY_REPLACEMENT: &str = "Move Proposal authority into the profile's `permissions.proposals` entry for the Action. Use `ownership: caller` for owner-only access, and explicitly retain the required `operations` and target `rowBoundaries`. See https://docs.registrystack.org/configure/breg-proposals/."; +const REQUEST_VISIBILITY_REPLACEMENT: &str = "Move Proposal authority into the profile's `permissions.proposals` entry for the Action. Use `party: owner` for owner-only access, and explicitly retain the required `operations` and target `rowBoundaries`. See https://docs.registrystack.org/configure/breg-proposals/."; const READABLE_REQUEST_FIELDS_REPLACEMENT: &str = "Declare the profile's `permissions.proposals` entry for the Action with explicit `readableInputs`, `readableAttachments`, and `readableContextFields` for the disclosure it needs. Review status uses the separate `get-review-status` operation; do not widen Record or Proposal grants. See https://docs.registrystack.org/configure/breg-proposals/."; const EQUALS_INPUT_REPLACEMENT: &str = "Rename `equalsInput` to `equalsFromInput`, keeping the same input reference."; @@ -6248,9 +6464,17 @@ const RETIRED_ACTION_PLAN_KEYS: [RemovedKey<'static>; 2] = [ /// Members `registry.yaml` no longer accepts, each with the member that /// replaced it. +const MEMBERSHIP_BOUNDARIES_REPLACEMENT: &str = "Declare membership: {key, principal, active} on the membership Record type and write each boundary as a rowBoundaries entry {field, membership}."; + +const RETIRED_PROPOSAL_OWNERSHIP: RemovedKey<'static> = RemovedKey { + pointer: "/accessProfiles/*/permissions/proposals/*/ownership", + replacement: "Replace `ownership: caller` with `party: owner`. See https://docs.registrystack.org/configure/breg-proposals/.", +}; + const PROJECT_REMOVED_KEYS: &[RemovedKey<'static>] = &[ RETIRED_ACTION_PLAN_KEYS[0], RETIRED_ACTION_PLAN_KEYS[1], + RETIRED_PROPOSAL_OWNERSHIP, RemovedKey { pointer: "/datasets/*/id", replacement: "Write datasets as a mapping from each id to the rest of its entry, datasets: {DATASET_ID: {display: ...}}, with no id member.", @@ -6352,12 +6576,12 @@ const PROJECT_REMOVED_KEYS: &[RemovedKey<'static>] = &[ replacement: FROM_FIELD_REPLACEMENT, }, RemovedKey { - pointer: "/recordTypes/*/accessProfiles/*/membershipBoundaries/*/membershipEntity", - replacement: "Rename `membershipEntity` to `membershipRecordType`.", + pointer: "/recordTypes/*/accessProfiles/*/membershipBoundaries", + replacement: MEMBERSHIP_BOUNDARIES_REPLACEMENT, }, RemovedKey { - pointer: "/accessProfiles/*/permissions/records/*/membershipBoundaries/*/membershipEntity", - replacement: "Rename `membershipEntity` to `membershipRecordType`.", + pointer: "/accessProfiles/*/permissions/records/*/membershipBoundaries", + replacement: MEMBERSHIP_BOUNDARIES_REPLACEMENT, }, RemovedKey { pointer: "/entities", @@ -6558,12 +6782,12 @@ const MODULE_REMOVED_KEYS: &[RemovedKey<'static>] = &[ replacement: FROM_FIELD_REPLACEMENT, }, RemovedKey { - pointer: "/recordTypes/*/accessProfiles/*/membershipBoundaries/*/membershipEntity", - replacement: "Rename `membershipEntity` to `membershipRecordType`.", + pointer: "/recordTypes/*/accessProfiles/*/membershipBoundaries", + replacement: MEMBERSHIP_BOUNDARIES_REPLACEMENT, }, RemovedKey { - pointer: "/extendRecordTypes/*/accessProfiles/*/membershipBoundaries/*/membershipEntity", - replacement: "Rename `membershipEntity` to `membershipRecordType`.", + pointer: "/extendRecordTypes/*/accessProfiles/*/membershipBoundaries", + replacement: MEMBERSHIP_BOUNDARIES_REPLACEMENT, }, RemovedKey { pointer: "/recordTypes/*/hooks/*/handler/kind", @@ -6684,11 +6908,11 @@ pub const MODULE_FORMAT: FormatSpec<'static> = FormatSpec { removed_keys: MODULE_REMOVED_KEYS, }; -// Replaying a verified package can see the Action Plan keys its sealed source -// predates. Other retired keys are still checked by the shared reader. +// Verified predecessors may carry historical Action Plan and Proposal grant +// spellings. Other retired keys are still checked by the shared reader. const SEALED_PROJECT_FORMAT: FormatSpec<'static> = FormatSpec { removed_keys: PROJECT_REMOVED_KEYS - .split_at(RETIRED_ACTION_PLAN_KEYS.len()) + .split_at(RETIRED_ACTION_PLAN_KEYS.len() + 1) .1, ..PROJECT_FORMAT }; @@ -6704,20 +6928,22 @@ const SEALED_MODULE_FORMAT: FormatSpec<'static> = FormatSpec { /// column, and the action that fixes it (CFG-DIAG-1), and none repeats a /// value from the file. pub fn read_project_yaml(file: &str, bytes: &[u8]) -> Result, Report> { - read_project(file, bytes, false).map(|(decoded, _)| decoded) + read_project(file, bytes, false, None).map(|(decoded, _)| decoded) } fn read_project( file: &str, bytes: &[u8], sealed: bool, + predecessor_memberships: Option<&mut PredecessorMemberships>, ) -> Result<(Decoded, bool), Report> { let format = if sealed { &SEALED_PROJECT_FORMAT } else { &PROJECT_FORMAT }; - let (mut decoded, translated) = read_with_value_types(file, bytes, format, sealed)?; + let (mut decoded, translated) = + read_with_value_types(file, bytes, format, sealed, predecessor_memberships)?; let errors = crate::authoring_integrity::project_diagnostics(&mut decoded); if errors.is_empty() { Ok((decoded, translated)) @@ -6733,7 +6959,7 @@ fn normalize_sealed_action_plans(value: &mut Value, document: &Document) -> Resu return Ok(false); }; let mut current = root.contains_key("actionPlans"); - let mut translated = rename_sealed_plan_key(root, "functions", "actionPlans", "", document)?; + let mut translated = rename_sealed_key(root, "functions", "actionPlans", "", document)?; if let Some(actions) = root.get_mut("actions").and_then(Value::as_object_mut) { for (id, action) in actions { let Some(plan) = action.get_mut("plan").and_then(Value::as_object_mut) else { @@ -6761,7 +6987,7 @@ fn normalize_sealed_action_plans(value: &mut Value, document: &Document) -> Resu } current |= current_plan; if (legacy_plan || duplicate_reference) - && rename_sealed_plan_key(plan, "function", "actionPlan", &pointer, document)? + && rename_sealed_key(plan, "function", "actionPlan", &pointer, document)? { plan.insert("type".to_owned(), Value::String("scripted".to_owned())); translated = true; @@ -6771,7 +6997,44 @@ fn normalize_sealed_action_plans(value: &mut Value, document: &Document) -> Resu Ok(translated) } -fn rename_sealed_plan_key( +fn normalize_sealed_proposal_parties( + value: &mut Value, + document: &Document, +) -> Result { + let mut translated = false; + for (profile_path, profile) in entries_mut(value, "accessProfiles", "") { + let Some(permissions) = profile.get_mut("permissions") else { + continue; + }; + let permissions_path = format!("{profile_path}/permissions"); + for (path, entry) in entries_mut(permissions, "proposals", &permissions_path) { + let Some(grant) = entry.as_object_mut() else { + continue; + }; + if rename_sealed_key(grant, "ownership", "party", &path, document)? { + match &grant["party"] { + Value::Null => {} + Value::String(party) if party == "caller" => { + grant.insert("party".to_owned(), Value::String("owner".to_owned())); + } + _ => { + return Err(document.report_with([document.diagnostic_at_value( + Severity::Error, + "config.invalid-value", + &format!("{path}/ownership"), + "A historical Proposal ownership grant must be caller or null.", + "Use a package sealed by the previous release.", + )])); + } + } + translated = true; + } + } + } + Ok(translated) +} + +fn rename_sealed_key( members: &mut serde_json::Map, old: &str, current: &str, @@ -6794,18 +7057,258 @@ fn rename_sealed_plan_key( Ok(true) } +#[derive(Debug, Default)] +pub(crate) struct PredecessorMemberships { + // Keep the full historical tuples for rehearsal and for reconstructing + // module locks. Different grants could name different fields on one source. + pub historical: BTreeMap>, + pub current_site: Option, +} + +fn current_membership_site(value: &mut Value) -> Option { + let has_membership = |rows: Option<&Value>| { + rows.and_then(Value::as_array) + .is_some_and(|rows| rows.iter().any(|entry| entry.get("membership").is_some())) + }; + for (path, rows) in entries_mut(value, "rowBoundarySets", "") { + if has_membership(Some(rows)) { + return Some(path); + } + } + for (profile_path, profile) in entries_mut(value, "accessProfiles", "") { + let Some(permissions) = profile.get_mut("permissions") else { + continue; + }; + let permissions_path = format!("{profile_path}/permissions"); + for (path, grant) in entries_mut(permissions, "records", &permissions_path) { + if has_membership(grant.get("rowBoundaries")) { + return Some(format!("{path}/rowBoundaries")); + } + } + for surface in ["actions", "proposals"] { + for (grant_path, grant) in entries_mut(permissions, surface, &permissions_path) { + for (path, target) in entries_mut(grant, "targets", &grant_path) { + if has_membership(target.get("rowBoundaries")) { + return Some(format!("{path}/rowBoundaries")); + } + } + } + } + } + for collection in ["recordTypes", "extendRecordTypes"] { + for (path, record_type) in entries_mut(value, collection, "") { + if record_type.get("membership").is_some() { + return Some(format!("{path}/membership")); + } + for (path, grant) in entries_mut(record_type, "accessProfiles", &path) { + if has_membership(grant.get("rowBoundaries")) { + return Some(format!("{path}/rowBoundaries")); + } + } + } + } + None +} + +fn normalize_predecessor_memberships( + value: &mut Value, + document: &Document, + memberships: &mut PredecessorMemberships, +) -> Result<(), Report> { + memberships.current_site = current_membership_site(value); + for (profile_path, profile) in entries_mut(value, "accessProfiles", "") { + let Some(permissions) = profile.get_mut("permissions") else { + continue; + }; + for (path, grant) in entries_mut( + permissions, + "records", + &format!("{profile_path}/permissions"), + ) { + normalize_predecessor_membership_grant(grant, &path, document, memberships)?; + } + } + for collection in ["recordTypes", "extendRecordTypes"] { + for (path, record_type) in entries_mut(value, collection, "") { + for (path, grant) in entries_mut(record_type, "accessProfiles", &path) { + normalize_predecessor_membership_grant(grant, &path, document, memberships)?; + } + } + } + if let Some(site) = memberships + .current_site + .as_deref() + .filter(|_| !memberships.historical.is_empty()) + { + return Err(document.report_with([document.diagnostic_at_value( + Severity::Error, + "breg.membership.mixed-spelling", + site, + "The sealed source mixes historical and current membership declarations.", + "Use the original sources sealed by one release.", + )])); + } + Ok(()) +} + +fn normalize_predecessor_membership_grant( + grant: &mut Value, + path: &str, + document: &Document, + memberships: &mut PredecessorMemberships, +) -> Result<(), Report> { + let Some(grant) = grant.as_object_mut() else { + return Ok(()); + }; + if !grant.contains_key("membershipBoundaries") { + return Ok(()); + } + let site = format!("{path}/membershipBoundaries"); + let refuse = |code, site, message| { + document.report_with([document.diagnostic_at_value( + Severity::Error, + code, + site, + message, + "Use the original sources sealed by the previous release.", + )]) + }; + let boundaries: Vec = document.decode_at(&site)?; + if boundaries.len() > 8 { + return Err(refuse( + "breg.access.membership-limit", + &site, + "Declare at most eight membership boundaries.", + )); + } + for (index, boundary) in boundaries.iter().enumerate() { + let entry_site = format!("{site}/{index}"); + if boundaries[..index].contains(boundary) { + return Err(refuse( + "breg.access.membership-duplicate", + &entry_site, + "Each membership boundary must be unique.", + )); + } + for field in ["membershipKeyField", "principalField", "activeField"] { + document.decode_at::(&format!("{entry_site}/{field}"))?; + } + if boundary.field == crate::membership::CANONICAL_ID { + return Err(refuse( + "breg.access.membership-key-type", + &format!("{entry_site}/field"), + "A historical membership boundary requires a stored reference field.", + )); + } + } + if !boundaries.is_empty() { + let operations: UniqueSet = document.decode_at(&format!("{path}/operations"))?; + if operations.iter().any(|operation| { + !matches!( + operation, + Operation::Get + | Operation::Lookup + | Operation::List + | Operation::Revisions + | Operation::Snapshot + ) + }) || grant + .get("writableFields") + .and_then(Value::as_array) + .is_some_and(|fields| !fields.is_empty()) + { + return Err(refuse( + "breg.access.membership-read-only", + &site, + "Historical membership boundaries grant reads only.", + )); + } + if grant + .get("spatialQueries") + .is_some_and(|queries| !queries.is_null()) + { + return Err(refuse( + "breg.access.membership-spatial-unsupported", + &site, + "Historical membership boundaries do not grant spatial queries.", + )); + } + } + let row_site = format!("{path}/rowBoundaries"); + let Some(rows) = grant.get_mut("rowBoundaries") else { + return Err(refuse( + "config.missing-key", + path, + "The historical grant requires rowBoundaries.", + )); + }; + if rows.as_array().is_some_and(|entries| { + entries + .iter() + .any(|entry| entry.get("membership").is_some()) + }) { + return Err(refuse( + "breg.membership.mixed-spelling", + &site, + "The sealed grant declares both historical and current membership boundaries.", + )); + } + if !boundaries.is_empty() { + if rows.as_str() == Some("unrestricted") { + *rows = Value::Array(Vec::new()); + } else if rows.as_array().is_none_or(Vec::is_empty) { + return Err(refuse("config.invalid-value", &row_site, "Historical rowBoundaries must be unrestricted or a nonempty list of claim boundaries.")); + } + rows.as_array_mut() + .expect("historical row boundaries checked") + .extend(boundaries.iter().map(|boundary| { + serde_json::json!({ + "field": boundary.field, + "membership": boundary.membership_entity, + }) + })); + } + grant.remove("membershipBoundaries"); + memberships.historical.insert(site, boundaries); + Ok(()) +} + fn read_with_value_types( file: &str, bytes: &[u8], format: &FormatSpec<'_>, sealed: bool, + predecessor_memberships: Option<&mut PredecessorMemberships>, ) -> Result<(Decoded, bool), Report> { - let Decoded { - mut value, - document, - } = read_authored::(file, bytes, format)?; - let translated = if sealed { - normalize_sealed_action_plans(&mut value, &document)? + let ( + Decoded { + mut value, + document, + }, + removed_error, + ) = match read_authored::(file, bytes, format) { + Ok(decoded) => (decoded, None), + Err(report) + if report + .diagnostics() + .iter() + .all(|diagnostic| diagnostic.code == "config.removed-key") => + { + let without_removed = FormatSpec { + removed_keys: &[], + ..*format + }; + ( + read_authored::(file, bytes, &without_removed)?, + Some(report), + ) + } + Err(report) => return Err(report), + }; + let mut translated = if sealed { + let action_plans = normalize_sealed_action_plans(&mut value, &document)?; + let proposal_parties = normalize_sealed_proposal_parties(&mut value, &document)?; + action_plans || proposal_parties } else { // The key `type` is still valid. The removed-key table can only // refuse members, so report the retired tag at its value here. @@ -6829,13 +7332,15 @@ fn read_with_value_types( }) .collect(); if !diagnostics.is_empty() { - return Err(document.report_with(diagnostics)); + let removed = removed_error.into_iter().flat_map(Report::into_diagnostics); + return Err(document.report_with(removed.chain(diagnostics))); } false }; let option_errors = field_option_diagnostics(&document, &value); if !option_errors.is_empty() { - return Err(document.report_with(option_errors)); + let removed = removed_error.into_iter().flat_map(Report::into_diagnostics); + return Err(document.report_with(removed.chain(option_errors))); } let has_value_types = value.get("valueTypes").is_some(); let has_row_boundary_sets = value.get("rowBoundarySets").is_some(); @@ -6853,10 +7358,58 @@ fn read_with_value_types( "Declare the set under rowBoundarySets in this file and reference it by its identifier, with no other member.", )]) })?; - if !translated && !has_value_types && !resolved_sets && !has_row_boundary_sets { - return document - .decode() - .map(|value| (Decoded { value, document }, false)); + let removed_error = if let Some(memberships) = predecessor_memberships { + normalize_predecessor_memberships(&mut value, &document, memberships)?; + translated |= !memberships.historical.is_empty(); + let diagnostics: Vec<_> = removed_error + .into_iter() + .flat_map(Report::into_diagnostics) + .filter(|diagnostic| !memberships.historical.contains_key(&diagnostic.path)) + .collect(); + (!diagnostics.is_empty()).then(|| document.report_with(diagnostics)) + } else { + removed_error + }; + let mut requirement_errors = Vec::new(); + for collection in ["recordTypes", "extendRecordTypes"] { + for (pointer, entity) in entries_mut(&mut value, collection, "") { + let Some(rows) = entity + .pointer_mut("/accessRequirements/rowBoundaries") + .and_then(Value::as_array_mut) + else { + continue; + }; + for (index, row) in rows.iter_mut().enumerate() { + if serde_json::from_value::(row.clone()).is_ok() { + let base = format!("{pointer}/accessRequirements/rowBoundaries"); + let site = format!("{base}/{index}"); + requirement_errors.push(document.diagnostic_at_value( + Severity::Error, + "breg.access.membership-access-requirement-unsupported", + if document.span_of(&site).is_some() { + &site + } else { + &base + }, + "Record type accessRequirements.rowBoundaries accepts claim entries only.", + "Use a membership entry in rowBoundaries on a grant.", + )); + // Keep the item index while decoding the rest of the document. + // The requirement diagnostic prevents this placeholder from escaping. + *row = serde_json::json!({"field":"id","claim":"sub","operator":"equals"}); + } + } + } + } + if requirement_errors.is_empty() { + if let Some(report) = removed_error { + return Err(report); + } + if !translated && !has_value_types && !resolved_sets && !has_row_boundary_sets { + return document + .decode() + .map(|value| (Decoded { value, document }, false)); + } } // Every reference is expanded, so the read file holds the boundaries // inline and no set: it serializes to source that reads back the same. @@ -6877,13 +7430,14 @@ fn read_with_value_types( } let normalized = serde_json::to_vec(&value).expect("normalized authoring value serializes"); match read_authored::(file, &normalized, format) { - Ok(decoded) => Ok(( + Ok(decoded) if requirement_errors.is_empty() => Ok(( Decoded { value: decoded.value, document, }, translated, )), + Ok(_) => Err(document.report_with(requirement_errors)), Err(report) => { let diagnostics = report .into_diagnostics() @@ -6933,6 +7487,7 @@ fn read_with_value_types( .collect(); placed }) + .chain(requirement_errors) .collect(); Err(Report::new(diagnostics)) } @@ -7009,6 +7564,21 @@ fn field_option_diagnostics( ); } } + if collection == "actions" { + if let Some(forms) = item + .pointer("/execution/proposal/additionalForms") + .and_then(Value::as_object) + { + for (id, form) in forms { + if let Some(inputs) = form.get("inputs").and_then(Value::as_array) { + let id = registry_platform_yaml::escape_pointer_segment(id); + for (index, input) in inputs.iter().enumerate() { + check(input, format!("/actions/{item_key}/execution/proposal/additionalForms/{id}/inputs/{index}")); + } + } + } + } + } } } if let Some(types) = value.get("valueTypes").and_then(Value::as_object) { @@ -7025,20 +7595,22 @@ fn field_option_diagnostics( /// Read an authored module through the shared reader, as /// [`read_project_yaml`] reads a project. pub fn read_module_yaml(file: &str, bytes: &[u8]) -> Result, Report> { - read_module(file, bytes, false).map(|(decoded, _)| decoded) + read_module(file, bytes, false, None).map(|(decoded, _)| decoded) } fn read_module( file: &str, bytes: &[u8], sealed: bool, + predecessor_memberships: Option<&mut PredecessorMemberships>, ) -> Result<(Decoded, bool), Report> { let format = if sealed { &SEALED_MODULE_FORMAT } else { &MODULE_FORMAT }; - let (mut decoded, translated) = read_with_value_types(file, bytes, format, sealed)?; + let (mut decoded, translated) = + read_with_value_types(file, bytes, format, sealed, predecessor_memberships)?; let errors = crate::authoring_integrity::module_diagnostics(&mut decoded); if errors.is_empty() { Ok((decoded, translated)) @@ -7074,7 +7646,7 @@ pub fn parse_module_yaml(bytes: &[u8]) -> Result pub(crate) fn parse_sealed_project_yaml( bytes: &[u8], ) -> Result<(RegistryProject, bool), CompileFailure> { - read_project(PROJECT_FILE, bytes, true) + read_project(PROJECT_FILE, bytes, true, None) .map(|(decoded, translated)| (decoded.value, translated)) .map_err(|report| compile_failure_from_report("project", &report)) } @@ -7083,11 +7655,31 @@ pub(crate) fn parse_sealed_project_yaml( pub(crate) fn parse_sealed_module_yaml( bytes: &[u8], ) -> Result<(RegistryModule, bool), CompileFailure> { - read_module(MODULE_FILE, bytes, true) + read_module(MODULE_FILE, bytes, true, None) .map(|(decoded, translated)| (decoded.value, translated)) .map_err(|report| compile_failure_from_report("module", &report)) } +#[cfg(feature = "runtime")] +pub(crate) fn parse_predecessor_project_yaml( + bytes: &[u8], +) -> Result<(RegistryProject, PredecessorMemberships), CompileFailure> { + let mut memberships = PredecessorMemberships::default(); + read_project(PROJECT_FILE, bytes, true, Some(&mut memberships)) + .map(|(decoded, _)| (decoded.value, memberships)) + .map_err(|report| compile_failure_from_report("project", &report)) +} + +#[cfg(feature = "runtime")] +pub(crate) fn parse_predecessor_module_yaml( + bytes: &[u8], +) -> Result<(RegistryModule, PredecessorMemberships), CompileFailure> { + let mut memberships = PredecessorMemberships::default(); + read_module(MODULE_FILE, bytes, true, Some(&mut memberships)) + .map(|(decoded, _)| (decoded.value, memberships)) + .map_err(|report| compile_failure_from_report("module", &report)) +} + fn parse_json_value(bytes: &[u8], root: &str) -> Result { parse_json_strict(bytes).map_err(|error| { CompileFailure::from_one(Diagnostic::error( @@ -7478,19 +8070,22 @@ mod tests { use serde_json::json; #[test] - fn sealed_formats_skip_only_the_two_retired_action_plan_keys() { - for (authored, sealed) in [ - (&PROJECT_FORMAT, &SEALED_PROJECT_FORMAT), - (&MODULE_FORMAT, &SEALED_MODULE_FORMAT), + fn sealed_formats_skip_only_translated_retired_keys() { + for (authored, sealed, legacy_ownership) in [ + (&PROJECT_FORMAT, &SEALED_PROJECT_FORMAT, true), + (&MODULE_FORMAT, &SEALED_MODULE_FORMAT, false), ] { let expected = authored .removed_keys .iter() .map(|entry| entry.pointer) .filter(|pointer| { - !RETIRED_ACTION_PLAN_KEYS + let action_plan = RETIRED_ACTION_PLAN_KEYS .iter() - .any(|entry| entry.pointer == *pointer) + .any(|entry| entry.pointer == *pointer); + let proposal_ownership = + legacy_ownership && *pointer == RETIRED_PROPOSAL_OWNERSHIP.pointer; + !(action_plan || proposal_ownership) }) .collect::>(); let observed = sealed @@ -7499,7 +8094,36 @@ mod tests { .map(|entry| entry.pointer) .collect::>(); assert_eq!(observed, expected); - assert_eq!(authored.removed_keys.len() - observed.len(), 2); + assert_eq!( + authored.removed_keys.len() - observed.len(), + 2 + usize::from(legacy_ownership) + ); + } + } + + #[cfg(feature = "runtime")] + #[test] + fn only_a_sealed_project_translates_historical_proposal_ownership() { + let current = include_str!("../../../products/breg/examples/minimal/registry.yaml"); + let old = current.replace("party: owner", "ownership: caller"); + let parsed = parse_project_yaml(current.as_bytes()).unwrap(); + assert_eq!( + parse_sealed_project_yaml(old.as_bytes()).unwrap(), + (parsed, true) + ); + assert_eq!( + parse_project_yaml(old.as_bytes()) + .unwrap_err() + .diagnostics()[0] + .code, + "config.removed-key" + ); + for invalid in [ + "party: subject\n ownership: caller", + "ownership: owner", + ] { + let ambiguous = current.replace("party: owner", invalid); + assert!(parse_sealed_project_yaml(ambiguous.as_bytes()).is_err()); } } diff --git a/crates/registry-breg/src/contract/sentinel.rs b/crates/registry-breg/src/contract/sentinel.rs index df263029e3..ec6e8674c9 100644 --- a/crates/registry-breg/src/contract/sentinel.rs +++ b/crates/registry-breg/src/contract/sentinel.rs @@ -19,9 +19,10 @@ use registry_platform_yaml::{shape_union, Invalid, LocalId}; use serde::{de::IgnoredAny, Deserialize, Deserializer, Serialize, Serializer}; use super::{ - AccessProfileSource, AccessRequirementsSource, ActorKindSource, CompiledTaskGrantSource, - ConsentRequirementSource, EntityPermissionSource, LookupPermissionSource, - MembershipBoundarySource, Operation, PermissionsSource, ProvenanceFieldSource, + AccessProfileSource, AccessRequirementsSource, ActionTargetPermissionSource, ActorKindSource, + CompiledTaskGrantSource, ConsentRequirementSource, EntityPermissionSource, + LookupPermissionSource, MembershipBoundarySource, MembershipRowBoundarySource, Operation, + PermissionsSource, ProposalTargetPermissionSource, ProvenanceFieldSource, ReadPathPermissionSource, ReadableFields, RequiredFilterSource, RowBoundarySource, SpatialQueryPermissionSource, UniqueSet, }; @@ -55,6 +56,12 @@ impl Items for Vec { } } +impl Items for Vec { + fn holds_nothing(&self) -> bool { + self.is_empty() + } +} + impl Items for Vec { fn holds_nothing(&self) -> bool { self.is_empty() @@ -167,6 +174,86 @@ pub(super) enum RequiredScopes { shape_union!(RequiredScopes { scalar => Unrestricted, list => Listed }); +/// A row is bounded either by a direct claim or a membership Record type. +#[derive(Clone, Debug, Eq, PartialEq, Serialize)] +#[serde(untagged)] +pub(super) enum RowBoundaryEntry { + Claim(RowBoundarySource), + Membership(MembershipRowBoundarySource), +} + +#[cfg(feature = "schema")] +impl schemars::JsonSchema for RowBoundaryEntry { + fn schema_name() -> std::borrow::Cow<'static, str> { + "RowBoundaryEntry".into() + } + + fn json_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema { + let local_id = generator.subschema_for::(); + let operator = generator.subschema_for::(); + schemars::json_schema!({ + "type": "object", + "description": "A claim entry {field, claim, operator} or a membership entry {field, membership}.", + "additionalProperties": false, + "required": ["field"], + "properties": { + "field": {"type": "string"}, + "claim": {"type": "string"}, + "operator": operator, + "membership": local_id.clone() + }, + "if": {"required": ["membership"]}, + "then": {"properties": {"field": local_id, "claim": false, "operator": false}}, + "else": {"required": ["claim", "operator"]} + }) + } +} + +impl<'de> Deserialize<'de> for RowBoundaryEntry { + fn deserialize>(deserializer: D) -> Result { + #[derive(Deserialize)] + #[serde(deny_unknown_fields)] + struct Entry { + #[serde(default, deserialize_with = "present")] + field: Option, + #[serde(default, deserialize_with = "present")] + claim: Option, + #[serde(default, deserialize_with = "present")] + operator: Option, + #[serde(default, deserialize_with = "present")] + membership: Option, + } + fn present<'de, T: Deserialize<'de>, D: Deserializer<'de>>( + deserializer: D, + ) -> Result, D::Error> { + T::deserialize(deserializer).map(Some) + } + let entry = Entry::deserialize(deserializer)?; + match (entry.field, entry.claim, entry.operator, entry.membership) { + (Some(field), Some(claim), Some(operator), None) => { + Ok(Self::Claim(RowBoundarySource { + field, + claim, + operator, + })) + } + (Some(field), None, None, Some(membership)) => { + Ok(Self::Membership(MembershipRowBoundarySource { + field: LocalId::new(field) + .map_err(Invalid::into_error)? + .into_string(), + membership: membership.into_string(), + })) + } + _ => Err(Invalid::expected( + "a claim entry {field, claim, operator} or a membership entry {field, membership}", + "Write exactly one of the two rowBoundaries entry shapes.", + ) + .into_error()), + } + } +} + /// A reference to a named list of row boundaries the file declares under /// `rowBoundarySets`. The reader expands a reference into the set's boundaries /// before the typed model is decoded, so the compiler never holds one. @@ -186,9 +273,9 @@ pub(super) struct RowBoundarySetReference { pub(super) enum RowBoundaries { /// Reach every row. Unrestricted(Unrestricted), - /// Reach the rows every listed boundary binds to the caller's claims. - Listed(Listed, Rows>), - /// Reach the rows every boundary of a named set binds to the caller's claims. + /// Reach the rows bounded by every listed claim or membership entry. + Listed(Listed, Rows>), + /// Reach the rows bounded by every entry in a named set. // The reader expands the reference before decoding, so the typed model // only refuses it and never reads the identifier. Reference(#[allow(dead_code)] RowBoundarySetReference), @@ -222,40 +309,101 @@ pub(super) fn serialize_required_scopes( } } +type SplitRows = (Vec, Vec); + impl RowBoundaries { - /// The boundaries the compiler holds, where `unrestricted` is none. An - /// unexpanded reference is refused rather than read as none. - fn into_boundaries(self) -> Result, Invalid> { - match self { - Self::Unrestricted(_) => Ok(Vec::new()), - Self::Listed(Listed(boundaries, _)) => Ok(boundaries), - Self::Reference(_) => Err(Invalid::expected( - UNRESOLVED_REFERENCE, - UNRESOLVED_REFERENCE_ACTION, - )), + fn into_boundaries(self) -> Result { + let entries = match self { + Self::Unrestricted(_) => return Ok((Vec::new(), Vec::new())), + Self::Listed(Listed(entries, _)) => entries, + Self::Reference(_) => { + return Err(Invalid::expected( + UNRESOLVED_REFERENCE, + UNRESOLVED_REFERENCE_ACTION, + )) + } + }; + let mut claims = Vec::new(); + let mut memberships = Vec::new(); + for entry in entries { + match entry { + RowBoundaryEntry::Claim(claim) => claims.push(claim), + RowBoundaryEntry::Membership(membership) => memberships.push(membership), + } } + Ok((claims, memberships)) } -} -pub(super) fn row_boundaries<'de, D: Deserializer<'de>>( - deserializer: D, -) -> Result, D::Error> { - RowBoundaries::deserialize(deserializer)? - .into_boundaries() - .map_err(Invalid::into_error) + fn from_boundaries( + claims: Vec, + memberships: Vec, + ) -> Self { + if claims.is_empty() && memberships.is_empty() { + Self::Unrestricted(Unrestricted(PhantomData)) + } else { + Self::Listed(Listed( + claims + .into_iter() + .map(RowBoundaryEntry::Claim) + .chain(memberships.into_iter().map(RowBoundaryEntry::Membership)) + .collect(), + PhantomData, + )) + } + } } -pub(super) fn serialize_row_boundaries( - boundaries: &[RowBoundarySource], - serializer: S, -) -> Result { - if boundaries.is_empty() { - serializer.serialize_str(UNRESTRICTED) - } else { - boundaries.serialize(serializer) +impl Serialize for RowBoundaries { + fn serialize(&self, serializer: S) -> Result { + match self { + Self::Unrestricted(_) => serializer.serialize_str(UNRESTRICTED), + Self::Listed(Listed(entries, _)) => entries.serialize(serializer), + Self::Reference(_) => Err(serde::ser::Error::custom(UNRESOLVED_REFERENCE)), + } } } +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[derive(Deserialize, Serialize)] +#[serde(deny_unknown_fields, rename_all = "camelCase")] +pub(super) struct AuthoredTargetPermission { + record_type: String, + row_boundaries: RowBoundaries, +} + +macro_rules! target_permission { + ($source:ident, $record_type:ident) => { + impl TryFrom for $source { + type Error = Invalid; + + fn try_from(authored: AuthoredTargetPermission) -> Result { + let (row_boundaries, membership_row_boundaries) = + authored.row_boundaries.into_boundaries()?; + Ok(Self { + $record_type: authored.record_type, + row_boundaries, + membership_row_boundaries, + }) + } + } + + impl From<$source> for AuthoredTargetPermission { + fn from(source: $source) -> Self { + Self { + record_type: source.$record_type, + row_boundaries: RowBoundaries::from_boundaries( + source.row_boundaries, + source.membership_row_boundaries, + ), + } + } + } + }; +} + +target_permission!(ActionTargetPermissionSource, entity); +target_permission!(ProposalTargetPermissionSource, record_type); + /// Declares a member that only narrows: a list of at least one item, omitted /// when it narrows nothing. A scalar is refused with the same fix as an empty /// list, so an author who writes `unrestricted` here is told to omit the @@ -343,7 +491,7 @@ narrowing_member!( RowBoundarySetRows, RowBoundarySetRowsShapes, row_boundary_set_rows, - Vec, + Vec, "a list of at least one row boundary", "List the row boundaries the set holds. A set is a reusable list, so it is never empty and never unrestricted: write unrestricted on the grant that reaches every row." ); @@ -518,14 +666,7 @@ pub(super) struct AuthoredModuleProfile { #[serde(default, skip_serializing_if = "Option::is_none")] spatial_queries: Option, /// Row reach: `unrestricted`, or a list of at least one row boundary. - #[serde( - deserialize_with = "row_boundaries", - serialize_with = "serialize_row_boundaries" - )] - #[cfg_attr(feature = "schema", schemars(with = "RowBoundaries"))] - row_boundaries: Vec, - #[serde(default, skip_serializing_if = "Vec::is_empty")] - membership_boundaries: Vec, + row_boundaries: RowBoundaries, #[serde(default, skip_serializing_if = "Vec::is_empty")] require_consent: Vec, #[serde(default, skip_serializing_if = "Vec::is_empty")] @@ -550,10 +691,13 @@ pub(super) struct AuthoredModuleProfile { allow_data_export: bool, } -impl From for AccessProfileSource { - fn from(authored: AuthoredModuleProfile) -> Self { +impl TryFrom for AccessProfileSource { + type Error = Invalid; + + fn try_from(authored: AuthoredModuleProfile) -> Result { + let (row_boundaries, memberships) = authored.row_boundaries.into_boundaries()?; let (readable_fields, readable_fields_ceiling) = authored.readable_fields.into_parts(); - Self { + Ok(Self { id: authored.id, display: authored.display, default: authored.default, @@ -573,8 +717,11 @@ impl From for AccessProfileSource { required_filters: authored.required_filters, sortable_fields: authored.sortable_fields, spatial_queries: authored.spatial_queries, - row_boundaries: authored.row_boundaries, - membership_boundaries: authored.membership_boundaries, + row_boundaries, + membership_boundaries: memberships + .into_iter() + .map(MembershipBoundarySource::Declared) + .collect(), require_consent: authored.require_consent, lookups: authored.lookups, read_paths: authored.read_paths.into_iter().map(Into::into).collect(), @@ -582,7 +729,7 @@ impl From for AccessProfileSource { revision_access: authored.revision_access, provenance_fields: authored.provenance_fields, allow_data_export: authored.allow_data_export, - } + }) } } @@ -610,8 +757,20 @@ impl From for AuthoredModuleProfile { required_filters: profile.required_filters, sortable_fields: profile.sortable_fields, spatial_queries: profile.spatial_queries, - row_boundaries: profile.row_boundaries, - membership_boundaries: profile.membership_boundaries, + row_boundaries: RowBoundaries::from_boundaries( + profile.row_boundaries, + profile + .membership_boundaries + .into_iter() + .map(|entry| match entry { + MembershipBoundarySource::Declared(entry) => entry, + MembershipBoundarySource::Expanded(entry) => MembershipRowBoundarySource { + field: entry.field, + membership: entry.membership_entity, + }, + }) + .collect(), + ), require_consent: profile.require_consent, lookups: profile.lookups, read_paths: profile.read_paths.into_iter().map(Into::into).collect(), @@ -626,12 +785,10 @@ impl From for AuthoredModuleProfile { pub(super) fn module_access_profiles<'de, D: Deserializer<'de>>( deserializer: D, ) -> Result, D::Error> { - Ok( - registry_platform_yaml::id_keyed_by_local_id::(deserializer)? - .into_iter() - .map(AccessProfileSource::from) - .collect(), - ) + registry_platform_yaml::id_keyed_by_local_id::(deserializer)? + .into_iter() + .map(|profile| AccessProfileSource::try_from(profile).map_err(Invalid::into_error)) + .collect() } pub(super) fn serialize_module_access_profiles( @@ -732,10 +889,6 @@ pub(super) struct AuthoredEntityPermission { #[serde(serialize_with = "serialize_entity_rows")] #[cfg_attr(feature = "schema", schemars(with = "RowBoundaries"))] row_boundaries: Option, - /// Current active membership required for each stored reference key. - #[serde(default, skip_serializing_if = "Vec::is_empty")] - #[cfg_attr(feature = "schema", schemars(extend("default" = [])))] - membership_boundaries: Vec, /// Current subject-issued consent required for each row, ANDed. #[serde(default, skip_serializing_if = "Vec::is_empty")] #[cfg_attr(feature = "schema", schemars(extend("default" = [])))] @@ -788,6 +941,7 @@ impl TryFrom for EntityPermissionSource { )); }; let (readable_fields, readable_fields_ceiling) = authored.readable_fields.into_parts(); + let (row_boundaries, membership_row_boundaries) = row_boundaries.into_boundaries()?; Ok(Self { entity: authored.entity, operations: authored.operations, @@ -799,8 +953,8 @@ impl TryFrom for EntityPermissionSource { required_filters: authored.required_filters, sortable_fields: authored.sortable_fields, spatial_queries: authored.spatial_queries, - row_boundaries: row_boundaries.into_boundaries()?, - membership_boundaries: authored.membership_boundaries, + row_boundaries, + membership_row_boundaries, require_consent: authored.require_consent, lookups: authored.lookups, read_paths: authored.read_paths.into_iter().map(Into::into).collect(), @@ -814,11 +968,6 @@ impl TryFrom for EntityPermissionSource { impl From for AuthoredEntityPermission { fn from(source: EntityPermissionSource) -> Self { - let rows = if source.row_boundaries.is_empty() { - RowBoundaries::Unrestricted(Unrestricted(PhantomData)) - } else { - RowBoundaries::Listed(Listed(source.row_boundaries, PhantomData)) - }; Self { entity: source.entity, operations: source.operations, @@ -832,8 +981,10 @@ impl From for AuthoredEntityPermission { required_filters: source.required_filters, sortable_fields: source.sortable_fields, spatial_queries: source.spatial_queries, - row_boundaries: Some(rows), - membership_boundaries: source.membership_boundaries, + row_boundaries: Some(RowBoundaries::from_boundaries( + source.row_boundaries, + source.membership_row_boundaries, + )), require_consent: source.require_consent, lookups: source.lookups, read_paths: source.read_paths.into_iter().map(Into::into).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/disclosure.rs b/crates/registry-breg/src/disclosure.rs index 7d066edcf9..f6587bd523 100644 --- a/crates/registry-breg/src/disclosure.rs +++ b/crates/registry-breg/src/disclosure.rs @@ -82,6 +82,33 @@ impl DisclosurePlan<'_> { }) } + #[cfg(feature = "runtime")] + pub(crate) fn withholds_record_before_allocation( + &self, + state: &Map, + ) -> Result { + for condition in &self.conditions { + if matches!(condition.withhold, DisclosureWithhold::Record) + && condition.when.iter().all(|predicate| { + let field = match predicate { + DisclosureWhenPredicate::FieldEquals { field, .. } + | DisclosureWhenPredicate::FieldIn { field, .. } + | DisclosureWhenPredicate::FieldIsNull { field } + | DisclosureWhenPredicate::FieldIsNotNull { field } => field, + }; + self.entity + .fields + .get(field) + .is_none_or(|field| field.generate.is_none()) + }) + && when_matches(self.entity, &condition.when, state)? + { + return Ok(true); + } + } + Ok(false) + } + /// Whether a `record` or `history` condition matches `state`, so the /// record's revisions and snapshots behave as absent. pub fn withholds_history(&self, state: &Map) -> Result { diff --git a/crates/registry-breg/src/evidence_source/tests.rs b/crates/registry-breg/src/evidence_source/tests.rs index 7c9f0bf6ed..6214a239ed 100644 --- a/crates/registry-breg/src/evidence_source/tests.rs +++ b/crates/registry-breg/src/evidence_source/tests.rs @@ -427,11 +427,13 @@ fn membership_project() -> Value { {"id":"active","type":"boolean","classification":"internal"}, {"id":"other-active","type":"boolean","classification":"internal"}]})) ]); - source["accessProfiles"]["evidence-source"]["permissions"]["records"][0] - ["membershipBoundaries"] = json!([{ - "field":"organization","membershipRecordType":"membership","membershipKeyField":"organization", - "principalField":"principal","activeField":"active" - }]); + source["recordTypes"]["membership"]["membership"] = + json!({"key":"organization","principal":"principal","active":"active"}); + let grant = &mut source["accessProfiles"]["evidence-source"]["permissions"]["records"][0]; + grant["rowBoundaries"] + .as_array_mut() + .unwrap() + .push(json!({"field":"organization","membership":"membership"})); source } @@ -441,13 +443,12 @@ fn membership_behavior_reaches_helper_semantics_source_fields_and_select_authori let registry = compiled(&original, SQL); let before = export_evidence_source(®istry, &options()).unwrap(); for (name, value) in [ - ("principalField", "other-principal"), - ("activeField", "other-active"), - ("membershipKeyField", "other-organization"), + ("principal", "other-principal"), + ("active", "other-active"), + ("key", "other-organization"), ] { let mut changed = original.clone(); - changed["accessProfiles"]["evidence-source"]["permissions"]["records"][0] - ["membershipBoundaries"][0][name] = json!(value); + changed["recordTypes"]["membership"]["membership"][name] = json!(value); let after_registry = compiled(&changed, SQL); assert_eq!( select_policies(®istry, ®istry.entities()["record"], "evidence-source"), @@ -510,10 +511,7 @@ fn membership_behavior_reaches_helper_semantics_source_fields_and_select_authori fn reached_derived_source_consumes_its_membership_helper() { let mut original = membership_project(); let reader = &original["accessProfiles"]["evidence-source"]["permissions"]["records"][0]; - let (boundary, row_boundaries) = ( - reader["membershipBoundaries"].clone(), - reader["rowBoundaries"].clone(), - ); + let row_boundaries = reader["rowBoundaries"].clone(); original["recordTypes"].as_object_mut().unwrap().insert("flag".to_owned(), json!({"route":"flags","primaryDataset":"test-dataset","mutationMode":"mutable","fields":[ {"id":"code","type":"string","maximumLength":32,"classification":"internal"}, {"id":"organization","type":"reference","target":"organization","classification":"internal"}, @@ -522,15 +520,17 @@ fn reached_derived_source_consumes_its_membership_helper() { {"id":"enabled","type":"boolean","classification":"internal"}] })); original["accessProfiles"]["evidence-source"]["permissions"]["records"].as_array_mut().unwrap().push(json!({ - "recordType":"flag","operations":["get"],"readableFields":["code","enabled"],"rowBoundaries":row_boundaries, - "membershipBoundaries":boundary + "recordType":"flag","operations":["get"],"readableFields":["code","enabled"],"rowBoundaries":row_boundaries })); let sql = "SELECT r.id AS id, f.enabled AS active FROM registry_source.record r JOIN registry_source.flag f ON f.code = r.code"; let mut selection = options(); selection.fields = vec!["active".into()]; let before = export_evidence_source(&compiled(&original, sql), &selection).unwrap(); - original["accessProfiles"]["evidence-source"]["permissions"]["records"][1] - ["membershipBoundaries"][0]["field"] = json!("other-organization"); + original["accessProfiles"]["evidence-source"]["permissions"]["records"][1]["rowBoundaries"] + .as_array_mut() + .unwrap() + .last_mut() + .unwrap()["field"] = json!("other-organization"); assert_ne!( before.behavior_revision, export_evidence_source(&compiled(&original, sql), &selection) diff --git a/crates/registry-breg/src/fixtures.rs b/crates/registry-breg/src/fixtures.rs index 1b1ad4578b..bca5e40b8c 100644 --- a/crates/registry-breg/src/fixtures.rs +++ b/crates/registry-breg/src/fixtures.rs @@ -250,6 +250,11 @@ pub enum FixtureError { ResponseTooLarge, ResponseShapeRefused, ExpectationMismatch, + /// A Proposal Get step's `waitSeconds` ran out before its response + /// matched the step's expectation. + ProposalWaitTimedOut { + wait_seconds: u8, + }, ExecutionRefused, RuntimeSetup(SchemaTestRuntimeSetupError), CandidateBindingRefused, @@ -349,6 +354,12 @@ impl fmt::Display for FixtureError { "journeys[{journey_index}] `{journey_id}`: {message}" ); } + if let Self::ProposalWaitTimedOut { wait_seconds } = self { + return write!( + formatter, + "fixture.proposal.wait-timed-out: the Proposal step did not complete with a matching response within waitSeconds ({wait_seconds}). Check that the Action applies automatically and that the expected fields are the applied ones" + ); + } if let Self::ExpectedFieldNotReadable { step_id, field, @@ -403,6 +414,7 @@ impl fmt::Display for FixtureError { | Self::ReceiptDocument(_) | Self::JourneyRefused { .. } | Self::ExpectedFieldNotReadable { .. } + | Self::ProposalWaitTimedOut { .. } | Self::RequiredActionInputMissing { .. } => { unreachable!("handled above") } @@ -466,8 +478,11 @@ struct StepSource { #[cfg_attr(feature = "schema", schemars(with = "Option"))] capture: Option, /// Maps disclosed Action result aliases to distinct local capture aliases. - /// Capture aliases must be unique throughout the journey, including earlier - /// captures; the reader checks this semantic rule. + /// On a Proposal get or apply step, maps an effect ID to a record capture + /// taken from the application's result links; the effect must be the + /// Action's only effect on its Record type. Capture aliases must be unique + /// throughout the journey, including earlier captures; the reader checks + /// this semantic rule. #[serde(default, deserialize_with = "members::local_id_map")] #[cfg_attr( feature = "schema", @@ -509,6 +524,15 @@ enum ActionSource { input: Map, #[serde(default)] idempotency_key: Option, + /// The text a `message` step writes to the Proposal's thread. + #[serde(default)] + text: Option, + /// On a Get step, how long the schema test runs the built-in + /// application executor and reads the Proposal again until the + /// response matches the step's expectation. + #[serde(default)] + #[cfg_attr(feature = "schema", schemars(with = "Option>"))] + wait_seconds: Option, }, Import { #[serde(deserialize_with = "members::http_objects")] @@ -749,7 +773,7 @@ struct ClaimsSource { } impl ClaimsSource { - /// The authored scopes as a set, for comparison with a profile's. + /// The full authored scope set, for exact credential binding. fn scope_set(&self) -> BTreeSet { self.scopes.iter().cloned().collect() } @@ -1122,6 +1146,9 @@ struct ValidatedStep { expect: ExpectationSource, problem_bindings: FixtureProblemBindings, capture: Option, + /// Result captures: for an Invoke, alias by effect ID; for a Proposal + /// step, alias by the effect's Record type, which validation proved names + /// that effect alone, since result links carry no effect ID. capture_results: BTreeMap, } @@ -1816,12 +1843,22 @@ fn validate_claims( profile: &AccessProfileSource, outcome: ExpectedOutcome, ) -> Result<(), FixtureError> { + // Exact bearer binding includes every authored scope. For the profile + // comparison, set aside only OIDC scopes the profile does not require. + let profile_scopes = claims + .scopes + .iter() + .filter(|scope| { + profile.required_scopes.contains(*scope) + || !registry_platform_oidc::OPENID_CONNECT_SCOPES.contains(&scope.as_str()) + }) + .cloned() + .collect::>(); if claims .principal .as_deref() .is_none_or(|value| value.is_empty() || value.len() > MAX_BINDING_BYTES) - || !claims - .scopes + || !profile_scopes .iter() .all(|scope| profile.required_scopes.contains(scope)) { @@ -1871,7 +1908,7 @@ fn validate_claims( } if outcome == ExpectedOutcome::Success && (claims.principal.is_none() - || claims.scope_set() != *profile.required_scopes + || profile_scopes != *profile.required_scopes || (!profile.required_purposes.is_empty() && claims.purpose.is_none()) || missing_direct_claim) { @@ -2089,15 +2126,11 @@ fn fixture_action_input_value_is_valid( } } +/// The condition inputs the Action's own HTTP contract requires, so a journey +/// sends exactly the preconditions a caller would. A current-revision Action +/// requires none. fn condition_input_api_names(action: &CompiledAction) -> BTreeSet { - let logical_ids = action - .effects - .iter() - .filter_map(|effect| match &effect.target.binding { - crate::model::CompiledPlanTargetBinding::Existing { input } => Some(input.as_str()), - crate::model::CompiledPlanTargetBinding::Create => None, - }) - .collect::>(); + let logical_ids = crate::plan::condition_inputs(action); action .inputs .iter() @@ -3688,6 +3721,32 @@ async fn execute_schema_test_with_issuers( let mut runtime = SchemaTestRuntime::new(database, config, compiled, issuers, initial_facts.clone()).await?; + let result = run_schema_test_journeys(&mut runtime, suite, &credential_map).await; + if let Some(worker) = runtime.application_worker.take() { + worker + .shutdown(config.operational_timeouts().shutdown_grace) + .await; + } + result?; + + let final_facts = database_execution_facts(&runtime.pool).await?; + if final_facts != runtime.initial_facts || !runtime.readiness.is_ready().await { + return Err(FixtureError::CandidateBindingRefused); + } + let successful = SuccessfulFixtureJourneys { + registry_revision: suite.registry_revision.clone(), + file_sha256: suite.file_sha256.clone(), + journey_ids: sorted_journey_ids(suite), + candidate_binding_sha256: candidate_binding_sha256(&candidate), + }; + build_schema_test_receipt(&candidate, suite, &successful) +} + +async fn run_schema_test_journeys( + runtime: &mut SchemaTestRuntime, + suite: &ValidatedFixtureJourneys, + credential_map: &CredentialMap, +) -> Result<(), FixtureError> { let mut bearer_index = 0usize; let mut observations = BTreeMap::new(); for (journey_index, journey) in suite.journeys.iter().enumerate() { @@ -3700,44 +3759,62 @@ async fn execute_schema_test_with_issuers( let bearer = credential_map .get(&(journey.id.clone(), step.id.clone())) .ok_or_else(|| step_failure(FixtureError::RequestConstructionRefused))?; - runtime - .authenticate_exact(step, bearer.as_str()) - .await - .map_err(&step_failure)?; let bearer_token = bearer.as_str(); - let response = if matches!(step.action, ActionSource::Import { .. }) { - runtime - .execute_import(step, &observations, bearer_token) - .await - .map_err(&step_failure)? + let wait = proposals::wait_seconds(step).map(|wait_seconds| { + let deadline = tokio::time::Instant::now() + + std::time::Duration::from_secs(u64::from(wait_seconds)); + (deadline, wait_seconds) + }); + let execute = async { + runtime.authenticate_exact(step, bearer_token).await?; + let response = if matches!(step.action, ActionSource::Import { .. }) { + runtime + .execute_import(step, &observations, bearer_token) + .await? + } else if let Some((deadline, wait_seconds)) = wait { + runtime + .await_proposal( + &journey.id, + step, + &observations, + bearer_token, + deadline, + wait_seconds, + ) + .await? + } else { + let request = fixture_request(&journey.id, step, &observations, bearer_token)?; + runtime + .app + .call(request) + .await + .map_err(|error| match error {})? + }; + let actual = response.status().as_u16(); + if actual != step.expect.status { + let (problem_code, problem_detail) = response_problem(response).await; + return Err(FixtureError::ResponseStatusMismatch { + expected: step.expect.status, + actual, + problem_code, + problem_detail, + }); + } + accept_response( + step, + response, + &mut observations, + Some(&runtime.pool), + false, + ) + .await + }; + let result = if let Some((deadline, wait_seconds)) = wait { + run_proposal_wait_step(deadline, wait_seconds, execute).await } else { - let request = fixture_request(&journey.id, step, &observations, bearer_token) - .map_err(&step_failure)?; - runtime - .app - .call(request) - .await - .map_err(|error| match error {})? + execute.await }; - let actual = response.status().as_u16(); - if actual != step.expect.status { - let (problem_code, problem_detail) = response_problem(response).await; - return Err(step_failure(FixtureError::ResponseStatusMismatch { - expected: step.expect.status, - actual, - problem_code, - problem_detail, - })); - } - accept_response( - step, - response, - &mut observations, - Some(&runtime.pool), - false, - ) - .await - .map_err(step_failure)?; + result.map_err(step_failure)?; bearer_index += 1; } observations.clear(); @@ -3745,17 +3822,41 @@ async fn execute_schema_test_with_issuers( if bearer_index != credential_map.len() { return Err(FixtureError::ExecutionRefused); } - let final_facts = database_execution_facts(&runtime.pool).await?; - if final_facts != runtime.initial_facts || !runtime.readiness.is_ready().await { - return Err(FixtureError::CandidateBindingRefused); + Ok(()) +} + +async fn run_proposal_wait_step( + deadline: tokio::time::Instant, + wait_seconds: u8, + step: impl std::future::Future>, +) -> Result { + match tokio::time::timeout_at(deadline, step).await { + // A ready future can win even if it finished after the deadline. + Ok(result) if tokio::time::Instant::now() < deadline => result, + _ => Err(FixtureError::ProposalWaitTimedOut { wait_seconds }), } - let successful = SuccessfulFixtureJourneys { - registry_revision: suite.registry_revision.clone(), - file_sha256: suite.file_sha256.clone(), - journey_ids: sorted_journey_ids(suite), - candidate_binding_sha256: candidate_binding_sha256(&candidate), - }; - build_schema_test_receipt(&candidate, suite, &successful) +} + +async fn read_proposal_wait_response( + app: &mut Router, + request: Request, + expected_status: u16, + expected_fields: &Map, +) -> Result>, FixtureError> { + let response = app.call(request).await.map_err(|error| match error {})?; + if response.status().as_u16() != expected_status { + return Ok(Some(response)); + } + let (parts, body) = response.into_parts(); + let bytes = to_bytes(body, MAX_RESPONSE_BYTES) + .await + .map_err(|_| FixtureError::ResponseTooLarge)?; + let matched = serde_json::from_slice::(&bytes).is_ok_and(|document| { + expected_fields + .iter() + .all(|(key, value)| document.get(key) == Some(value)) + }); + Ok(matched.then(|| Response::from_parts(parts, Body::from(bytes)))) } /// The problem code and detail a status mismatch may name. A code is kept @@ -3818,6 +3919,10 @@ struct SchemaTestRuntime { package_revision: String, schema_fingerprint: String, import_authority: ImportAuthorityOperatorService, + /// The mutation service behind `app`, which a waiting Proposal step + /// drives through the built-in application executor. + mutations: Arc, + application_worker: Option, #[cfg(feature = "wasm")] _wasm_runtime: crate::wasm_runtime::ConfiguredWasmRuntime, } @@ -3960,7 +4065,7 @@ impl SchemaTestRuntime { cursor_codec, ) .with_postgres_revisions(revisions) - .with_postgres_mutations(mutations), + .with_postgres_mutations(Arc::clone(&mutations)), ); let app = crate::startup::with_request_timeout_for_test( crate::api::authenticated_router(service, Arc::clone(&authenticator)), @@ -3976,11 +4081,52 @@ impl SchemaTestRuntime { package_revision: expected.package_digest, schema_fingerprint: expected.schema_fingerprint, import_authority, + mutations, + application_worker: None, #[cfg(feature = "wasm")] _wasm_runtime: wasm_runtime, }) } + /// Read a Proposal until the response matches the step's expectation or + /// the step deadline expires. Before each read the built-in executor runs + /// the production automatic-application path until it has no due work or + /// the step's deadline expires. Steps without a wait never start an attempt. + async fn await_proposal( + &mut self, + journey_id: &str, + step: &ValidatedStep, + observations: &BTreeMap, + token: &str, + deadline: tokio::time::Instant, + wait_seconds: u8, + ) -> Result, FixtureError> { + while tokio::time::Instant::now() < deadline { + let worker = self.application_worker.get_or_insert_with(|| { + proposals::ApplicationWorker::spawn(Arc::clone(&self.mutations)) + }); + if worker.run_once(deadline).await? { + continue; + } + if tokio::time::Instant::now() >= deadline { + break; + } + let request = fixture_request(journey_id, step, observations, token)?; + if let Some(response) = read_proposal_wait_response( + &mut self.app, + request, + step.expect.status, + &step.expect.fields, + ) + .await? + { + return Ok(response); + } + tokio::time::sleep(std::time::Duration::from_millis(100)).await; + } + Err(FixtureError::ProposalWaitTimedOut { wait_seconds }) + } + async fn authenticate_exact( &self, step: &ValidatedStep, @@ -4663,7 +4809,11 @@ async fn accept_response( } } if !step.capture_results.is_empty() { - capture_immediate_action_results(step, &document, observations)?; + if let ActionSource::Proposal { .. } = step.action { + proposals::capture_results(step, &document, observations)?; + } else { + capture_immediate_action_results(step, &document, observations)?; + } } if let Some(capture) = step.capture.as_ref() { let kind = capture_observation_kind(step, &headers, &document)?; @@ -6478,6 +6628,7 @@ fn operation_method(operation: Operation) -> HttpMethod { } Operation::Patch => HttpMethod::Patch, Operation::Tombstone => HttpMethod::Delete, + Operation::Reference => unreachable!("a fixture step never names a reference grant"), } } @@ -6510,6 +6661,56 @@ mod tests { PackageLoadContext, PackageMigrationPlanInput, PackageModuleSource, PackageSourceFile, }; + #[tokio::test] + async fn proposal_wait_deadline_covers_delayed_get_and_body_independently() { + struct PendingBody; + impl futures_core::Stream for PendingBody { + type Item = Result; + + fn poll_next( + self: std::pin::Pin<&mut Self>, + _: &mut std::task::Context<'_>, + ) -> std::task::Poll> { + std::task::Poll::Pending + } + } + + for (path, app) in [ + ( + "/get", + Router::new().route( + "/get", + axum::routing::get(std::future::pending::>), + ), + ), + ( + "/body", + Router::new().route( + "/body", + axum::routing::get(|| async { Body::from_stream(PendingBody) }), + ), + ), + ] { + let mut app = app; + let request = Request::get(path).body(Body::empty()).unwrap(); + let deadline = tokio::time::Instant::now() + std::time::Duration::from_millis(20); + let fields = Map::from_iter([("state".to_owned(), json!("applied"))]); + let result = run_proposal_wait_step( + deadline, + 1, + read_proposal_wait_response(&mut app, request, 200, &fields), + ) + .await; + assert!( + matches!( + result, + Err(FixtureError::ProposalWaitTimedOut { wait_seconds: 1 }) + ), + "{path} must report the step deadline" + ); + } + } + #[test] fn fixture_refusals_distinguish_missing_claim_from_refused_credential() { assert_eq!( @@ -6934,12 +7135,14 @@ mod tests { assert_exact_claims(&undeclared, &profile, &exact, &claims.scope_set()), Err(FixtureError::AuthorityWideningRefused) ); - let widened_scopes = - BTreeSet::from(["registry:read".to_owned(), "registry:write".to_owned()]); - assert_eq!( - assert_exact_claims(&claims, &profile, &exact, &widened_scopes), - Err(FixtureError::AuthorityWideningRefused) - ); + for scope in ["registry:write", "openid"] { + let mut widened_scopes = claims.scope_set(); + widened_scopes.insert(scope.to_owned()); + assert_eq!( + assert_exact_claims(&claims, &profile, &exact, &widened_scopes), + Err(FixtureError::AuthorityWideningRefused) + ); + } } #[test] @@ -6989,6 +7192,58 @@ mod tests { } } + #[test] + fn fixture_profile_scope_comparison_sets_aside_openid_scopes() { + for (required, scopes, expected) in [ + (json!([]), json!(["openid", "profile"]), Ok(())), + ( + json!(["fixture:write", "openid"]), + json!(["openid", "profile", "fixture:write"]), + Ok(()), + ), + ( + json!(["fixture:write", "openid"]), + json!(["profile", "fixture:write"]), + Err(FixtureError::AuthorityWideningRefused), + ), + ( + json!(["fixture:write"]), + json!(["openid", "fixture:write"]), + Ok(()), + ), + ( + json!(["fixture:write"]), + json!(["openid", "fixture:write", "fixture:extra"]), + Err(FixtureError::AuthorityWideningRefused), + ), + ( + json!(["fixture:write"]), + json!(["openid"]), + Err(FixtureError::AuthorityWideningRefused), + ), + ] { + let profile = serde_json::from_value(json!({ + "id": "fixture", + "principalClaim": "sub", + "actorKind": "human", + "operations": ["get"], + "rowBoundaries": [], + "requiredScopes": required + })) + .unwrap(); + let claims = serde_json::from_value(json!({ + "principal": "fixture-person", + "actorKind": "human", + "scopes": scopes + })) + .unwrap(); + assert_eq!( + validate_claims(&claims, &profile, ExpectedOutcome::Success), + expected + ); + } + } + #[test] fn fixture_claims_leave_reserved_consent_claims_to_the_verified_client() { let profile: AccessProfileSource = serde_json::from_value(json!({ @@ -7073,7 +7328,7 @@ journeys: - id: list-people recordType: person accessProfile: person-operator - claims: {principal: fixture-operator, purpose: person-maintenance} + claims: {principal: fixture-operator, purpose: person-maintenance, scopes: [people:write]} request: {type: list} expect: {outcome: success, status: 200, count: 0} "#; @@ -7400,7 +7655,7 @@ journeys: {"id":"name","type":"string","maximumLength":80,"required":true,"classification":"internal"}], "plan":{"type":"scripted","actionPlan":"person-plan","inputs":["person","name"], "writes":[{"id":"person","target":{"fromInput":"person"},"operation":"patch","fields":["name"]}]}}}, - "accessProfiles":{"person-operator": {"principalClaim":"principal","requiredScopes":"unrestricted","requiredPurposes":["person-maintenance"], + "accessProfiles":{"person-operator": {"principalClaim":"principal","requiredScopes":["people:write"],"requiredPurposes":["person-maintenance"], "permissions":{"records":[{"recordType":"person","operations":["get","list"],"readableFields":["name"],"rowBoundaries":"unrestricted"}], "actions":[{"action":"rename-person","operations":["invoke"],"targets":[{"recordType":"person","rowBoundaries":"unrestricted"}],"results":["person"]}]}}} })).unwrap() @@ -8797,7 +9052,7 @@ journeys: .expect("constraint project compiles"); let step = |id: &str, request: &str| { format!( - " - id: {id}\n recordType: widget\n accessProfile: operator\n claims:\n principal: fixture-operator\n purpose: case-management\n directClaims: {{jurisdiction: zone-a}}\n request: {request}\n expect: {{outcome: refusal, status: 409, problemCode: mutation.conflict}}\n" + " - id: {id}\n recordType: widget\n accessProfile: operator\n claims:\n principal: fixture-operator\n scopes: [fixture:write]\n purpose: case-management\n directClaims: {{jurisdiction: zone-a}}\n request: {request}\n expect: {{outcome: refusal, status: 409, problemCode: mutation.conflict}}\n" ) }; let journeys = format!( diff --git a/crates/registry-breg/src/fixtures/proposals.rs b/crates/registry-breg/src/fixtures/proposals.rs index 7ff32dd06a..c91792a78b 100644 --- a/crates/registry-breg/src/fixtures/proposals.rs +++ b/crates/registry-breg/src/fixtures/proposals.rs @@ -1,8 +1,90 @@ // SPDX-License-Identifier: Apache-2.0 //! Authored Proposal journeys exercise only the ordinary authenticated source API. +use std::time::Duration; + +use tokio::sync::{mpsc, oneshot, watch}; +use tokio::time::{timeout, Instant}; + use super::*; use crate::contract::ProposalOperation; use crate::model::{CompiledActionExecution, CompiledProposalPermission}; +use crate::startup::{BackgroundTask, OperationalEvent, SupervisedTask}; + +struct ApplicationAttempt { + step_deadline: Instant, + result: oneshot::Sender, +} + +/// The schema test owns this worker until cleanup. Each waiting step can ask +/// for one production application attempt at a time. +pub(super) struct ApplicationWorker { + attempts: mpsc::Sender, + shutdown: watch::Sender, + task: SupervisedTask, +} + +impl ApplicationWorker { + pub(super) fn spawn(mutations: Arc) -> Self { + let (attempts, mut requested) = mpsc::channel::(1); + let (shutdown, shutdown_rx) = watch::channel(false); + let task = SupervisedTask::spawn( + BackgroundTask::ReviewWorker, + async move { + while let Some(attempt) = requested.recv().await { + let worked = + if attempt.result.is_closed() || Instant::now() >= attempt.step_deadline { + false + } else { + match mutations.run_automatic_proposal_once().await { + Ok(worked) => worked, + Err(_) => { + OperationalEvent::ReviewWorkerIterationFailed.emit(); + false + } + } + }; + // The step may have timed out. The worker's transaction + // and lease govern the attempt even without a waiter. + let _ = attempt.result.send(worked); + } + }, + shutdown_rx, + None, + ); + Self { + attempts, + shutdown, + task, + } + } + + pub(super) async fn run_once(&self, step_deadline: Instant) -> Result { + let (result, completed) = oneshot::channel(); + self.attempts + .send(ApplicationAttempt { + step_deadline, + result, + }) + .await + .map_err(|_| FixtureError::ExecutionRefused)?; + completed.await.map_err(|_| FixtureError::ExecutionRefused) + } + + pub(super) async fn shutdown(self, grace: Duration) { + let Self { + attempts, + shutdown, + mut task, + } = self; + shutdown.send_replace(true); + drop(attempts); + if timeout(grace, task.join()).await.is_err() { + // Cancel and join like serve. An unfinished committed claim + // retains its token, attempt count and expiry for lease recovery. + task.abort_and_join().await; + } + } +} #[derive(Clone, Copy, Deserialize, PartialEq, Eq)] #[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] @@ -19,6 +101,10 @@ pub(super) enum ProposalJourneyOperation { Apply, GetReviewContext, GetReviewStatus, + /// Write `text` to the Proposal's message thread. + Message, + /// Mark the thread read through the newest message the capture shows. + ReadMessages, } impl ProposalJourneyOperation { @@ -35,6 +121,7 @@ impl ProposalJourneyOperation { Self::Apply => ProposalOperation::Apply, Self::GetReviewContext => ProposalOperation::GetReviewContext, Self::GetReviewStatus => ProposalOperation::GetReviewStatus, + Self::Message | Self::ReadMessages => ProposalOperation::Message, }) } fn path(self) -> &'static str { @@ -50,6 +137,8 @@ impl ProposalJourneyOperation { Self::Apply => "apply", Self::GetReviewContext => "review-context", Self::GetReviewStatus => "review-status", + Self::Message => "messages", + Self::ReadMessages => "messages/read", } } fn reads(self) -> bool { @@ -83,6 +172,7 @@ fn profile(grant: &CompiledProposalPermission) -> Result Option { + match &step.action { + ActionSource::Proposal { wait_seconds, .. } => *wait_seconds, + _ => None, + } +} + +/// Validate `captureResults` on a Proposal step and register each alias as a +/// record capture. An application's result links name a Record type and a +/// record, not an effect, so an effect is captured only when it is the +/// Action's one effect on its Record type; the returned map is keyed by that +/// Record type. +fn validate_result_captures( + step: &StepSource, + operation: ProposalJourneyOperation, + action: &CompiledAction, + captures: &mut BTreeMap, + ids: &mut BTreeSet, +) -> Result, FixtureError> { + let mut by_record_type = BTreeMap::new(); + if step.capture_results.is_empty() { + return Ok(by_record_type); + } + if !matches!( + operation, + ProposalJourneyOperation::Get | ProposalJourneyOperation::Apply + ) || step.expect.outcome != ExpectedOutcome::Success + { + return Err(FixtureError::JourneyShapeRefused); + } + for (effect, alias) in &step.capture_results { + let record_type = &action + .effects + .iter() + .find(|compiled| compiled.id == *effect) + .ok_or(FixtureError::LogicalReferenceRefused)? + .target + .entity_id; + if action + .effects + .iter() + .filter(|compiled| compiled.target.entity_id == *record_type) + .count() + != 1 + { + return Err(FixtureError::LogicalReferenceRefused); + } + if !valid_stable_id(alias) { + return Err(FixtureError::LogicalReferenceRefused); + } + if !ids.insert(alias.clone()) { + return Err(FixtureError::DuplicateIdentifier); + } + captures.insert( + alias.clone(), + CaptureSource { + entity: Some(record_type.clone()), + has_etag: false, + condition_map: false, + proposal_action: None, + }, + ); + by_record_type.insert(record_type.clone(), alias.clone()); + } + Ok(by_record_type) +} + +/// Capture each record the step names from the application's result links. +pub(super) fn capture_results( + step: &ValidatedStep, + document: &Value, + observations: &mut BTreeMap, +) -> Result<(), FixtureError> { + let links = document + .pointer("/application/resultLinks") + .and_then(Value::as_array) + .ok_or(FixtureError::ResponseShapeRefused)?; + for (record_type, alias) in &step.capture_results { + let mut matching = links + .iter() + .filter(|link| link["recordType"].as_str() == Some(record_type)); + let (Some(link), None) = (matching.next(), matching.next()) else { + return Err(FixtureError::ResponseShapeRefused); + }; + let record_id = link["recordId"] + .as_str() + .filter(|value| uuid::Uuid::parse_str(value).is_ok_and(|id| id.to_string() == *value)) + .ok_or(FixtureError::ResponseShapeRefused)?; + let revision = link["revision"] + .as_u64() + .ok_or(FixtureError::ResponseShapeRefused)?; + observations.insert( + alias.clone(), + Observation { + kind: ObservationKind::Record { + record_id: record_id.to_owned(), + etag: format!("\"breg-action-result-{revision}\""), + }, + }, + ); + } + Ok(()) +} + fn observed<'a>( observations: &'a BTreeMap, reference: &str, @@ -290,6 +509,8 @@ pub(super) fn request( submission_capture, input, idempotency_key, + text, + .. } = &step.action else { return Err(FixtureError::RequestConstructionRefused); @@ -302,7 +523,7 @@ pub(super) fn request( .as_str() .ok_or(FixtureError::RequestConstructionRefused)?; path = path.replace("{proposal_id}", id); - if !operation.reads() { + if !operation.reads() && *operation != ProposalJourneyOperation::ReadMessages { if_match = Some( etag_capture .as_deref() @@ -331,6 +552,20 @@ pub(super) fn request( let (document, _) = observed(observations, reference)?; json!({"submissionVersion":document["submissionVersion"],"effectDigest":document["effectDigest"]}) } + ProposalJourneyOperation::Message => { + json!({"text":text.as_deref().ok_or(FixtureError::RequestConstructionRefused)?}) + } + // Read through the newest message the captured document shows. + ProposalJourneyOperation::ReadMessages => { + let reference = proposal_capture + .as_ref() + .ok_or(FixtureError::RequestConstructionRefused)?; + let (document, _) = observed(observations, reference)?; + let through = document["messages"]["items"][0]["id"] + .as_str() + .ok_or(FixtureError::RequestConstructionRefused)?; + json!({ "through": through }) + } _ => json!({}), }; let mut request = authenticated_json_request( @@ -346,7 +581,7 @@ pub(super) fn request( if operation.reads() { *request.body_mut() = Body::empty(); request.headers_mut().remove(CONTENT_TYPE); - } else { + } else if *operation != ProposalJourneyOperation::ReadMessages { let key = format!( "fixture-{journey}-{}-{}", step.action_id @@ -374,17 +609,23 @@ pub(super) fn assert_response(step: &ValidatedStep, document: &Value) -> Result< let ActionSource::Proposal { operation, .. } = &step.action else { return Err(FixtureError::ResponseShapeRefused); }; - if !matches!( + // A thread command answers a reviewer without Get with the review context. + let review_document = matches!( *operation, ProposalJourneyOperation::GetReviewContext | ProposalJourneyOperation::GetReviewStatus - ) && (document["actionId"].as_str() != step.action_id.as_deref() - || document["id"] - .as_str() - .is_none_or(|id| uuid::Uuid::parse_str(id).is_err()) - || !matches!( - document["state"].as_str(), - Some("draft" | "submitted" | "applied" | "cancelled" | "rejected") - )) + ) || matches!( + *operation, + ProposalJourneyOperation::Message | ProposalJourneyOperation::ReadMessages + ) && document.get("context").is_some(); + if !review_document + && (document["actionId"].as_str() != step.action_id.as_deref() + || document["id"] + .as_str() + .is_none_or(|id| uuid::Uuid::parse_str(id).is_err()) + || !matches!( + document["state"].as_str(), + Some("draft" | "submitted" | "applied" | "cancelled" | "rejected") + )) { return Err(FixtureError::ResponseShapeRefused); } @@ -542,6 +783,295 @@ mod tests { ); } + const AUTOMATIC_PROJECT: &[u8] = + include_bytes!("../../tests/fixtures/automatic-application/project.yaml"); + const AUTOMATIC_JOURNEYS: &[u8] = + include_bytes!("../../tests/fixtures/automatic-application/journeys.yaml"); + + fn automatic_registry() -> CompiledRegistry { + compile_project_with_assets( + &parse_project_yaml(AUTOMATIC_PROJECT).unwrap(), + &[], + &[], + CompileProfile::Authoring, + ) + .unwrap() + } + + fn step<'a>(suite: &'a ValidatedFixtureJourneys, id: &str) -> &'a ValidatedStep { + suite + .journeys + .iter() + .flat_map(|journey| &journey.steps) + .find(|step| step.id == id) + .unwrap() + } + + #[test] + fn a_get_step_may_wait_and_capture_the_record_its_effect_wrote() { + let suite = validate_fixture_journeys(AUTOMATIC_JOURNEYS, &automatic_registry()).unwrap(); + let wait = step(&suite, "await-application"); + assert_eq!(wait_seconds(wait), Some(10)); + // Result links carry no effect ID, so the capture is held by the + // effect's Record type, which names that effect alone. + assert_eq!( + wait.capture_results, + BTreeMap::from([("note".to_owned(), "filed-note".to_owned())]) + ); + assert_eq!(wait_seconds(step(&suite, "submit-note")), None); + } + + #[test] + #[allow( + clippy::disallowed_methods, + reason = "tests edit a checked-in synthetic authored journey to assert refusals" + )] + fn waits_and_result_captures_are_refused_where_they_cannot_hold() { + let registry = automatic_registry(); + let original: Value = serde_norway::from_slice(AUTOMATIC_JOURNEYS).unwrap(); + let refused = |step_id: &str, edit: &dyn Fn(&mut Value)| { + let mut changed = original.clone(); + let step = changed["journeys"][0]["steps"] + .as_array_mut() + .unwrap() + .iter_mut() + .find(|step| step["id"] == step_id) + .unwrap(); + edit(step); + validate_fixture_journeys(&serde_json::to_vec(&changed).unwrap(), ®istry).is_err() + }; + // Only a Get waits; a command is never repeated. + assert!(refused("submit-note", &|step| step["request"] + ["waitSeconds"] = + json!(5))); + // The wait is bounded at one minute and is never zero. + for bound in [0, 61] { + assert!(refused("await-application", &|step| step["request"] + ["waitSeconds"] = + json!(bound))); + } + // A wait needs fields to wait for, and a success to read them from. + assert!(refused("await-application", &|step| { + step["expect"].as_object_mut().unwrap().remove("fields"); + })); + assert!(refused("await-application", &|step| { + step["expect"] = + json!({"outcome": "refusal", "status": 404, "problemCode": "resource.not-found"}); + step.as_object_mut().unwrap().remove("captureResults"); + })); + // A result capture names one of the Action's effects, on a read or + // apply response that carries the application. + assert!(refused("await-application", &|step| step + ["captureResults"] = + json!({"unknown-effect": "filed-note"}))); + assert!(refused("submit-note", &|step| step["captureResults"] = + json!({"note": "filed-note"}))); + // A captured alias is unique in the journey. + assert!(refused("await-application", &|step| step + ["captureResults"] = + json!({"filed": "draft"}))); + } + + #[test] + #[allow( + clippy::disallowed_methods, + reason = "tests edit a checked-in synthetic authored project to assert refusals" + )] + fn two_effects_on_one_record_type_cannot_be_told_apart_in_the_result_links() { + let mut project: Value = serde_norway::from_slice(AUTOMATIC_PROJECT).unwrap(); + project["actions"]["file-note"]["plan"]["effects"] + .as_array_mut() + .unwrap() + .push(json!({"id": "copy", "target": {"recordType": "note"}, "operation": "create", "set": {"body": {"fromInput": "body"}}})); + let registry = compile_project_with_assets( + &crate::contract::parse_project_json(&serde_json::to_vec(&project).unwrap()).unwrap(), + &[], + &[], + CompileProfile::Authoring, + ) + .unwrap(); + assert!(validate_fixture_journeys(AUTOMATIC_JOURNEYS, ®istry).is_err()); + } + + #[test] + fn a_result_capture_takes_the_link_for_its_effects_record_type() { + let suite = validate_fixture_journeys(AUTOMATIC_JOURNEYS, &automatic_registry()).unwrap(); + let wait = step(&suite, "await-application"); + let record = uuid::Uuid::new_v4(); + let mut observations = BTreeMap::new(); + capture_results( + wait, + &json!({"application": {"resultLinks": [ + {"recordType": "note", "recordId": record, "revision": 1} + ]}}), + &mut observations, + ) + .unwrap(); + let ObservationKind::Record { record_id, .. } = &observations["filed-note"].kind else { + panic!("a result capture is a record observation"); + }; + assert_eq!(record_id, &record.to_string()); + for document in [ + json!({}), + json!({"application": {"resultLinks": []}}), + json!({"application": {"resultLinks": [ + {"recordType": "other", "recordId": record, "revision": 1} + ]}}), + json!({"application": {"resultLinks": [ + {"recordType": "note", "recordId": "not-a-uuid", "revision": 1} + ]}}), + ] { + assert!(capture_results(wait, &document, &mut BTreeMap::new()).is_err()); + } + } + + #[test] + fn the_starter_journeys_wait_for_their_automatic_registration() { + let registry = compile_project_with_assets( + &parse_project_yaml(include_bytes!( + "../../../../products/breg/examples/minimal/registry.yaml" + )) + .unwrap(), + &[], + &[], + CompileProfile::Authoring, + ) + .unwrap(); + let suite = validate_fixture_journeys( + include_bytes!("../../../../products/breg/examples/minimal/tests/journeys.yaml"), + ®istry, + ) + .unwrap(); + assert!(wait_seconds(step(&suite, "await-registration")).is_some()); + } + + const MESSAGE_PROJECT: &[u8] = + include_bytes!("../../tests/fixtures/message-journeys/project.yaml"); + + const MESSAGE_JOURNEY: &[u8] = + include_bytes!("../../tests/fixtures/message-journeys/journeys.yaml"); + + fn message_registry() -> CompiledRegistry { + crate::compiler::compile_project( + &parse_project_yaml(MESSAGE_PROJECT).unwrap(), + &[], + CompileProfile::Authoring, + ) + .unwrap() + } + + fn message_step<'a>(suite: &'a ValidatedFixtureJourneys, id: &str) -> &'a ValidatedStep { + suite.journeys[0] + .steps + .iter() + .find(|step| step.id == id) + .unwrap() + } + + #[tokio::test] + async fn message_journeys_write_through_the_thread_route_and_read_through_the_newest_message() { + let registry = message_registry(); + let suite = validate_fixture_journeys(MESSAGE_JOURNEY, ®istry).unwrap(); + let id = uuid::Uuid::new_v4(); + let newest = uuid::Uuid::new_v4(); + let observations = BTreeMap::from([ + ( + "office-view".to_owned(), + Observation { + kind: ObservationKind::Proposal { + document: json!({"id":id}), + etag: "\"office-condition\"".to_owned(), + }, + }, + ), + ( + "applicant-view".to_owned(), + Observation { + kind: ObservationKind::Proposal { + document: json!({"id":id,"messages":{"items":[{"id":newest},{"id":uuid::Uuid::new_v4()}]}}), + etag: "\"applicant-condition\"".to_owned(), + }, + }, + ), + ]); + + let write = fixture_request( + "thread", + message_step(&suite, "office-writes"), + &observations, + "synthetic-token", + ) + .unwrap(); + assert_eq!(write.method(), Method::POST); + assert_eq!(write.uri().path(), format!("/v1/proposals/{id}/messages")); + assert_eq!(write.uri().query(), Some("accessProfile=office")); + assert_eq!(write.headers()[IF_MATCH], "\"office-condition\""); + assert!(write.headers().contains_key("idempotency-key")); + let bytes = axum::body::to_bytes(write.into_body(), 4096).await.unwrap(); + let body: Value = serde_json::from_slice(&bytes).unwrap(); + assert_eq!(body, json!({"text":"Please add the full address."})); + + let read = fixture_request( + "thread", + message_step(&suite, "applicant-reads"), + &observations, + "synthetic-token", + ) + .unwrap(); + assert_eq!(read.method(), Method::POST); + assert_eq!( + read.uri().path(), + format!("/v1/proposals/{id}/messages/read") + ); + // Mark-read only moves the reader's side forward: no condition, no key. + assert!(!read.headers().contains_key(IF_MATCH)); + assert!(!read.headers().contains_key("idempotency-key")); + let bytes = axum::body::to_bytes(read.into_body(), 4096).await.unwrap(); + let body: Value = serde_json::from_slice(&bytes).unwrap(); + assert_eq!(body, json!({"through":newest})); + } + + #[test] + #[allow( + clippy::disallowed_methods, + reason = "tests edit an inline synthetic journey to assert refusals" + )] + fn message_steps_take_text_only_where_they_write_and_need_the_grant() { + let registry = message_registry(); + let original: Value = serde_norway::from_slice(MESSAGE_JOURNEY).unwrap(); + let edit = |id: &str, change: &dyn Fn(&mut Value)| { + let mut changed = original.clone(); + let step = changed["journeys"][0]["steps"] + .as_array_mut() + .unwrap() + .iter_mut() + .find(|step| step["id"] == id) + .unwrap(); + change(step); + validate_fixture_journeys(&serde_json::to_vec(&changed).unwrap(), ®istry) + }; + // A message without text, text on a step that writes none, and a + // mark-read that names a key are each refused. + assert!(edit("office-writes", &|step| { + step["request"].as_object_mut().unwrap().remove("text"); + }) + .is_err()); + assert!(edit("applicant-view", &|step| { + step["request"]["text"] = json!("Not a message"); + }) + .is_err()); + assert!(edit("applicant-reads", &|step| { + step["request"]["idempotencyKey"] = json!("read-once"); + }) + .is_err()); + // The applicant's grant holds message; a profile without it cannot + // be named for a message step. + assert!(edit("office-writes", &|step| { + step["accessProfile"] = json!("missing-profile"); + }) + .is_err()); + } + #[test] fn proposal_unknown_members_use_positioned_closed_union_diagnostics() { let bytes = b"apiVersion: id.registrystack.org/formats/breg/journeys/v1\nkind: BRegJourneys\njourneys:\n - id: example\n steps:\n - id: start\n action: deactivate-facility\n accessProfile: facility-correction-author\n claims: {principal: example}\n request:\n type: proposal\n transition: start\n approve: true\n expect: {outcome: success, status: 201}\n"; diff --git a/crates/registry-breg/src/generated_ddl.rs b/crates/registry-breg/src/generated_ddl.rs index f1b5ac18c3..7d0633c44c 100644 --- a/crates/registry-breg/src/generated_ddl.rs +++ b/crates/registry-breg/src/generated_ddl.rs @@ -26,6 +26,7 @@ use crate::physical_names::{ const RECORD_ID_COLUMN: &str = "record_id"; const GENERATED_TEXT_COLLATION: &str = "pg_catalog.pg_c_utf8"; +pub(crate) const REFERENCE_PROBE_ENTITY_SETTING: &str = "registry.reference_probe_entity"; pub(crate) const REFERENCE_LIFECYCLE_COLUMN: &str = "record_reference_lifecycle"; /// The schema the generated spatial SQL reads PostGIS from. pub const POSTGIS_EXTENSION_SCHEMA: &str = "registry_spatial_ext"; @@ -237,6 +238,7 @@ pub(crate) fn generate_ddl_with_actions( names: &PhysicalNameInventory, actions: &CompiledActionInventory, ) -> DdlInventory { + let membership_probes = crate::membership::probes(entities, actions); let mut statements = vec![DdlStatement { id: "schema.registry_data".to_owned(), kind: DdlStatementKind::Schema, @@ -502,7 +504,10 @@ pub(crate) fn generate_ddl_with_actions( for field_id in spatial_projection_fields(entity) { statements.push(spatial_projection_statements(entity, &field_id).create_index); } - for (id, _, sql) in crate::consent::index_statements(entity) { + for (id, _, sql) in crate::consent::index_statements(entity) + .into_iter() + .chain(crate::membership::index_statement(entity)) + { statements.push(DdlStatement { id, kind: DdlStatementKind::Index, @@ -544,35 +549,48 @@ pub(crate) fn generate_ddl_with_actions( // Invoker helpers give membership facts a processing-only RLS context. // The exception block rolls back the local marker on errors; normal return // restores its prior value. No cluster-wide custom-parameter ACL is needed. - for entity in entities.values() { - for (profile_id, boundaries) in &entity.membership_boundaries { - for (index, boundary) in boundaries.iter().enumerate() { - let name = crate::membership::function_name(&entity.id, profile_id, index); - let body = format!( - "DECLARE prior_marker text := current_setting('registry.membership_probe', true); authorized boolean; BEGIN PERFORM set_config('registry.membership_probe', {}, true); SELECT EXISTS (SELECT 1 FROM registry_data.{} AS membership WHERE {} AND membership.{} = $1) INTO authorized; PERFORM set_config('registry.membership_probe', COALESCE(prior_marker, ''), true); RETURN authorized; EXCEPTION WHEN OTHERS THEN RAISE; END", - quote_literal(&name), - quote_identifier(&boundary.membership_table), - crate::membership::source_predicate(boundary, "membership"), - quote_identifier(&boundary.membership_key_column), - ); - statements.push(DdlStatement { - id: format!("registry_context.{name}"), - kind: DdlStatementKind::Function, - sql: format!( - "CREATE FUNCTION registry_context.{}(uuid) RETURNS boolean LANGUAGE plpgsql STABLE STRICT SECURITY INVOKER SET search_path = pg_catalog AS {}", - quote_identifier(&name), quote_literal(&body), - ), - }); - functions.push(DdlFunction { - id: format!("registry_context.{name}"), - schema: "registry_context".to_owned(), - name, - arguments: "uuid".to_owned(), - runtime_execute: true, - spatial_bbox_execute: false, - }); - } - } + for probe in &membership_probes { + let boundary = probe.boundary; + let name = probe.name.clone(); + let scan = format!( + "1 FROM registry_data.{} AS membership WHERE {} AND membership.{} = $1", + quote_identifier(&boundary.membership_table), + crate::membership::source_predicate(boundary, "membership"), + quote_identifier(&boundary.membership_key_column), + ); + let (query, volatility) = if probe.locks { + ( + format!( + "PERFORM {scan} ORDER BY membership.record_id FOR SHARE; authorized := FOUND" + ), + "VOLATILE", + ) + } else { + ( + format!("SELECT EXISTS (SELECT {scan}) INTO authorized"), + "STABLE", + ) + }; + let body = format!( + "DECLARE prior_marker text := current_setting('registry.membership_probe', true); authorized boolean; BEGIN PERFORM set_config('registry.membership_probe', {}, true); {query}; PERFORM set_config('registry.membership_probe', COALESCE(prior_marker, ''), true); RETURN authorized; EXCEPTION WHEN OTHERS THEN RAISE; END", + quote_literal(&name), + ); + statements.push(DdlStatement { + id: format!("registry_context.{name}"), + kind: DdlStatementKind::Function, + sql: format!( + "CREATE FUNCTION registry_context.{}(uuid) RETURNS boolean LANGUAGE plpgsql {volatility} STRICT SECURITY INVOKER SET search_path = pg_catalog AS {}", + quote_identifier(&name), quote_literal(&body), + ), + }); + functions.push(DdlFunction { + id: format!("registry_context.{name}"), + schema: "registry_context".to_owned(), + name, + arguments: "uuid".to_owned(), + runtime_execute: true, + spatial_bbox_execute: false, + }); } // Consent probes share the membership security shape: an invoker helper // whose own marker opens the consent table's guarded policy for this @@ -608,17 +626,20 @@ pub(crate) fn generate_ddl_with_actions( } } for entity in entities.values() { - let runtime_privileges = runtime_privileges(entity, entities, actions); + let runtime_privileges = runtime_privileges(entity, entities, actions, &membership_probes); let runtime_lock_column = !runtime_privileges.contains(&TablePrivilege::Update) - && actions - .actions + && (membership_probes .iter() - .flat_map(|action| &action.target_uses) - .any(|target| { - target.entity_id == entity.id - && matches!(target.operation, Operation::Get | Operation::Invoke) - }); - let policies = policies(entity, entities, actions); + .any(|probe| probe.locks && probe.boundary.membership_entity == entity.id) + || actions + .actions + .iter() + .flat_map(|action| &action.target_uses) + .any(|target| { + target.entity_id == entity.id + && matches!(target.operation, Operation::Get | Operation::Invoke) + })); + let policies = policies(entity, entities, actions, &membership_probes); let table = quote_identifier(&entity.physical_table); statements.push(DdlStatement { id: format!("entity.{}.rls.enable", entity.id), @@ -1508,6 +1529,7 @@ fn runtime_privileges( entity: &CompiledEntity, entities: &BTreeMap, actions: &CompiledActionInventory, + membership_probes: &[crate::membership::MembershipProbe<'_>], ) -> BTreeSet { let operations = entity .access_profiles @@ -1524,18 +1546,17 @@ fn runtime_privileges( | Operation::Batch | Operation::Revisions | Operation::Snapshot + | Operation::Reference ) }) || path_select_entities(entities).contains(&entity.id) + || membership_probes + .iter() + .any(|probe| probe.boundary.membership_entity == entity.id) || entities.values().any(|root| { - root.membership_boundaries + root.consent_requirements .values() .flatten() - .any(|boundary| boundary.membership_entity == entity.id) - || root - .consent_requirements - .values() - .flatten() - .any(|requirement| requirement.record == entity.id) + .any(|requirement| requirement.record == entity.id) }) { privileges.insert(TablePrivilege::Select); @@ -1577,6 +1598,7 @@ fn policies( entity: &CompiledEntity, entities: &BTreeMap, actions: &CompiledActionInventory, + membership_probes: &[crate::membership::MembershipProbe<'_>], ) -> Vec { let mut policies = Vec::new(); for profile in entity.access_profiles.values() { @@ -1588,7 +1610,15 @@ fn policies( if !profile_supports_command(&profile.operations, command) { continue; } - let authority = policy_authority_expression(entity, profile); + let mut authority = policy_authority_expression(entity, profile); + if command == PolicyCommand::Select + && profile.operations.contains(&Operation::Reference) + { + authority = format!( + "({authority}) AND current_setting('{REFERENCE_PROBE_ENTITY_SETTING}', true) = {}", + quote_literal(&entity.id), + ); + } let (using_expression, check_expression) = match command { PolicyCommand::Select => ( Some(format!("({authority}) AND (record_lifecycle = 'active')")), @@ -1639,7 +1669,7 @@ fn policies( }); } } - policies.extend(membership_source_policies(entity, entities)); + policies.extend(membership_source_policies(entity, membership_probes)); policies.extend(consent_source_policies(entity, entities)); policies.extend(read_path_policies_for_table(entity, entities)); policies.extend(immediate_action_target_policies_for_table(entity, actions)); @@ -1680,36 +1710,38 @@ pub(crate) fn disclosure_policy_name(entity_id: &str, condition_id: &str) -> Str fn membership_source_policies( entity: &CompiledEntity, - entities: &BTreeMap, + probes: &[crate::membership::MembershipProbe<'_>], ) -> Vec { let mut policies = Vec::new(); - for root in entities.values() { - for (profile, boundaries) in &root.membership_boundaries { - for (index, boundary) in boundaries.iter().enumerate() { - if boundary.membership_entity != entity.id { - continue; - } - policies.push(DdlPolicy { - permissive: true, - name: format!( - "registry_{}", - crate::membership::function_name(&root.id, profile, index) - ), - command: PolicyCommand::Select, - access_profile: profile.clone(), - applies_to: DdlPolicyRole::Runtime, - using_expression: Some(format!( - "({}) AND ({})", - crate::membership::source_guard(&root.id, profile, index), - crate::membership::source_predicate( - boundary, - "e_identifier(&entity.physical_table) - ) - )), - check_expression: None, - }); - } + for probe in probes + .iter() + .filter(|probe| probe.boundary.membership_entity == entity.id) + { + let select = DdlPolicy { + permissive: true, + name: format!("registry_{}", probe.name), + command: PolicyCommand::Select, + access_profile: probe.profile.to_owned(), + applies_to: DdlPolicyRole::Runtime, + using_expression: Some(format!( + "({}) AND ({})", + crate::membership::source_guard(&probe.name, probe.profile), + crate::membership::source_predicate( + probe.boundary, + "e_identifier(&entity.physical_table) + ) + )), + check_expression: None, + }; + if probe.locks { + policies.push(DdlPolicy { + name: format!("{}_update", select.name), + command: PolicyCommand::Update, + check_expression: Some("false".to_owned()), + ..select.clone() + }); } + policies.push(select); } policies } @@ -1891,6 +1923,8 @@ fn profile_inserts(operations: &BTreeSet) -> bool { fn profile_supports_command(operations: &BTreeSet, command: PolicyCommand) -> bool { match command { + // A reference grant serves no read route, but a direct write naming a + // record reads it under this policy to check the caller's reach. PolicyCommand::Select => operations.iter().any(|operation| { matches!( operation, @@ -1900,6 +1934,7 @@ fn profile_supports_command(operations: &BTreeSet, command: PolicyCom | Operation::Batch | Operation::Revisions | Operation::Snapshot + | Operation::Reference ) }), PolicyCommand::Insert => profile_inserts(operations), @@ -2113,6 +2148,7 @@ fn immediate_action_target_policies_for_table( if !emitted_profiles.insert(grant.profile_id.as_str()) || target_effects.is_empty() { continue; } + let first_policy = policies.len(); let expressions = immediate_action_application_expressions( target_entity, action, @@ -2211,6 +2247,7 @@ fn immediate_action_target_policies_for_table( check_expression: Some(writable), }); } + append_action_target_probes(target_entity, grant, &mut policies[first_policy..]); } for target_use in action.target_uses.iter().filter(|target_use| { @@ -2232,6 +2269,7 @@ fn immediate_action_target_policies_for_table( .iter() .any(|target| target.entity_id == target_entity.id) }) { + let first_policy = policies.len(); let expression = immediate_action_link_expression( target_entity, action, @@ -2267,12 +2305,31 @@ fn immediate_action_target_policies_for_table( using_expression: Some(format!("{expression} AND record_lifecycle = 'active'")), check_expression: Some("false".to_owned()), }); + append_action_target_probes(target_entity, grant, &mut policies[first_policy..]); } } } policies } +fn append_action_target_probes( + entity: &CompiledEntity, + grant: &crate::model::CompiledActionPermission, + policies: &mut [DdlPolicy], +) { + if let Some(target) = grant + .entity_target_locks() + .find(|target| target.entity_id == entity.id) + { + crate::membership::append_target_probes( + entity, + &grant.profile_id, + &target.membership_boundaries, + policies, + ); + } +} + fn immediate_action_application_expressions( target_entity: &CompiledEntity, action: &CompiledAction, @@ -3430,6 +3487,13 @@ pub(crate) fn quote_literal(value: &str) -> String { format!("'{}'", value.replace('\'', "''")) } +#[cfg(test)] +use crate as breg_fixture_crate; + +#[cfg(test)] +#[path = "../tests/support/membership_targets.rs"] +mod membership_targets; + #[cfg(test)] mod tests { use serde_json::json; @@ -3443,6 +3507,147 @@ mod tests { SPATIAL_BBOX_FUNCTION_NAME, SPATIAL_POLYGON_CONTRACT_FUNCTION_NAME, }; + #[test] + fn action_target_policies_append_the_membership_probe() { + let (registry, mut actions) = super::membership_targets::immediate(false); + let mut patch = actions.actions[0].effects[0].clone(); + patch.id = "patch-child".into(); + patch.operation = super::Operation::Patch; + patch.target.binding = crate::model::CompiledPlanTargetBinding::Existing { + input: "child".into(), + }; + actions.actions[0].effects.push(patch); + let ddl = super::generate_ddl_with_actions( + registry.entities(), + registry.physical_names(), + &actions, + ); + let probe = ddl + .functions + .iter() + .find(|f| f.name.starts_with("membership_target_")) + .unwrap(); + assert_eq!( + ddl.functions + .iter() + .filter(|f| f.name.starts_with("membership_target_")) + .count(), + 1 + ); + for (entity, commands) in [ + ( + "child", + vec![ + super::PolicyCommand::Select, + super::PolicyCommand::Insert, + super::PolicyCommand::Update, + ], + ), + ( + "parent", + vec![super::PolicyCommand::Select, super::PolicyCommand::Update], + ), + ] { + let table = ddl + .tables + .iter() + .find(|table| table.entity_id == entity) + .unwrap(); + let field = if entity == "child" { + "parent" + } else { + "directory" + }; + let suffix = format!( + " AND registry_context.{}({})", + quote_identifier(&probe.name), + quote_identifier(®istry.entities()[entity].fields[field].physical_name) + ); + assert_eq!( + table + .policies + .iter() + .map(|policy| policy.command) + .collect::>(), + commands + ); + for expression in table.policies.iter().flat_map(|policy| { + policy + .using_expression + .iter() + .chain(&policy.check_expression) + }) { + assert!( + expression == "false" || expression.ends_with(&suffix), + "{expression}" + ); + } + } + } + + #[test] + fn proposal_target_policies_append_the_membership_probe() { + for automatic in [false, true] { + let source = crate::proposal_hooks::test_model::source(json!([])); + let (registry, actions) = super::membership_targets::proposal(source, automatic); + let lockable = + crate::membership::lockable_membership_tables(registry.entities(), &actions); + assert_eq!(lockable.contains_key(&("clerk", "membership")), !automatic); + let before = super::proposal::target_policies( + ®istry.entities()["target"], + registry.actions(), + ); + let after = super::proposal::target_policies(®istry.entities()["target"], &actions); + assert_eq!(before.len(), after.len()); + let mut caller_checks = 0; + let mut system_checks = 0; + for (base, guarded) in before.iter().zip(&after) { + for (base, guarded) in base + .using_expression + .iter() + .chain(&base.check_expression) + .zip( + guarded + .using_expression + .iter() + .chain(&guarded.check_expression), + ) + { + if base.contains("'actorKind' = 'caller'") { + assert!(guarded.starts_with(&format!( + "({base}) AND registry_context.\"membership_target_" + ))); + caller_checks += 1; + } else { + assert_eq!(base, guarded); + system_checks += usize::from(base.contains("'system-proposal-apply'")); + } + } + } + assert!(caller_checks > 0); + assert_eq!(system_checks > 0, automatic); + } + } + + #[test] + fn the_membership_lock_helper_is_volatile_and_takes_for_share() { + let (registry, actions) = super::membership_targets::immediate(false); + let ddl = super::generate_ddl_with_actions( + registry.entities(), + registry.physical_names(), + &actions, + ); + let name = crate::membership::lock_function_name("registrar", "membership"); + let mut helper = ddl + .statements + .iter() + .filter(|statement| statement.id == format!("registry_context.{name}")); + let sql = &helper.next().unwrap().sql; + assert!(helper.next().is_none()); + assert!(sql.contains("(uuid) RETURNS boolean LANGUAGE plpgsql VOLATILE STRICT SECURITY INVOKER SET search_path = pg_catalog")); + assert!(sql.contains("ORDER BY membership.record_id FOR SHARE; authorized := FOUND")); + } + #[cfg(feature = "runtime")] #[test] fn an_added_required_column_carries_its_requiredness_in_a_separate_statement() { diff --git a/crates/registry-breg/src/history_maintenance.rs b/crates/registry-breg/src/history_maintenance.rs index fce1dc16a2..24342131b5 100644 --- a/crates/registry-breg/src/history_maintenance.rs +++ b/crates/registry-breg/src/history_maintenance.rs @@ -65,6 +65,7 @@ impl From for HistoryMaintenanceError { | PostgresKernelError::DatabaseTransport(_) | PostgresKernelError::FieldPatternSyntax { .. } | PostgresKernelError::FieldPatternExistingRows { .. } + | PostgresKernelError::MembershipDuplicateLiveRows { .. } | PostgresKernelError::FieldEncryptionBlindCollision { .. } | PostgresKernelError::FieldEncryptionRetainedProposalSnapshots { .. } | PostgresKernelError::BlindIndexReindexRowLimit { .. } => Self::InvalidInput, diff --git a/crates/registry-breg/src/history_schema.rs b/crates/registry-breg/src/history_schema.rs index e9454ca13b..26fd486a78 100644 --- a/crates/registry-breg/src/history_schema.rs +++ b/crates/registry-breg/src/history_schema.rs @@ -847,6 +847,7 @@ mod tests { change_control: None, classification: Classification::Restricted, access_requirements: None, + membership: None, access_log: None, disclosure_conditions: Vec::new(), geojson: None, diff --git a/crates/registry-breg/src/hooks.rs b/crates/registry-breg/src/hooks.rs index 98ce539b4a..df7efae22c 100644 --- a/crates/registry-breg/src/hooks.rs +++ b/crates/registry-breg/src/hooks.rs @@ -474,7 +474,12 @@ impl BregDeliverySeams { let batch = match self.prune_terminal_batch().await { Ok(batch) => batch, Err(reason) => { + let code = match reason { + RetentionFailureReason::LockTimeout => "hook.retention.lock_timeout", + _ => "hook.retention.failed", + }; tracing::error!( + code, removed, reason = reason.as_str(), "hook metadata retention failed" diff --git a/crates/registry-breg/src/idempotency.rs b/crates/registry-breg/src/idempotency.rs index 6e152eb4e0..3c752ec7ef 100644 --- a/crates/registry-breg/src/idempotency.rs +++ b/crates/registry-breg/src/idempotency.rs @@ -14,6 +14,7 @@ use uuid::Uuid; use crate::history_reference::SnapshotReference; use crate::model::HttpMethod; use crate::postgres::{ActionClaimContext, ClaimContext, RowBoundaryContext}; +use crate::proposal_messages::Side; use crate::stored_bytes; // Every compiled effect mutates at least one field, so this also bounds the @@ -88,20 +89,31 @@ impl HeldResponse { body: &serde_json::Value, headers: BTreeMap>, ) -> Result { + Self::from_json_if_fits(status, body, headers)?.ok_or(IdempotencyError::InvalidInput) + } + + pub(crate) fn from_json_if_fits( + status: u16, + body: &serde_json::Value, + headers: BTreeMap>, + ) -> Result, IdempotencyError> { if !(200..=299).contains(&status) || headers.values().any(|value| !valid_header_value(value)) { return Err(IdempotencyError::InvalidInput); } let body = canonicalize_json(body).map_err(|_| IdempotencyError::InvalidInput)?; - if body.is_empty() || body.len() > MAX_HELD_BODY_BYTES { + if body.is_empty() { return Err(IdempotencyError::InvalidInput); } - Ok(Self { + if body.len() > MAX_HELD_BODY_BYTES { + return Ok(None); + } + Ok(Some(Self { status, body, headers, - }) + })) } #[must_use] @@ -304,6 +316,7 @@ pub(crate) enum StoredResultMetadata { record_revision: i64, submission_version: i64, result_count: u16, + thread_side: Option, }, ImmediateAction { result_count: u16, @@ -816,15 +829,20 @@ pub(crate) async fn lock_and_load( else { return Ok(None); }; - if row.get::<_, String>(0) != binding.binding_reference { + let result_kind = row.get::<_, String>(1); + let stored_binding = row.get::<_, String>(0); + let thread_side = if result_kind == "proposal" { + matched_proposal_thread_side(&binding.binding_reference, &stored_binding)? + } else if stored_binding == binding.binding_reference { + None + } else { return Err(IdempotencyError::Conflict); - } + }; if row.get::<_, Option>(9).is_some() { // Erasure is permanent. Keep the consumed key reserved and refuse // replay without presenting a transient outage to retrying clients. return Err(IdempotencyError::Conflict); } - let result_kind = row.get::<_, String>(1); if result_kind == "erased" { // Erasure is irreversible, so the consumed key answers with the same // terminal conflict the erased-at path answers with. A transient outage @@ -892,6 +910,7 @@ pub(crate) async fn lock_and_load( record_revision, submission_version, result_count, + thread_side, } } "immediate_action" => { @@ -981,6 +1000,7 @@ pub(crate) async fn insert_result( record_revision, submission_version, result_count, + .. } if !record_reference.is_empty() && *record_revision > 0 && *submission_version > 0 @@ -1019,6 +1039,13 @@ pub(crate) async fn insert_result( }; let caller = &binding.caller; let receipt_retention_days = i32::from(caller.receipt_retention_days); + let binding_reference = match metadata { + StoredResultMetadata::Proposal { + thread_side: Some(side), + .. + } => proposal_thread_binding_reference(&binding.binding_reference, *side), + _ => binding.binding_reference.clone(), + }; let changed = transaction .execute( "INSERT INTO registry_internal.registry_idempotency @@ -1030,7 +1057,7 @@ pub(crate) async fn insert_result( transaction_timestamp() + pg_catalog.make_interval(days => $15))", &[ &binding.key_reference, - &binding.binding_reference, + &binding_reference, &result_kind, &record_revision, &status, @@ -1054,6 +1081,29 @@ pub(crate) async fn insert_result( Ok(()) } +fn proposal_thread_binding_reference(binding: &str, side: Side) -> String { + sha256_reference( + "breg-idempotency-proposal-thread-v1", + &[binding, side.as_str()], + ) +} + +fn matched_proposal_thread_side( + binding: &str, + stored: &str, +) -> Result, IdempotencyError> { + // The spent-key identity is independent of the side. Older receipts + // can still match the request, but cannot prove which side they served. + if binding == stored { + return Ok(None); + } + [Side::Party, Side::Official] + .into_iter() + .find(|side| proposal_thread_binding_reference(binding, *side) == stored) + .map(Some) + .ok_or(IdempotencyError::Conflict) +} + /// Replace exact cached mutation responses that could replay erased historical /// bytes with a minimal tombstone row. The idempotency key and binding remain /// durable so an old retry cannot re-execute the mutation. @@ -1330,6 +1380,24 @@ impl std::fmt::Debug for HeldResponse { mod tests { use super::*; + #[test] + fn proposal_receipt_binding_preserves_the_request_and_recovers_the_original_side() { + let binding = "original-request"; + assert_eq!(matched_proposal_thread_side(binding, binding), Ok(None)); + for side in [Side::Party, Side::Official] { + let bound = proposal_thread_binding_reference(binding, side); + assert_ne!(bound, binding); + assert_eq!( + matched_proposal_thread_side(binding, &bound), + Ok(Some(side)) + ); + assert_eq!( + matched_proposal_thread_side("another-request", &bound), + Err(IdempotencyError::Conflict) + ); + } + } + #[test] fn a_policy_refuses_every_issuer_the_engine_reserves() { for reserved in [ diff --git a/crates/registry-breg/src/immediate_actions.rs b/crates/registry-breg/src/immediate_actions.rs index bb474dc6a7..2255a589d9 100644 --- a/crates/registry-breg/src/immediate_actions.rs +++ b/crates/registry-breg/src/immediate_actions.rs @@ -8,8 +8,10 @@ use serde_json::json; use sha2::{Digest, Sha256}; use crate::contract::{ - AccessProfileSource, ActionEffectSource, ActionSource, ActionValueSource, FieldTypeSource, - Operation, ProjectAccessProfileSource, RowBoundarySource, DECIMAL_BOUNDS_REQUIREMENTS, + AccessProfileSource, ActionEffectSource, ActionInputSource, ActionSource, ActionValueSource, + FieldTypeSource, Operation, ProjectAccessProfileSource, ProposalPolicySource, + ProposalReviewSource, RowBoundarySource, DECIMAL_BOUNDS_REQUIREMENTS, MAXIMUM_ADDITIONAL_FORMS, + MAXIMUM_ADDITIONAL_FORM_INPUTS, }; use crate::diagnostics::Diagnostic; use crate::logical_names::{default_api_name, reserved_logical_name, valid_api_name}; @@ -158,7 +160,7 @@ fn compile_action( "an Action must declare at least one typed input", )); } - let inputs = compile_inputs(action, entities, errors); + let inputs = compile_inputs(&action.inputs, "actions[].inputs[]", entities, errors); let input_map = inputs .iter() .map(|input| (input.id.as_str(), input)) @@ -305,6 +307,21 @@ fn compile_action( errors, ); if let crate::contract::ActionExecutionSource::Proposal { proposal } = &action.execution { + // Submit reads the subject field of the referenced Record, like a + // commit guard reads its field. + if let Some(crate::contract::ProposalSubjectSource { + input, + field: Some(field), + }) = &proposal.subject + { + if let Some(binding) = input_map.get(input.as_str()) { + if let FieldTypeSource::Reference { .. } = &binding.field_type { + if let Some(existing) = target_uses.iter_mut().find(|use_| use_.operation == Operation::Get && matches!(&use_.source, CompiledActionTargetUseSource::Input { input: selected } if selected == input)) { + existing.fields.insert(field.clone()); + } + } + } + } if let Some(context) = &proposal.review_context { for projection in context.fields.values() { if let crate::contract::ProposalContextValueSource::Record { input, field } = @@ -1424,26 +1441,29 @@ fn validate_current_revision( } fn compile_inputs( - action: &ActionSource, + source: &[ActionInputSource], + path: &str, entities: &BTreeMap, errors: &mut Vec, ) -> Vec { let mut ids = BTreeSet::new(); let mut api_names = BTreeSet::new(); let mut inputs = Vec::new(); - for input in &action.inputs { - validate_id(&input.id, "actions[].inputs[].id", errors); + let id_path = format!("{path}.id"); + let api_name_path = format!("{path}.apiName"); + for input in source { + validate_id(&input.id, &id_path, errors); if reserved_logical_name(&input.id) { errors.push(Diagnostic::error( "breg.action.input-id-reserved", - "actions[].inputs[].id", + &id_path, "an action input identifier collides with a reserved Registry field", )); } if !ids.insert(input.id.as_str()) { errors.push(Diagnostic::error( "breg.action.input-id-duplicate", - "actions[].inputs[].id", + &id_path, "action input identifiers must be duplicate-free", )); } @@ -1454,18 +1474,18 @@ fn compile_inputs( if !valid_api_name(&api_name) || reserved_logical_name(&api_name) { errors.push(Diagnostic::error( "breg.action.input-api-name-invalid", - "actions[].inputs[].apiName", + &api_name_path, "an action input API name must be a non-reserved lower camelCase identifier", )); } if !api_names.insert(api_name.clone()) { errors.push(Diagnostic::error( "breg.action.input-api-name-duplicate", - "actions[].inputs[].apiName", + &api_name_path, "action input API names must be unique within the action", )); } - validate_field_type_bounds(&input.field_type, "actions[].inputs[]", errors); + validate_field_type_bounds(&input.field_type, path, errors); if let Some(pattern) = &input.pattern { if !matches!( input.field_type, @@ -1473,13 +1493,13 @@ fn compile_inputs( ) { errors.push(Diagnostic::error( "breg.action.input-pattern-type-unsupported", - "actions[].inputs[].pattern", + format!("{path}.pattern"), "pattern requires a string or text action input", )); } else if !crate::compiler::native_pattern_within_bounds(pattern) { errors.push(Diagnostic::error( "breg.action.input-pattern-bounds-invalid", - "actions[].inputs[].pattern", + format!("{path}.pattern"), "PostgreSQL pattern must be at most 4096 UTF-8 bytes and contain no NUL; syntax is validated by PostgreSQL", )); } @@ -1488,7 +1508,7 @@ fn compile_inputs( if !entities.contains_key(target) { errors.push(Diagnostic::error( "breg.action.input-reference-target-unknown", - "actions[].inputs[].target", + format!("{path}.target"), "an action reference input target does not resolve", )); } @@ -1506,6 +1526,84 @@ fn compile_inputs( inputs } +fn compile_additional_forms( + action_id: &str, + proposal: &ProposalPolicySource, + entities: &BTreeMap, + errors: &mut Vec, +) -> BTreeMap { + if proposal.additional_forms.is_empty() { + return BTreeMap::new(); + } + let path = format!("actions[id={action_id}].execution.proposal.additionalForms"); + if matches!(proposal.review, ProposalReviewSource::None {}) { + errors.push(Diagnostic::error( + "breg.additional-form.review-required", + &path, + "additional forms require review.type: required; configure required review or remove additionalForms", + )); + } + if proposal.additional_forms.len() > MAXIMUM_ADDITIONAL_FORMS { + errors.push(Diagnostic::error( + "breg.additional-form.count", + &path, + &format!("declare at most {MAXIMUM_ADDITIONAL_FORMS} additional forms"), + )); + } + let mut additional_forms = BTreeMap::new(); + for (id, form) in &proposal.additional_forms { + let inputs = format!("{path}.{id}.inputs"); + if !(1..=MAXIMUM_ADDITIONAL_FORM_INPUTS).contains(&form.inputs.len()) { + errors.push(Diagnostic::error( + "breg.additional-form.input-count", + &inputs, + &format!( + "declare from 1 to {MAXIMUM_ADDITIONAL_FORM_INPUTS} inputs per additional form" + ), + )); + } + for (index, input) in form.inputs.iter().enumerate() { + if matches!( + input.field_type, + FieldTypeSource::Reference { .. } + | FieldTypeSource::Crs84Point { .. } + | FieldTypeSource::Crs84Polygon { .. } + | FieldTypeSource::Structured { .. } + | FieldTypeSource::VocabularyCode { .. } + ) { + errors.push(Diagnostic::error( + "breg.additional-form.input-type", + format!("{inputs}[{index}].type"), + "choose boolean, string, text, int64, decimal, date, timestamp, or uuid", + )); + } + if input.pattern.is_some() { + errors.push(Diagnostic::error( + "breg.additional-form.input-pattern", + format!("{inputs}[{index}].pattern"), + "remove the PostgreSQL pattern from the additional-form input", + )); + } + } + let fields = compile_inputs(&form.inputs, &format!("{inputs}[]"), entities, errors); + if !(1..=32).contains(&form.maximum_count) { + errors.push(Diagnostic::error( + "breg.additional-form.maximum-count", + format!("{path}.{id}.maximumCount"), + "allow between 1 and 32 entries per submission", + )); + } + additional_forms.insert( + id.clone(), + crate::model::CompiledAdditionalForm { + maximum_count: form.maximum_count, + inputs: fields, + }, + ); + } + additional_forms +} + /// Binds each file an Action request carries to the record slot one create /// effect fills. Only an immediate fixed-plan Action without Evidence or a /// timer can carry files: every other immediate path has no request to take @@ -2433,7 +2531,8 @@ fn compile_permissions( "Action permissions support only the invoke operation", )); } - let target_locks = compile_permission_targets(entities, profile, grant, errors); + let target_locks = + compile_permission_targets(entities, profile, grant, target_uses, errors); validate_permission_covers_uses(&target_locks, target_uses, errors); let targets = discriminate_permission_targets(&target_locks, target_uses, errors); for result in grant.results.iter() { @@ -2487,12 +2586,14 @@ fn validate_action_permission_sources( struct PermissionTargetLock { entity_id: String, row_boundaries: Vec, + membership_boundaries: Vec, } fn compile_permission_targets( entities: &BTreeMap, profile: &ProjectAccessProfileSource, grant: &crate::contract::ActionPermissionSource, + target_uses: &[CompiledActionTargetUse], errors: &mut Vec, ) -> Vec { let mut seen = BTreeSet::new(); @@ -2526,15 +2627,63 @@ fn compile_permission_targets( "project.accessProfiles[].permissions.actions[].targets", errors, ); + let writes = target_uses.iter().any(|use_| { + use_.entity_id == target.entity && crate::membership::is_record_write(use_.operation) + }); + let membership_boundaries = compile_target_memberships( + entities, profile, entity, &target.row_boundaries, &target.membership_row_boundaries, + true, + writes, + &format!("accessProfiles[id={}].permissions.actions[action={}].targets[recordType={}].rowBoundaries", profile.id, grant.action, target.entity), + errors, + ); targets.push(PermissionTargetLock { entity_id: target.entity.clone(), row_boundaries: target.row_boundaries.clone(), + membership_boundaries, }); } targets.sort_by(|left, right| left.entity_id.cmp(&right.entity_id)); targets } +#[allow(clippy::too_many_arguments)] +fn compile_target_memberships( + entities: &BTreeMap, + profile: &ProjectAccessProfileSource, + entity: &CompiledEntity, + row_boundaries: &[RowBoundarySource], + entries: &[crate::contract::MembershipRowBoundarySource], + write_grant: bool, + writes_record: bool, + location: &str, + errors: &mut Vec, +) -> Vec { + crate::membership::validate_write_admission( + profile.required_scopes.is_empty(), + profile.requester_clients.is_empty(), + &profile.principal_claim, + write_grant, + writes_record && entity.membership.is_some(), + row_boundaries, + !entries.is_empty(), + location, + errors, + ); + entries + .iter() + .filter_map( + |entry| match crate::membership::resolve_entry(entry, entities, location) { + Ok((physical, _)) => Some(physical), + Err(error) => { + errors.push(error); + None + } + }, + ) + .collect() +} + fn discriminate_permission_targets( target_locks: &[PermissionTargetLock], target_uses: &[CompiledActionTargetUse], @@ -2553,6 +2702,7 @@ fn discriminate_permission_targets( operation: target_use.operation, source: target_use.source.clone(), row_boundaries: target_lock.row_boundaries.clone(), + membership_boundaries: target_lock.membership_boundaries.clone(), }); } if !matched { @@ -3027,6 +3177,178 @@ pub(crate) fn hex_lower(bytes: &[u8]) -> String { out } +fn party_label(party: Option) -> &'static str { + match party { + Some(crate::contract::ProposalParty::Owner) => "`party: owner`", + Some(crate::contract::ProposalParty::Subject) => "`party: subject`", + None => "an entry without `party`", + } +} + +/// The operations a subject entry may hold. The subject follows work someone +/// else filed: it reads, answers, adds files and withdraws, and never changes +/// what was filed. +const SUBJECT_OPERATIONS: [crate::contract::ProposalOperation; 7] = [ + crate::contract::ProposalOperation::Get, + crate::contract::ProposalOperation::List, + crate::contract::ProposalOperation::GetReviewStatus, + crate::contract::ProposalOperation::Answer, + crate::contract::ProposalOperation::Add, + crate::contract::ProposalOperation::Message, + crate::contract::ProposalOperation::Cancel, +]; + +fn validate_proposal_subject( + action: &ActionSource, + entities: &BTreeMap, + subject: &crate::contract::ProposalSubjectSource, + errors: &mut Vec, +) { + let path = format!("actions[id={}].execution.proposal.subject", action.id); + let Some(input) = action.inputs.iter().find(|input| input.id == subject.input) else { + errors.push(Diagnostic::error( + "breg.proposal.subject-input-unknown", + format!("{path}.input"), + &format!( + "the subject input `{}` is not an input of Action `{}`", + subject.input, action.id + ), + )); + return; + }; + if !input.required { + errors.push(Diagnostic::error( + "breg.proposal.subject-input-optional", + format!("{path}.input"), + &format!( + "the subject input `{}` must be required, so every submitted Proposal names its subject", + input.id + ), + )); + } + match (&subject.field, &input.field_type) { + ( + None, + FieldTypeSource::String { .. } | FieldTypeSource::Text { .. } | FieldTypeSource::Uuid, + ) => {} + (Some(field), FieldTypeSource::Reference { target, .. }) => { + let plaintext = entities + .get(target) + .and_then(|entity| entity.fields.get(field)) + .is_some_and(|declared| { + declared.encryption.is_none() + && matches!( + declared.field_type, + FieldTypeSource::String { .. } | FieldTypeSource::Text { .. } + ) + }); + if !plaintext { + errors.push(Diagnostic::error( + "breg.proposal.subject-field-type", + format!("{path}.field"), + &format!( + "the subject field `{field}` must be a plaintext string or text field of Record type `{target}`" + ), + )); + } + } + (None, _) => errors.push(Diagnostic::error( + "breg.proposal.subject-input-type", + format!("{path}.input"), + &format!( + "the subject input `{}` must be a string, text or uuid input; to read the subject from a referenced Record, add `field`", + input.id + ), + )), + (Some(_), _) => errors.push(Diagnostic::error( + "breg.proposal.subject-input-type", + format!("{path}.input"), + &format!( + "a subject `field` is read through a reference input, and `{}` is not one", + input.id + ), + )), + } +} + +fn validate_party_grant( + action: &ActionSource, + profile: &ProjectAccessProfileSource, + grant: &crate::contract::ProposalPermissionSource, + subject_declared: bool, + errors: &mut Vec, +) { + use crate::contract::{ProposalOperation, ProposalParty}; + let path = format!( + "accessProfiles[id={}].permissions.proposals[action={}]", + profile.id, action.id + ); + if grant.submits_for.is_some() + && (!grant.operations.contains(&ProposalOperation::Submit) || !subject_declared) + { + errors.push(Diagnostic::error( + "breg.proposal.submits-for-invalid", + format!("{path}.submitsFor"), + &format!( + "`submitsFor` lets a Submit name someone else as the subject: it needs `submit` in the same entry and `execution.proposal.subject` on Action `{}`", + action.id + ), + )); + } + if grant.party != Some(ProposalParty::Subject) { + return; + } + if !subject_declared { + errors.push(Diagnostic::error( + "breg.proposal.subject-undeclared", + format!("{path}.party"), + &format!( + "access profile `{}` holds a `party: subject` entry, but Action `{}` declares no `execution.proposal.subject`", + profile.id, action.id + ), + )); + } + let forbidden = grant + .operations + .iter() + .filter(|operation| !SUBJECT_OPERATIONS.contains(operation)) + .map(|operation| operation.as_str()) + .collect::>(); + if !forbidden.is_empty() { + errors.push(Diagnostic::error( + "breg.proposal.subject-operation-forbidden", + format!("{path}.operations"), + &format!( + "a `party: subject` entry cannot hold {}. The subject may hold only get, list, get-review-status, answer, add, message and cancel", + forbidden.join(", ") + ), + )); + } + if !matches!( + profile.actor_kind, + None | Some(crate::contract::ActorKindSource::Human) + ) { + errors.push(Diagnostic::error( + "breg.proposal.permission-invalid", + format!("{path}.party"), + &format!( + "a `party: subject` entry is for people: access profile `{}` must set `actorKind: human` or leave it unset", + profile.id + ), + )); + } + if profile.required_scopes.is_empty() + && profile.requester_clients.is_empty() + && profile.principal_claim != "sub" + { + errors.push(Diagnostic::error( + "breg.access.open-subject-principal-not-sub", + format!("accessProfiles[id={}].principalClaim", profile.id), + "An open profile with a `party: subject` entry must set principalClaim to sub.", + )); + } +} + fn compile_execution( action: &ActionSource, entities: &BTreeMap, @@ -3040,6 +3362,7 @@ fn compile_execution( let ActionExecutionSource::Proposal { proposal } = &action.execution else { return CompiledActionExecution::Immediate; }; + let additional_forms = compile_additional_forms(&action.id, proposal, entities, errors); let attachment_field_names = action .inputs .iter() @@ -3126,6 +3449,25 @@ fn compile_execution( } } }; + let subject = proposal.subject.as_ref().map(|subject| { + validate_proposal_subject(action, entities, subject, errors); + subject.clone() + }); + let messages = proposal.messages.as_ref().map(|messages| { + if !(1..=MAX_PROPOSAL_MESSAGE_COUNT).contains(&messages.maximum_count) { + errors.push(Diagnostic::error( + "breg.proposal.message-count-invalid", + format!( + "actions[id={}].execution.proposal.messages.maximumCount", + action.id + ), + &format!("a Proposal thread holds 1 through {MAX_PROPOSAL_MESSAGE_COUNT} messages"), + )); + } + CompiledProposalMessages { + maximum_count: messages.maximum_count, + } + }); let mut permissions = Vec::new(); for profile in profiles { for grant in profile @@ -3135,6 +3477,26 @@ fn compile_execution( .filter(|grant| grant.action == action.id) { crate::consent::validate_proposal_permission(profile, grant, entities, errors); + validate_party_grant(action, profile, grant, subject.is_some(), errors); + if grant.operations.contains(&ProposalOperation::Message) + && (messages.is_none() + || matches!( + profile.actor_kind, + Some(ActorKindSource::Agent | ActorKindSource::Service) + )) + { + errors.push(Diagnostic::error( + "breg.proposal.message-grant-invalid", + format!( + "accessProfiles[id={}].permissions.proposals[action={}].operations", + profile.id, action.id + ), + &format!( + "`message` reads and writes the thread between people: Action `{}` must declare `execution.proposal.messages`, and access profile `{}` must set `actorKind: human` or leave it unset", + action.id, profile.id + ), + )); + } if application.is_automatic() && grant.operations.iter().any(|operation| { matches!( @@ -3163,7 +3525,8 @@ fn compile_execution( || !grant .operations .contains(&ProposalOperation::GetReviewStatus) - || grant.ownership.is_some() + || grant.party.is_some() + || grant.submits_for.is_some() || !grant.targets.is_empty() || !grant.readable_context_fields.is_empty() || !grant.readable_inputs.is_empty() @@ -3185,12 +3548,12 @@ fn compile_execution( || !grant .operations .contains(&ProposalOperation::GetReviewStatus) - || grant.ownership != Some(ProposalOwnership::Caller)) + || grant.party.is_none()) { errors.push(Diagnostic::error( "breg.proposal.review-progress-grant-invalid", "accessProfiles[].permissions.proposals[].readableReviewProgress", - "review progress requires caller-owned GetReviewStatus authority for an Action with required review, and cannot be enabled on the named review-authority service grant", + "review progress requires party-bound GetReviewStatus authority for an Action with required review, and cannot be enabled on the named review-authority service grant", )); } @@ -3202,21 +3565,42 @@ fn compile_execution( ProposalOperation::Edit | ProposalOperation::GetReviewContext ) }) || (grant.operations.contains(&ProposalOperation::Edit) - && grant.ownership != Some(ProposalOwnership::Caller))) + && grant.party != Some(ProposalParty::Owner))) { errors.push(Diagnostic::error("breg.proposal.standing-agent-operation-forbidden", "accessProfiles[].permissions.proposals", "an agent without a task grant can only start or edit caller-owned draft Proposals and read an explicitly bounded review context; other operations require task-grant or human authority")); } - if grant.operations.is_empty() - || permissions - .iter() - .any(|entry: &CompiledProposalPermission| entry.profile_id == profile.id) - { + if grant.operations.is_empty() { errors.push(Diagnostic::error( "breg.proposal.permission-invalid", "accessProfiles[].permissions.proposals", "Proposal grants require operations and one entry per Action", )); } + // One entry per party; an entry bound to no party governs the + // whole Action for its profile, so it stands alone. + if permissions + .iter() + .any(|entry: &CompiledProposalPermission| { + entry.profile_id == profile.id + && (entry.party == grant.party + || entry.party.is_none() + || grant.party.is_none()) + }) + { + errors.push(Diagnostic::error( + "breg.proposal.permission-invalid", + format!( + "accessProfiles[id={}].permissions.proposals[action={}]", + profile.id, action.id + ), + &format!( + "access profile `{}` holds more than one Proposal entry for Action `{}` where the second is {}. Hold at most one entry for each party (`party: owner`, `party: subject`), and no entry without `party` beside them", + profile.id, + action.id, + party_label(grant.party), + ), + )); + } if grant .operations .contains(&ProposalOperation::GetApplicationActor) @@ -3259,9 +3643,27 @@ fn compile_execution( "accessProfiles[].permissions.proposals[].targets", errors, ); + let write_grant = grant + .operations + .iter() + .copied() + .any(crate::membership::is_proposal_write); + let writes = write_grant + && target_uses.iter().any(|use_| { + use_.entity_id == target.record_type + && crate::membership::is_record_write(use_.operation) + }); + let membership_boundaries = compile_target_memberships( + entities, profile, entity, &target.row_boundaries, &target.membership_row_boundaries, + write_grant, + writes, + &format!("accessProfiles[id={}].permissions.proposals[action={}].targets[recordType={}].rowBoundaries", profile.id, grant.action, target.record_type), + errors, + ); targets.push(CompiledProposalTargetPermission { entity_id: target.record_type.clone(), row_boundaries: target.row_boundaries.clone(), + membership_boundaries, }); } if !authority_status @@ -3287,6 +3689,44 @@ fn compile_execution( "context grants must name fields in this Action's declared review context", )); } + // Form values reach only a person reading for themselves; a + // profile no such person reads through may not hold a form field. + let form_fields = proposal + .review_context + .as_ref() + .map(|context| { + context + .fields + .iter() + .filter(|(_, source)| { + matches!( + source, + crate::contract::ProposalContextValueSource::AdditionalForm { .. } + ) + }) + .map(|(name, _)| name.clone()) + .collect::>() + }) + .unwrap_or_default(); + if (profile.task_grant.is_some() + || matches!( + profile.actor_kind, + Some(ActorKindSource::Agent | ActorKindSource::Service) + )) + && !grant.readable_context_fields.is_disjoint(&form_fields) + { + errors.push(Diagnostic::error( + "breg.additional-form.context-reader-invalid", + format!( + "accessProfiles[id={}].permissions.proposals[action={}].readableContextFields", + profile.id, action.id + ), + &format!( + "a review-context field that shows an additional form is served only to a person reading for themselves: access profile `{}` is an agent, service or task-grant profile and may not read it", + profile.id + ), + )); + } if grant .operations .contains(&ProposalOperation::GetTaskGrantContext) @@ -3409,6 +3849,25 @@ fn compile_execution( "attachment grants must name declared slots and require Get for reads, Edit for attachment writes, or Add for additions", )); } + if grant + .readable_forms + .iter() + .any(|id| !additional_forms.contains_key(id)) + || grant + .writable_forms + .iter() + .any(|id| !additional_forms.contains_key(id)) + || (!grant.readable_forms.is_empty() + && !grant.operations.contains(&ProposalOperation::Get)) + || (!grant.writable_forms.is_empty() + && !grant.operations.contains(&ProposalOperation::Add)) + { + errors.push(Diagnostic::error( + "breg.additional-form.grant-invalid", + "accessProfiles[].permissions.proposals", + "form grants must name declared forms and require Get for reads or Add for writes", + )); + } permissions.push(CompiledProposalPermission { profile_id: profile.id.clone(), review_authority: grant.review_authority.clone(), @@ -3421,12 +3880,15 @@ fn compile_execution( required_scopes: profile.required_scopes.as_set().clone(), required_purposes: profile.required_purposes.as_set().clone(), operations: grant.operations.as_set().clone(), - ownership: grant.ownership, + party: grant.party, + submits_for_anyone: grant.submits_for == Some(ProposalSubmitsFor::Anyone), targets, readable_context_fields: grant.readable_context_fields.as_set().clone(), readable_inputs: grant.readable_inputs.as_set().clone(), readable_attachments: grant.readable_attachments.as_set().clone(), writable_attachments: grant.writable_attachments.as_set().clone(), + readable_forms: grant.readable_forms.as_set().clone(), + writable_forms: grant.writable_forms.as_set().clone(), writable_inputs: grant .writable_inputs .as_ref() @@ -3458,6 +3920,16 @@ fn compile_execution( } use crate::contract::ProposalContextValueSource; let valid = match value { + ProposalContextValueSource::AdditionalForm { form } => { + if !additional_forms.contains_key(form) { + errors.push(Diagnostic::error( + "breg.additional-form.context-unknown", + "actions[].execution.proposal.reviewContext.fields", + "the review-context field must name a declared form", + )); + } + true + } ProposalContextValueSource::Document { slot } => attachments.contains_key(slot), ProposalContextValueSource::Additions { slot } => proposal .additions @@ -3518,8 +3990,11 @@ fn compile_execution( review_context: proposal.review_context.clone(), attachments, additions: proposal.additions.clone(), + additional_forms, promotions: Vec::new(), permissions, + subject, + messages, }, } } @@ -3550,12 +4025,17 @@ pub fn migration_review_revision(action: &CompiledAction) -> String { guard.label = None; } if let crate::model::CompiledActionExecution::Proposal { proposal } = &mut action.execution { + // Form declarations may change without reinterpreting a frozen Action. + proposal.additional_forms.clear(); proposal .permissions .sort_by(|a, b| a.profile_id.cmp(&b.profile_id)); for hook in &mut proposal.hooks { hook.display = Default::default(); } + // The thread changes no frozen work: requests in flight get it at + // activation. + proposal.messages = None; if let Some(grant) = &mut proposal.system_apply_grant { grant.revision.clear(); grant.action_revision.clear(); @@ -3834,6 +4314,11 @@ pub(crate) fn definition_revision( if let Some(slot) = &proposal.additions { policy["additions"] = json!(slot); } + // The subject decides who may follow frozen work, so declaring + // or moving it changes the Action. Omitted when undeclared. + if let Some(subject) = &proposal.subject { + policy["subject"] = json!(subject); + } // Promotions change what an approved Proposal writes, so they are // part of the Action's identity. Omitting an empty list keeps the // revision of every Action without promotions unchanged. @@ -3875,3 +4360,86 @@ pub(crate) fn definition_revision( )) ) } + +#[cfg(test)] +mod membership_target_tests { + use super::*; + use crate::compiler::{compile_project, CompileProfile}; + use crate::contract::{parse_project_json, MembershipRowBoundarySource}; + use serde_json::json; + + fn project() -> (crate::contract::RegistryProject, crate::CompiledRegistry) { + let mut source = crate::proposal_hooks::test_model::source(json!([])); + let fixture: serde_json::Value = serde_json::from_str(include_str!( + "../../../products/breg/fixtures/organization-membership-access/registry.yaml" + )) + .unwrap(); + for id in ["membership", "organization"] { + source["recordTypes"][id] = fixture["recordTypes"][id].clone(); + source["recordTypes"][id]["primaryDataset"] = json!("directory"); + } + source["recordTypes"]["membership"]["accessRequirements"]["requiredScopes"] = + json!(["proposal:manage"]); + source["recordTypes"]["target"]["fields"] + .as_array_mut() + .unwrap() + .push(json!({"id":"organization","type":"reference","target":"organization","classification":"internal"})); + let project = parse_project_json(&serde_json::to_vec(&source).unwrap()).unwrap(); + let registry = compile_project(&project, &[], CompileProfile::Authoring).unwrap(); + (project, registry) + } + + fn entry() -> MembershipRowBoundarySource { + MembershipRowBoundarySource { + field: "organization".into(), + membership: "membership".into(), + } + } + + #[test] + fn an_action_target_membership_entry_reaches_every_discriminated_use() { + let (mut project, registry) = project(); + let profile = &mut project.access_profiles[0]; + profile.permissions.actions[0].targets[0].membership_row_boundaries = vec![entry()]; + let uses = ®istry.actions().actions[0].target_uses; + let mut errors = Vec::new(); + let locks = compile_permission_targets( + registry.entities(), + profile, + &profile.permissions.actions[0], + uses, + &mut errors, + ); + let targets = discriminate_permission_targets(&locks, uses, &mut errors); + assert!(targets.len() > 1); + assert!(targets.iter().all(|target| { + target.membership_boundaries.len() == 1 + && target.membership_boundaries[0].membership_entity == "membership" + })); + assert!(errors.is_empty(), "{errors:?}"); + } + + #[test] + fn a_proposal_target_membership_entry_reaches_the_compiled_target() { + let (mut project, registry) = project(); + let action = ®istry.actions().actions[0]; + project.access_profiles[0].permissions.proposals[0].targets[0].membership_row_boundaries = + vec![entry()]; + let mut errors = Vec::new(); + let execution = compile_execution( + &project.actions[0], + registry.entities(), + &project.access_profiles, + &project.review_authorities, + &action.target_uses, + &mut errors, + ); + let crate::model::CompiledActionExecution::Proposal { proposal } = execution else { + panic!("expected a Proposal"); + }; + let compiled = &proposal.permissions[0].targets[0].membership_boundaries; + assert_eq!(compiled.len(), 1); + assert_eq!(compiled[0].membership_entity, "membership"); + assert!(errors.is_empty(), "{errors:?}"); + } +} diff --git a/crates/registry-breg/src/ingestion_store.rs b/crates/registry-breg/src/ingestion_store.rs index 117c42d3e4..7edaf31c01 100644 --- a/crates/registry-breg/src/ingestion_store.rs +++ b/crates/registry-breg/src/ingestion_store.rs @@ -1619,7 +1619,7 @@ mod tests { {"id":"serial-code","apiName":"serialNumber","type":"string","maximumLength":64,"classification":"internal"} ] }}, - "accessProfiles":{"operator": {"default":true,"principalClaim":"registry_principal","requiredScopes":"unrestricted", + "accessProfiles":{"operator": {"default":true,"principalClaim":"registry_principal","requiredScopes":["records:write"], "requiredPurposes":["review"], "permissions":{"records":[{ "recordType":"entry","operations":["create"], @@ -1746,7 +1746,7 @@ mod tests { "datasets":{{"test-dataset": {{}}}},"recordTypes":{{"entry":{{"primaryDataset":"test-dataset","route":"entries","mutationMode":"mutable","classification":"internal", "fields":[{fields}] }}}}, - "accessProfiles":{{"operator":{{"default":true,"principalClaim":"registry_principal","requiredScopes":"unrestricted", + "accessProfiles":{{"operator":{{"default":true,"principalClaim":"registry_principal","requiredScopes":["records:write"], "requiredPurposes":["review"], "permissions":{{"records":[{{ "recordType":"entry","operations":["create"], diff --git a/crates/registry-breg/src/lib.rs b/crates/registry-breg/src/lib.rs index fd492a52dd..3a821a25f2 100644 --- a/crates/registry-breg/src/lib.rs +++ b/crates/registry-breg/src/lib.rs @@ -150,11 +150,14 @@ pub mod problem_location; pub mod proposal_events; pub mod proposal_hooks; #[cfg(feature = "runtime")] +mod proposal_messages; +#[cfg(feature = "runtime")] mod proposal_prepare; #[cfg(feature = "runtime")] pub mod proposal_retention; #[cfg(feature = "runtime")] mod proposal_store; +pub(crate) mod proposal_subject; pub mod proposal_workflow; pub mod query; #[cfg(feature = "runtime")] diff --git a/crates/registry-breg/src/lifecycle.rs b/crates/registry-breg/src/lifecycle.rs index d2c8b21ad2..ff86883f07 100644 --- a/crates/registry-breg/src/lifecycle.rs +++ b/crates/registry-breg/src/lifecycle.rs @@ -91,6 +91,8 @@ pub(crate) struct ProposalTurnContext { pub(crate) submission_blocked: bool, pub(crate) review: ProposalReviewProgress, pub(crate) ask_open: bool, + /// An office message on the thread the party has not read. + pub(crate) message_unread: bool, pub(crate) application: ProposalApplicationProgress, } @@ -297,6 +299,7 @@ impl ProposalTurn { #[derive(Clone, Copy)] enum TurnCondition { Always, + MessageUnread, SubmittedParty, SubmittedOfficial, SubmittedNobody, @@ -306,14 +309,17 @@ impl TurnCondition { const fn description(self) -> &'static str { match self { Self::Always => "Always while the Proposal is in this state.", + Self::MessageUnread => { + "An office message on the thread is unread by the party. This changes the turn only, never the status." + } Self::SubmittedParty => { "The submission package is blocked; Review is pending or retrying with an open ask; Review ended without a usable approval; or, after approval or when Review is not required, application is not manual and is blocked without recovery retry." } Self::SubmittedOfficial => { - "The submission package is not blocked, and either Review is pending or being retried without an open ask, or, after approval or when Review is not required, application is manual or is blocked with recovery retry." + "The submission package is not blocked, no office message is unread by the party, and either Review is pending or being retried without an open ask, or, after approval or when Review is not required, application is manual or is blocked with recovery retry." } Self::SubmittedNobody => { - "The submission package is not blocked, Review is approved or not required, and application is neither manual nor blocked, including queued, running, or unreported application status." + "The submission package is not blocked, no office message is unread by the party, Review is approved or not required, and application is neither manual nor blocked, including queued, running, or unreported application status." } } } @@ -322,6 +328,7 @@ impl TurnCondition { fn matches(self, context: ProposalTurnContext) -> bool { match self { Self::Always => true, + Self::MessageUnread => context.message_unread, Self::SubmittedParty => submitted_turn(context) == ProposalTurn::Party, Self::SubmittedOfficial => submitted_turn(context) == ProposalTurn::Official, Self::SubmittedNobody => submitted_turn(context) == ProposalTurn::Nobody, @@ -371,6 +378,12 @@ const DRAFT_TURN_RULES: &[TurnRule] = &[TurnRule { condition: TurnCondition::Always, }]; const SUBMITTED_TURN_RULES: &[TurnRule] = &[ + // An unread office message is something for the party to read. The + // status follows the rules after it, so no command opens or closes. + TurnRule { + turn: ProposalTurn::Party, + condition: TurnCondition::MessageUnread, + }, // Package blocking precedes Review and application progress in the runtime. TurnRule { turn: ProposalTurn::Party, @@ -428,9 +441,16 @@ pub(crate) fn proposal_status_and_turn( .find(|rule| rule.condition.matches(context)) .expect("every Proposal state and context has a turn") .turn; + // The status follows whose move it is, which an unread message is not. + let moving = proposal_turn_rules(state) + .iter() + .filter(|rule| !matches!(rule.condition, TurnCondition::MessageUnread)) + .find(|rule| rule.condition.matches(context)) + .expect("every Proposal state and context has a turn") + .turn; let status = proposal_status_rules(state) .iter() - .find(|(_, condition)| condition.matches(context, turn)) + .find(|(_, condition)| condition.matches(context, moving)) .expect("every Proposal state and context has a status") .0; (status, turn) @@ -750,9 +770,11 @@ mod tests { R::Answered, R::Ended, ] { - for ask_open in [false, true] { + for (ask_open, message_unread) in + [(false, false), (true, false), (false, true), (true, true)] + { for application in [A::Manual, A::BlockedRetry, A::BlockedOther, A::Other] { - let expected = match state { + let mut expected = match state { S::Draft => (0, "draft", "party"), S::Cancelled => (1, "cancelled", "nobody"), S::Applied => (2, "applied", "nobody"), @@ -783,10 +805,16 @@ mod tests { }, }, }; + // An unread office message is the party's turn + // on any open submission, and never a status. + if state == S::Submitted && message_unread { + expected.2 = "party"; + } let context = ProposalTurnContext { submission_blocked: blocked, review, ask_open, + message_unread, application, }; let (status, turn) = proposal_status_and_turn(state, context); @@ -800,6 +828,7 @@ mod tests { assert_eq!( turn.as_str() == "party", matches!(status.as_str(), "draft" | "awaiting-party") + || (state == S::Submitted && message_unread) ); for terminal in ["applied", "rejected", "cancelled"] { assert_eq!( @@ -810,10 +839,12 @@ mod tests { if status.as_str() == "approved" { assert_eq!(review, R::Approved); } - if status.as_str() == "in-review" { + if status.as_str() == "in-review" && !message_unread { assert_eq!(turn.as_str(), "official"); } - if matches!(status.as_str(), "approved" | "processing") { + if matches!(status.as_str(), "approved" | "processing") + && !message_unread + { assert!(matches!(turn.as_str(), "official" | "nobody")); } } @@ -875,6 +906,7 @@ mod tests { submission_blocked, review, ask_open: false, + message_unread: false, application, }, ) diff --git a/crates/registry-breg/src/membership.rs b/crates/registry-breg/src/membership.rs index 522bf756f4..ea76478a21 100644 --- a/crates/registry-breg/src/membership.rs +++ b/crates/registry-breg/src/membership.rs @@ -1,27 +1,65 @@ // SPDX-License-Identifier: Apache-2.0 //! One-hop current membership checks over governed stored records. -use std::collections::BTreeMap; -#[cfg(feature = "runtime")] -use std::collections::BTreeSet; +use std::collections::{BTreeMap, BTreeSet}; -use crate::contract::{EntitySource, FieldTypeSource, Operation}; +use crate::contract::{ + ActionPlanSource, ActionSource, EntitySource, ExpandedMembershipBoundarySource, + FieldTypeSource, MembershipBoundarySource, MembershipDeclarationSource, + MembershipRowBoundarySource, Operation, ProposalOperation, RegistryProject, RowBoundarySource, +}; use crate::diagnostics::Diagnostic; use crate::generated_ddl::{quote_identifier, quote_literal}; -use crate::model::{CompiledEntity, CompiledMembershipBoundary}; +use crate::model::{ + CompiledActionExecution, CompiledActionInventory, CompiledEntity, CompiledMembershipBoundary, +}; use crate::physical_names::hex_prefix; use sha2::{Digest, Sha256}; -pub(crate) fn validate(entities: &BTreeMap, errors: &mut Vec) { +/// The canonical identifier every Record type carries. As a membership +/// boundary field it names the protected row's own `record_id`. +pub(crate) const CANONICAL_ID: &str = "id"; + +pub(crate) fn validate( + project: &RegistryProject, + actions: &BTreeMap, + entities: &BTreeMap, + errors: &mut Vec, +) { for entity in entities.values() { + validate_declaration(project, entity, entities, errors); for profile in &entity.access_profiles { - if profile.membership_boundaries.is_empty() { - continue; - } let location = format!( - "recordTypes[id={}].accessProfiles[id={}].membershipBoundaries", + "recordTypes[id={}].accessProfiles[id={}].rowBoundaries", entity.id, profile.id ); + let has_membership = !profile.membership_boundaries.is_empty(); + let writes = profile.operations.iter().copied().any(is_record_write); + let writes_membership = entity.membership.is_some() + && (writes + || profile.operations.contains(&Operation::Import) + || profile.operations.contains(&Operation::Batch)); + validate_write_admission( + profile.required_scopes.is_empty(), + profile.requester_clients.is_empty(), + &profile.principal_claim, + writes, + writes_membership, + &profile.row_boundaries, + has_membership, + &location, + errors, + ); + if !has_membership { + continue; + } + if profile.operations.contains(&Operation::Import) { + errors.push(Diagnostic::error( + "breg.access.membership-import-unsupported", + &location, + "Import grants cannot use a membership entry in rowBoundaries.", + )); + } if profile.operations.iter().any(|operation| { !matches!( operation, @@ -30,112 +68,42 @@ pub(crate) fn validate(entities: &BTreeMap, errors: &mut V | Operation::List | Operation::Revisions | Operation::Snapshot + | Operation::Create + | Operation::Patch + | Operation::Tombstone + | Operation::Batch + | Operation::Import + | Operation::Reference ) - }) || !profile.writable_fields.is_empty() + }) || (!profile.writable_fields.is_empty() + && !writes + && !profile.operations.contains(&Operation::Import)) { - errors.push(Diagnostic::error("breg.access.membership-read-only", &location, - "membership boundaries support get, lookup, list, revisions and snapshot only; use a separate directly authorized profile for writes and proposal application")); + refuse_membership_write(&location, errors); } if profile.spatial_queries.is_some() { errors.push(Diagnostic::error("breg.access.membership-spatial-unsupported", &location, "spatial bbox uses a separate database authority role; use a directly authorized bbox profile or ordinary membership-filtered reads")); } - if profile.membership_boundaries.len() > 8 { - errors.push(Diagnostic::error( - "breg.access.membership-limit", - &location, - "declare at most eight one-hop membership boundaries", - )); - } - for (index, boundary) in profile.membership_boundaries.iter().enumerate() { - let path = format!("{location}[{index}]"); - if profile.membership_boundaries[..index].contains(boundary) { - errors.push(Diagnostic::error( - "breg.access.membership-duplicate", - &path, - "each membership boundary must be unique", - )); - } - let Some(membership) = entities.get(&boundary.membership_entity) else { - errors.push(Diagnostic::error( - "breg.access.membership-entity-unknown", - &path, - "membershipRecordType must name a governed Record type", - )); - continue; - }; - let root_field = entity - .fields - .iter() - .find(|field| field.id == boundary.field); - let key_field = membership - .fields - .iter() - .find(|field| field.id == boundary.membership_key_field); - let matching = match (root_field, key_field) { - (Some(root), Some(key)) => matches!((&root.field_type, &key.field_type), - (FieldTypeSource::Reference { target: a, .. }, FieldTypeSource::Reference { target: b, .. }) if a == b), - _ => false, - }; - if !matching { - errors.push(Diagnostic::error( - "breg.access.membership-key-type", - &path, - "field and membershipKeyField must be stored references to the same entity", - )); - } - if !membership.fields.iter().any(|field| { - field.id == boundary.principal_field - && matches!( - field.field_type, - FieldTypeSource::String { .. } | FieldTypeSource::Text { .. } - ) - }) { - errors.push(Diagnostic::error("breg.access.membership-principal-type", &path, - "principalField must be a stored string or text field matching the verified principal")); - } - // The membership predicate compares the principal column to the - // verified plaintext principal, so ciphertext can never match. - if membership - .fields - .iter() - .any(|field| field.id == boundary.principal_field && field.encrypted) - { - errors.push(Diagnostic::error("breg.access.membership-principal-encrypted", &path, - "principalField must be a plaintext stored field; an encrypted field cannot match the verified principal")); - } - if !membership.fields.iter().any(|field| { - field.id == boundary.active_field - && matches!(field.field_type, FieldTypeSource::Boolean) - }) { - errors.push(Diagnostic::error("breg.access.membership-active-type", &path, - "activeField must be a stored Boolean field; only true memberships authorize access")); - } - // A membership source is a leaf authorization fact. Its own RLS must - // never traverse back into the protected root, even through an OR arm. - if membership.id == entity.id - || membership - .access_profiles - .iter() - .any(|candidate| !candidate.membership_boundaries.is_empty()) - || entities.values().any(|candidate| { - candidate - .read_paths - .iter() - .any(|path| path.through == membership.id || path.to == membership.id) - }) - { - errors.push(Diagnostic::error("breg.access.membership-source-recursive", &path, - "membership sources must be ordinary leaf entities without membership boundaries or incoming read paths; use a separate membership fact entity")); - } - if let Some(requirements) = &membership.access_requirements { - let mut processing = requirements.clone(); - processing.row_boundaries.clear(); - crate::access::check_profile(&processing, profile, &path, errors); - if !requirements.row_boundaries.is_empty() { - errors.push(Diagnostic::error("breg.access.membership-source-row-requirement", &path, - "membership source row requirements cannot be inferred from a root profile; use its mandatory scopes and purposes with the fixed principal membership predicate")); - } + let entries = profile + .membership_boundaries + .iter() + .map(MembershipBoundarySource::entry) + .collect::>(); + let writes_rows = writes + || profile.operations.contains(&Operation::Batch) + || profile.operations.contains(&Operation::Import); + for source in + validate_entries(entity, &entries, writes_rows, entities, &location, errors) + { + if let Some(requirements) = &source.access_requirements { + crate::access::check_profile_authority( + requirements, + &profile.required_scopes, + &profile.required_purposes, + &location, + errors, + ); } } } @@ -158,53 +126,1008 @@ pub(crate) fn validate(entities: &BTreeMap, errors: &mut V } } } + validate_target_entries(project, actions, entities, errors); + validate_source_writes(project, actions, entities, errors); + validate_source_key_writes(project, actions, entities, errors); +} + +fn refuse_source_key_write(location: &str, errors: &mut Vec) { + errors.push(Diagnostic::error( + "breg.access.membership-source-key-write", + location, + "Change a membership source's key, principal or active flag through an Action whose reference target grant you scope, or through an unrestricted grant. A bounded grant can only deactivate an existing row.", + )); +} + +/// Whether a plan can decide who a row of `source` names, or for which key, +/// other than by a create whose key comes from a reference input: a function +/// ceiling over the key, principal or active field, a key set any other way, +/// a principal set on an existing row, or an existing row's active flag set +/// to anything but a fixed `false`. +fn plan_sets_key_unchecked( + action: &ActionSource, + source: &str, + declaration: &MembershipDeclarationSource, +) -> bool { + let reference_input = |input: &str| { + action.inputs.iter().any(|candidate| { + candidate.id == input + && matches!(candidate.field_type, FieldTypeSource::Reference { .. }) + }) + }; + match &action.plan { + ActionPlanSource::Fixed { effects } => effects + .iter() + .filter(|effect| writes_target(action, &effect.target, source)) + .any(|effect| { + effect.set.iter().any(|(field, value)| { + if *field == declaration.key { + // Defence in depth: compiling the plan already requires + // a reference field to come from a reference input or + // an earlier create, so no test reaches this arm alone. + !(value.from_field.as_deref().is_some_and(reference_input) + || value.from_effect.is_some()) + } else if effect.operation == Operation::Create { + false + } else if *field == declaration.principal { + true + } else { + *field == declaration.active + && !(value.from_field.is_none() + && value.from_effect.is_none() + && value.value == Some(serde_json::Value::Bool(false))) + } + }) + }), + ActionPlanSource::Function { writes, .. } => writes + .iter() + .filter(|ceiling| writes_target(action, &ceiling.target, source)) + .any(|ceiling| { + ceiling.fields.iter().any(|field| { + *field == declaration.key + || *field == declaration.principal + || *field == declaration.active + }) + }), + } +} + +/// Whether a grant is bounded, yet not on the source's key: by claims, or by +/// a membership entry on another field. Neither checks which key it writes. +/// A grant with no boundary at all is unrestricted by the author's choice. +fn bounded_off_key( + rows: &[RowBoundarySource], + membership_fields: &[String], + declaration: &MembershipDeclarationSource, +) -> bool { + (!rows.is_empty() || !membership_fields.is_empty()) + && !bounds_key(membership_fields.iter().cloned(), declaration) +} + +/// A grant bounded only by claims on a membership source's own row cannot +/// choose which key, or for whom, that row grants authority. +fn validate_source_key_writes( + project: &RegistryProject, + actions: &BTreeMap, + entities: &BTreeMap, + errors: &mut Vec, +) { + for source in entities.values() { + let Some(declaration) = &source.membership else { + continue; + }; + let fields = probe_fields(declaration); + for grant in &source.access_profiles { + let entries = grant + .membership_boundaries + .iter() + .map(|boundary| boundary.entry().field) + .collect::>(); + if !bounded_off_key(&grant.row_boundaries, &entries, declaration) { + continue; + } + let location = format!( + "recordTypes[id={}].accessProfiles[id={}]", + source.id, grant.id + ); + if grant.operations.iter().any(|operation| { + matches!( + operation, + Operation::Create | Operation::Batch | Operation::Import + ) + }) { + refuse_source_key_write(&format!("{location}.operations"), errors); + } else if grant.operations.contains(&Operation::Patch) + && grant + .writable_fields + .iter() + .any(|field| fields.contains(&field.as_str())) + { + // A Patch of the active flag can set it back to true. + refuse_source_key_write(&format!("{location}.writableFields"), errors); + } + } + let target_bounded_off_key = + |rows: &[RowBoundarySource], entries: &[MembershipRowBoundarySource]| { + let fields = entries + .iter() + .map(|entry| entry.field.clone()) + .collect::>(); + bounded_off_key(rows, &fields, declaration) + }; + for profile in &project.access_profiles { + let action_grants = profile.permissions.actions.iter().map(|grant| { + ( + "actions", + grant.action.as_str(), + grant + .targets + .iter() + .find(|target| target.entity == source.id) + .map(|target| { + target_bounded_off_key( + &target.row_boundaries, + &target.membership_row_boundaries, + ) + }), + ) + }); + let proposal_grants = profile + .permissions + .proposals + .iter() + .filter(|grant| grant.operations.iter().copied().any(is_proposal_write)) + .map(|grant| { + ( + "proposals", + grant.action.as_str(), + grant + .targets + .iter() + .find(|target| target.record_type == source.id) + .map(|target| { + target_bounded_off_key( + &target.row_boundaries, + &target.membership_row_boundaries, + ) + }), + ) + }); + for (surface, action, bounded) in action_grants.chain(proposal_grants) { + if bounded == Some(true) + && actions.get(action).is_some_and(|collected| { + plan_sets_key_unchecked(&collected.source, &source.id, declaration) + }) + { + refuse_source_key_write( + &format!( + "accessProfiles[id={}].permissions.{surface}[action={action}].targets[recordType={}]", + profile.id, source.id + ), + errors, + ); + } + } + } + } } -pub(crate) fn compile(entities: &mut BTreeMap) { - let resolved = entities +/// The fields a membership probe reads on its source row besides its +/// lifecycle, which only a tombstone changes and so only removes authority. +fn probe_fields(declaration: &MembershipDeclarationSource) -> [&str; 3] { + [ + declaration.key.as_str(), + declaration.principal.as_str(), + declaration.active.as_str(), + ] +} + +/// The membership sources any entry of `profile` bounds it through. +fn bounding_sources<'a>( + project: &'a RegistryProject, + entities: &'a BTreeMap, + profile: &str, +) -> BTreeSet { + let records = entities + .values() + .flat_map(|entity| &entity.access_profiles) + .filter(|grant| grant.id == profile) + .flat_map(|grant| &grant.membership_boundaries) + .map(|boundary| boundary.entry().membership); + let targets = project + .access_profiles .iter() - .map(|(id, entity)| { - let profiles = entity - .access_profiles + .filter(|candidate| candidate.id == profile) + .flat_map(|candidate| { + candidate + .permissions + .actions .iter() - .filter_map(|(profile_id, profile)| { - if profile.membership_boundaries.is_empty() { - return None; - } - let boundaries = profile - .membership_boundaries + .flat_map(|grant| &grant.targets) + .flat_map(|target| &target.membership_row_boundaries) + .chain( + candidate + .permissions + .proposals + .iter() + .flat_map(|grant| &grant.targets) + .flat_map(|target| &target.membership_row_boundaries), + ) + .map(|entry| entry.membership.clone()) + }); + records.chain(targets).collect() +} + +/// Whether a plan can give authority on `source`: create a row, or set a +/// field its probe reads to anything but a fixed `false` on the active flag. +fn plan_grants_authority( + action: &ActionSource, + source: &str, + declaration: &MembershipDeclarationSource, +) -> bool { + let fields = probe_fields(declaration); + let targets = + |target: &crate::contract::ActionTargetSource| writes_target(action, target, source); + match &action.plan { + ActionPlanSource::Fixed { effects } => effects + .iter() + .filter(|effect| targets(&effect.target)) + .any(|effect| { + // Defence in depth: a create must set the key, which the + // field check below already refuses. + effect.operation == Operation::Create + || effect.set.iter().any(|(field, value)| { + fields.contains(&field.as_str()) + && !(*field == declaration.active + && value.from_field.is_none() + && value.from_effect.is_none() + && value.value == Some(serde_json::Value::Bool(false))) + }) + }), + ActionPlanSource::Function { writes, .. } => writes + .iter() + .filter(|ceiling| targets(&ceiling.target)) + .any(|ceiling| { + ceiling.operation == Operation::Create + || ceiling + .fields + .iter() + .any(|field| fields.contains(&field.as_str())) + }), + } +} + +fn refuse_source_write(location: &str, errors: &mut Vec) { + errors.push(Diagnostic::error( + "breg.access.membership-source-write", + location, + "A profile bounded through a membership source cannot create its rows or write the key, principal or active field its probe reads, unless that write is itself bounded over a different membership source. A fixed active: false, a tombstone, or a field the probe does not read only removes authority and is admitted.", + )); +} + +/// A profile that a membership source bounds must not be able to give +/// itself, or anyone, authority through that source. +fn validate_source_writes( + project: &RegistryProject, + actions: &BTreeMap, + entities: &BTreeMap, + errors: &mut Vec, +) { + // A module can declare a profile on its Record types alone, so walk every + // profile id a grant can carry, not only the project's. + let profile_ids = project + .access_profiles + .iter() + .map(|profile| profile.id.as_str()) + .chain( + entities + .values() + .flat_map(|entity| &entity.access_profiles) + .map(|grant| grant.id.as_str()), + ) + .collect::>(); + for profile_id in profile_ids { + let profile = project + .access_profiles + .iter() + .find(|profile| profile.id == profile_id); + for source_id in bounding_sources(project, entities, profile_id) { + let Some((source, declaration)) = entities.get(&source_id).and_then(|source| { + source + .membership + .as_ref() + .map(|declaration| (source, declaration)) + }) else { + continue; + }; + let fields = probe_fields(declaration); + if let Some(grant) = source.access_profiles.iter().find(|grant| { + grant.id == profile_id + && !bounds_key( + grant + .membership_boundaries + .iter() + .map(|boundary| boundary.entry().field), + declaration, + ) + }) { + let location = format!( + "recordTypes[id={}].accessProfiles[id={}]", + source.id, grant.id + ); + if grant.operations.iter().any(|operation| { + matches!( + operation, + Operation::Create | Operation::Batch | Operation::Import + ) + }) { + refuse_source_write(&format!("{location}.operations"), errors); + } else if grant.operations.contains(&Operation::Patch) + && grant + .writable_fields + .iter() + .any(|field| fields.contains(&field.as_str())) + { + refuse_source_write(&format!("{location}.writableFields"), errors); + } + } + // Action and Proposal grants exist on project profiles only. + let Some(profile) = profile else { + continue; + }; + let key_bounded = |entries: &[MembershipRowBoundarySource]| { + bounds_key(entries.iter().map(|entry| entry.field.clone()), declaration) + }; + let action_grants = profile.permissions.actions.iter().map(|grant| { + ( + "actions", + grant.action.as_str(), + grant + .targets .iter() - .map(|boundary| { - let source = &entities[&boundary.membership_entity]; - CompiledMembershipBoundary { - field: boundary.field.clone(), - membership_entity: source.id.clone(), - membership_table: source.physical_table.clone(), - membership_key_column: source.fields - [&boundary.membership_key_field] - .physical_name - .clone(), - principal_column: source.fields[&boundary.principal_field] - .physical_name - .clone(), - active_column: source.fields[&boundary.active_field] - .physical_name - .clone(), - } - }) - .collect(); - Some((profile_id.clone(), boundaries)) + .find(|target| target.entity == source.id) + .map(|target| !key_bounded(&target.membership_row_boundaries)), + ) + }); + let proposal_grants = profile + .permissions + .proposals + .iter() + .filter(|grant| grant.operations.iter().copied().any(is_proposal_write)) + .map(|grant| { + ( + "proposals", + grant.action.as_str(), + grant + .targets + .iter() + .find(|target| target.record_type == source.id) + .map(|target| !key_bounded(&target.membership_row_boundaries)), + ) + }); + for (surface, action, unbounded) in action_grants.chain(proposal_grants) { + // A target whose key is bounded over another source is + // governed by the one-level rule; a missing target is + // refused elsewhere. + if unbounded == Some(true) + && actions.get(action).is_some_and(|collected| { + plan_grants_authority(&collected.source, &source.id, declaration) + }) + { + refuse_source_write( + &format!( + "accessProfiles[id={}].permissions.{surface}[action={action}].targets[recordType={}]", + profile.id, source.id + ), + errors, + ); + } + } + } + } +} + +/// Whether a membership entry among `fields` sits on the source's key. Only +/// such an entry checks which key a write sets; an entry on another field +/// bounds that field alone. +fn bounds_key( + mut fields: impl Iterator, + declaration: &MembershipDeclarationSource, +) -> bool { + fields.any(|field| field == declaration.key) +} + +fn validate_declaration( + project: &RegistryProject, + entity: &EntitySource, + entities: &BTreeMap, + errors: &mut Vec, +) { + let Some(declaration) = &entity.membership else { + return; + }; + let location = format!("recordTypes[id={}].membership", entity.id); + let field = |id: &str| entity.fields.iter().find(|field| field.id == id); + if !field(&declaration.key) + .is_some_and(|field| matches!(field.field_type, FieldTypeSource::Reference { .. })) + { + errors.push(Diagnostic::error( + "breg.access.membership-key-type", + &location, + &format!( + "membership.key must name a stored reference field, found {}", + declaration.key + ), + )); + } + let principal = field(&declaration.principal); + if !principal.is_some_and(|field| { + matches!( + field.field_type, + FieldTypeSource::String { .. } | FieldTypeSource::Text { .. } + ) + }) { + errors.push(Diagnostic::error( + "breg.access.membership-principal-type", + &location, + &format!( + "membership.principal must name a stored string or text field, found {}", + declaration.principal + ), + )); + } + // The membership predicate compares the principal column to the + // verified plaintext principal, so ciphertext can never match. + if principal.is_some_and(|field| field.encrypted) { + errors.push(Diagnostic::error( + "breg.access.membership-principal-encrypted", + &location, + &format!( + "membership.principal must name a plaintext stored field, found encrypted field {}", + declaration.principal + ), + )); + } + if !field(&declaration.active) + .is_some_and(|field| matches!(field.field_type, FieldTypeSource::Boolean)) + { + errors.push(Diagnostic::error( + "breg.access.membership-active-type", + &location, + &format!( + "membership.active must name a stored Boolean field, found {}", + declaration.active + ), + )); + } + // A membership source's own RLS must never traverse back into the + // protected root, even through an OR arm. It may be bounded one level + // over a different source that is itself a leaf, and no further. + // Consent is a probe too: a source whose grant requires consent from a + // consent record that membership bounds could need its own probe to + // evaluate the consent probe. + let requires_bounded_consent = entity.access_profiles.iter().any(|profile| { + profile + .require_consent + .iter() + .any(|requirement| has_membership_entries(project, entities, &requirement.record)) + }); + if has_incoming_read_path(entities, &entity.id) + || requires_bounded_consent + || entity.access_profiles.iter().any(|profile| { + profile.membership_boundaries.iter().any(|boundary| { + !is_leaf_over(project, entities, &entity.id, &boundary.entry().membership) + }) + }) + { + refuse_recursive(&location, errors); + } + if entity + .access_requirements + .as_ref() + .is_some_and(|requirements| !requirements.row_boundaries.is_empty()) + { + errors.push(Diagnostic::error("breg.access.membership-source-row-requirement", &location, + "Use mandatory scopes and purposes on the membership Record type. The membership predicate provides its row restriction.")); + } +} + +/// Whether `source` is a membership leaf that `root`, itself a membership +/// source, may be bounded over: a different Record type that declares +/// membership, has no incoming read paths, and is bounded by no membership +/// entry anywhere, as a Record grant or as an Action or Proposal target. +/// The `source != root` and read-path checks are defence in depth: a +/// self-reference already puts an entry on the source, and the leaf's own +/// declaration refuses an incoming read path. Tests reach them only through +/// those other checks. +fn is_leaf_over( + project: &RegistryProject, + entities: &BTreeMap, + root: &str, + source: &str, +) -> bool { + source != root + && entities + .get(source) + .is_some_and(|candidate| candidate.membership.is_some()) + && !has_incoming_read_path(entities, source) + && !has_membership_entries(project, entities, source) +} + +fn has_incoming_read_path(entities: &BTreeMap, id: &str) -> bool { + entities.values().any(|candidate| { + candidate + .read_paths + .iter() + .any(|path| path.through == id || path.to == id) + }) +} + +fn has_membership_entries( + project: &RegistryProject, + entities: &BTreeMap, + id: &str, +) -> bool { + entities.get(id).is_some_and(|entity| { + entity + .access_profiles + .iter() + .any(|profile| !profile.membership_boundaries.is_empty()) + }) || project.access_profiles.iter().any(|profile| { + profile + .permissions + .actions + .iter() + .flat_map(|grant| &grant.targets) + .any(|target| target.entity == id && !target.membership_row_boundaries.is_empty()) + || profile + .permissions + .proposals + .iter() + .flat_map(|grant| &grant.targets) + .any(|target| { + target.record_type == id && !target.membership_row_boundaries.is_empty() + }) + }) +} + +fn refuse_recursive(location: &str, errors: &mut Vec) { + errors.push(Diagnostic::error( + "breg.access.membership-source-recursive", + location, + "A Record type declaring membership must have no incoming read paths, cannot require consent from a consent record that membership bounds, and its membership row boundaries may only name a different membership source that has no membership row boundaries or incoming read paths.", + )); +} + +fn validate_entries<'a>( + entity: &EntitySource, + entries: &[MembershipRowBoundarySource], + writes_rows: bool, + entities: &'a BTreeMap, + location: &str, + errors: &mut Vec, +) -> Vec<&'a EntitySource> { + if entries.len() > 8 { + errors.push(Diagnostic::error( + "breg.access.membership-limit", + location, + "declare at most eight one-hop membership boundaries", + )); + } + let mut sources = Vec::new(); + for (index, entry) in entries.iter().enumerate() { + let site = format!( + "{location}[membership={}:field={}]", + entry.membership, entry.field + ); + if entries[..index].contains(entry) { + errors.push(Diagnostic::error( + "breg.access.membership-duplicate", + &site, + "each membership boundary must be unique", + )); + } + let Some((source, declaration)) = entities.get(&entry.membership).and_then(|source| { + source + .membership + .as_ref() + .map(|declaration| (source, declaration)) + }) else { + errors.push(Diagnostic::error( + "breg.access.membership-record-type-unknown", + &site, + &format!( + "membership must name a Record type with a membership declaration, found {}", + entry.membership + ), + )); + continue; + }; + let root = entity.fields.iter().find(|field| field.id == entry.field); + let key = source + .fields + .iter() + .find(|field| field.id == declaration.key); + if entry.field == CANONICAL_ID && writes_rows { + // A create has no identifier to probe, and a write's key checks + // read stored fields. The identifier bounds reads and targets an + // Action or Proposal only references. + errors.push(Diagnostic::error( + "breg.access.membership-key-type", + &site, + "field id can bound only reads and Action or Proposal targets the plan does not write; bound writes by a stored reference field", + )); + } + if let Some(FieldTypeSource::Reference { target, .. }) = key.map(|key| &key.field_type) { + // The canonical identifier names the protected row itself, so it + // matches a key that references the protected Record type. + let matches = if entry.field == CANONICAL_ID { + *target == entity.id + } else { + root.is_some_and(|root| matches!( + &root.field_type, + FieldTypeSource::Reference { target: field_target, .. } if field_target == target + )) + }; + if !matches { + errors.push(Diagnostic::error( + "breg.access.membership-key-type", + &site, + &format!("field {} and membership.key {} must be stored references to the same Record type, or field must be id when membership.key references this Record type", entry.field, declaration.key), + )); + } + } + sources.push(source); + } + sources +} + +fn validate_target_entries( + project: &RegistryProject, + actions: &BTreeMap, + entities: &BTreeMap, + errors: &mut Vec, +) { + let hook_principals = entities + .values() + .flat_map(|entity| { + entity + .hooks + .iter() + .filter_map(|hook| hook.principal.as_deref()) + }) + .collect::>(); + let timer_actions = entities + .values() + .flat_map(|entity| entity.timers.iter().map(|timer| timer.invoke.as_str())) + .collect::>(); + for profile in &project.access_profiles { + let targets = profile + .permissions + .actions + .iter() + .flat_map(|grant| { + grant.targets.iter().map(move |target| { + ( + "actions", + grant.action.as_str(), + target.entity.as_str(), + &target.membership_row_boundaries, + &target.row_boundaries, + true, + ) + }) + }) + .chain(profile.permissions.proposals.iter().flat_map(|grant| { + grant.targets.iter().map(move |target| { + ( + "proposals", + grant.action.as_str(), + target.record_type.as_str(), + &target.membership_row_boundaries, + &target.row_boundaries, + grant.operations.iter().copied().any(is_proposal_write), + ) }) - .collect(); - (id.clone(), profiles) + })); + for (surface, action, id, entries, rows, write_grant) in targets { + // Invalid references receive the ordinary target diagnostics without + // embedding authored scalar values in admission paths. + if registry_platform_yaml::LocalId::new(action).is_err() + || registry_platform_yaml::LocalId::new(id).is_err() + { + continue; + } + let location = format!("accessProfiles[id={}].permissions.{surface}[action={action}].targets[recordType={id}].rowBoundaries", profile.id); + let declares_membership = entities + .get(id) + .is_some_and(|entity| entity.membership.is_some()); + let plan_writes_target = actions + .get(action) + .is_some_and(|action| plan_writes(&action.source, id)); + let writes_membership = write_grant && declares_membership && plan_writes_target; + validate_write_admission( + profile.required_scopes.is_empty(), + profile.requester_clients.is_empty(), + &profile.principal_claim, + write_grant, + writes_membership, + rows, + !entries.is_empty(), + &location, + errors, + ); + if entries.is_empty() { + continue; + } + if declares_membership + && entries + .iter() + .any(|entry| !is_leaf_over(project, entities, id, &entry.membership)) + { + refuse_recursive(&format!("recordTypes[id={id}].membership"), errors); + } + if surface == "actions" && hook_principals.contains(profile.id.as_str()) { + errors.push(Diagnostic::error( + "breg.access.membership-hook-unsupported", + &location, + "A grant used by a hook cannot use a membership entry in rowBoundaries.", + )); + } + if timer_actions.contains(action) { + errors.push(Diagnostic::error( + "breg.access.membership-timer-unsupported", + &location, + "A grant used by a timer cannot use a membership entry in rowBoundaries.", + )); + } + if let Some(entity) = entities.get(id) { + for source in validate_entries( + entity, + entries, + plan_writes_target, + entities, + &location, + errors, + ) { + if let Some(requirements) = &source.access_requirements { + crate::access::check_profile_authority( + requirements, + &profile.required_scopes, + &profile.required_purposes, + &location, + errors, + ); + } + } + } + } + } +} + +pub(crate) fn is_proposal_write(operation: ProposalOperation) -> bool { + match operation { + ProposalOperation::Answer + | ProposalOperation::Edit + | ProposalOperation::Add + | ProposalOperation::Submit + | ProposalOperation::Revise + | ProposalOperation::Cancel + | ProposalOperation::Apply + | ProposalOperation::Rebase + | ProposalOperation::Retry + | ProposalOperation::Message => true, + ProposalOperation::Get + | ProposalOperation::List + | ProposalOperation::GetReviewStatus + | ProposalOperation::GetReviewContext + | ProposalOperation::GetTaskGrantContext + | ProposalOperation::GetApplicationActor => false, + } +} + +/// Whether an effect or write ceiling target names `entity`, directly or +/// through a reference input. +pub(crate) fn writes_target( + action: &ActionSource, + target: &crate::contract::ActionTargetSource, + entity: &str, +) -> bool { + match (&target.entity, &target.from_field) { + (Some(record_type), None) => record_type == entity, + (None, Some(input)) => action.inputs.iter().any(|candidate| { + candidate.id == *input + && matches!( + &candidate.field_type, FieldTypeSource::Reference { target, .. } if target == entity + ) + }), + _ => false, + } +} + +fn plan_writes(action: &ActionSource, entity: &str) -> bool { + let writes = |target: &crate::contract::ActionTargetSource, operation| { + is_record_write(operation) && writes_target(action, target, entity) + }; + match &action.plan { + ActionPlanSource::Fixed { effects } => effects + .iter() + .any(|effect| writes(&effect.target, effect.operation)), + ActionPlanSource::Function { + writes: ceilings, .. + } => ceilings + .iter() + .any(|ceiling| writes(&ceiling.target, ceiling.operation)), + } +} + +pub(crate) fn is_record_write(operation: Operation) -> bool { + matches!( + operation, + Operation::Create | Operation::Patch | Operation::Tombstone + ) +} + +fn refuse_open_membership_principal(location: &str, errors: &mut Vec) { + errors.push(Diagnostic::error( + "breg.access.open-membership-principal-not-sub", + location, + "An open profile with a membership entry must set principalClaim to sub.", + )); +} + +#[allow(clippy::too_many_arguments)] +pub(crate) fn validate_write_admission( + scopeless: bool, + unrestricted_clients: bool, + principal_claim: &str, + writes: bool, + writes_membership: bool, + row_boundaries: &[RowBoundarySource], + has_membership: bool, + location: &str, + errors: &mut Vec, +) { + let open = scopeless && unrestricted_clients; + if open && has_membership && principal_claim != "sub" { + refuse_open_membership_principal(location, errors); + } + if open + && writes + && !has_membership + && !row_boundaries + .iter() + .any(|row| row.claim == principal_claim) + { + errors.push(Diagnostic::error( + "breg.access.open-write-without-principal-boundary", + location, + "An open profile must bound each write target with a membership entry or a row boundary on its principalClaim.", + )); + } + if scopeless && writes_membership { + errors.push(Diagnostic::error( + "breg.access.scopeless-membership-source-write", + location, + "A profile that admits tokens without scopes cannot write a Record type that declares membership.", + )); + } +} + +pub(crate) fn refuse_membership_write(location: &str, errors: &mut Vec) { + errors.push(Diagnostic::error( + "breg.access.membership-read-only", + location, + "Membership entries cannot authorize this operation. Use a separately authorized profile.", + )); +} + +pub(crate) fn resolve_entry( + entry: &MembershipRowBoundarySource, + entities: &BTreeMap, + location: &str, +) -> Result<(CompiledMembershipBoundary, ExpandedMembershipBoundarySource), Diagnostic> { + let source = entities + .get(&entry.membership) + .and_then(|source| { + source + .membership + .as_ref() + .map(|declaration| (source, declaration)) }) - .collect::>(); - for (id, boundaries) in resolved { - entities - .get_mut(&id) - .expect("compiled entity") - .membership_boundaries = boundaries; + .ok_or_else(|| { + Diagnostic::error( + "breg.access.membership-record-type-unknown", + location, + &format!( + "membership must name a Record type with a membership declaration, found {}", + entry.membership + ), + ) + })?; + let (source, declaration) = source; + let column = |name: &str, field: &str, code| { + source + .fields + .get(field) + .map(|field| field.physical_name.clone()) + .ok_or_else(|| { + Diagnostic::error( + code, + location, + &format!("membership.{name} names missing field {field}"), + ) + }) + }; + Ok(( + CompiledMembershipBoundary { + field: entry.field.clone(), + membership_entity: source.id.clone(), + membership_table: source.physical_table.clone(), + membership_key_column: column( + "key", + &declaration.key, + "breg.access.membership-key-type", + )?, + principal_column: column( + "principal", + &declaration.principal, + "breg.access.membership-principal-type", + )?, + active_column: column( + "active", + &declaration.active, + "breg.access.membership-active-type", + )?, + }, + ExpandedMembershipBoundarySource { + field: entry.field.clone(), + membership_entity: source.id.clone(), + membership_key_field: declaration.key.clone(), + principal_field: declaration.principal.clone(), + active_field: declaration.active.clone(), + }, + )) +} + +pub(crate) fn compile( + entities: &mut BTreeMap, +) -> Result<(), Vec> { + let mut resolved = Vec::new(); + let mut errors = Vec::new(); + for (id, entity) in entities.iter() { + for (profile_id, profile) in &entity.access_profiles { + if profile.membership_boundaries.is_empty() { + continue; + } + let location = + format!("recordTypes[id={id}].accessProfiles[id={profile_id}].rowBoundaries"); + let mut physical = Vec::new(); + let mut logical = Vec::new(); + for boundary in &profile.membership_boundaries { + match resolve_entry(&boundary.entry(), entities, &location) { + Ok((boundary, expanded)) => { + physical.push(boundary); + logical.push(MembershipBoundarySource::Expanded(expanded)); + } + Err(error) => errors.push(error), + } + } + resolved.push((id.clone(), profile_id.clone(), physical, logical)); + } } + if !errors.is_empty() { + return Err(errors); + } + for (id, profile_id, physical, logical) in resolved { + if let Some(entity) = entities.get_mut(&id) { + if let Some(profile) = entity.access_profiles.get_mut(&profile_id) { + profile.membership_boundaries = logical; + entity.membership_boundaries.insert(profile_id, physical); + } + } + } + Ok(()) } pub(crate) fn boundaries<'a>( @@ -313,10 +1236,214 @@ pub(crate) fn source_predicate(boundary: &CompiledMembershipBoundary, alias: &st ) } -pub(crate) fn source_guard(entity: &str, profile: &str, index: usize) -> String { +pub(crate) fn source_guard(name: &str, profile: &str) -> String { format!( "NULLIF(current_setting('registry.membership_probe', true), '') = {} AND NULLIF(current_setting('registry.access_profile', true), '') = {}", - quote_literal(&function_name(entity, profile, index)), + quote_literal(name), quote_literal(profile) ) } + +pub(crate) fn target_function_name(profile: &str, source: &str) -> String { + scoped_function_name("membership_target", profile, source) +} + +fn scoped_function_name(namespace: &str, profile: &str, source: &str) -> String { + let mut hash = Sha256::new(); + hash.update(format!("breg/{namespace}/v1")); + for part in [profile, source] { + hash.update((part.len() as u64).to_be_bytes()); + hash.update(part.as_bytes()); + } + format!("{namespace}_{}", hex_prefix(&hash.finalize(), 12)) +} + +pub(super) struct MembershipProbe<'a> { + pub name: String, + pub profile: &'a str, + pub boundary: &'a CompiledMembershipBoundary, + pub locks: bool, +} + +pub(super) fn probes<'a>( + entities: &'a BTreeMap, + actions: &'a CompiledActionInventory, +) -> Vec> { + let mut probes = Vec::new(); + for entity in entities.values() { + for (profile, boundaries) in &entity.membership_boundaries { + for (index, boundary) in boundaries.iter().enumerate() { + probes.push(MembershipProbe { + name: function_name(&entity.id, profile, index), + profile, + boundary, + locks: false, + }); + } + } + } + + let mut targets = BTreeSet::new(); + for (profile, boundary, _) in target_boundaries(actions) { + if targets.insert((profile, boundary.membership_entity.as_str())) { + probes.push(MembershipProbe { + name: target_function_name(profile, &boundary.membership_entity), + profile, + boundary, + locks: false, + }); + } + } + probes.extend( + lockable_membership_tables(entities, actions) + .into_iter() + .map(|((profile, source), boundary)| MembershipProbe { + name: lock_function_name(profile, source), + profile, + boundary, + locks: true, + }), + ); + probes +} + +fn target_boundaries( + actions: &CompiledActionInventory, +) -> impl Iterator { + actions.actions.iter().flat_map(|action| { + let action_operation = if action.execution.is_proposal() { + Operation::Start + } else { + Operation::Invoke + }; + let action_targets = action + .permissions + .iter() + .filter(move |grant| grant.operations.contains(&action_operation)) + .flat_map(move |grant| { + grant.entity_target_locks().flat_map(move |target| { + target.membership_boundaries.iter().map(move |boundary| { + ( + grant.profile_id.as_str(), + boundary, + action_operation == Operation::Invoke, + ) + }) + }) + }); + let proposal_targets = match &action.execution { + CompiledActionExecution::Proposal { proposal } => proposal.permissions.as_slice(), + CompiledActionExecution::Immediate => &[], + }; + action_targets.chain(proposal_targets.iter().flat_map(move |grant| { + // Caller Apply also includes an authorized external recovery actor. + let locks = grant.operations.contains(&ProposalOperation::Apply); + grant.targets.iter().flat_map(move |target| { + target + .membership_boundaries + .iter() + .map(move |boundary| (grant.profile_id.as_str(), boundary, locks)) + }) + })) + }) +} + +pub(crate) fn lock_function_name(profile: &str, source: &str) -> String { + scoped_function_name("membership_lock", profile, source) +} + +/// The membership sources write authority can lock, by access profile and Record type. +pub(crate) fn lockable_membership_tables<'a>( + entities: &'a BTreeMap, + actions: &'a CompiledActionInventory, +) -> BTreeMap<(&'a str, &'a str), &'a CompiledMembershipBoundary> { + let mut tables = BTreeMap::new(); + for entity in entities.values() { + for (profile, boundaries) in &entity.membership_boundaries { + if entity.access_profiles[profile] + .operations + .iter() + .any(|operation| { + matches!( + operation, + Operation::Create + | Operation::Patch + | Operation::Tombstone + | Operation::Batch + ) + }) + { + for boundary in boundaries { + tables.insert( + (profile.as_str(), boundary.membership_entity.as_str()), + boundary, + ); + } + } + } + } + for (profile, boundary, locks) in target_boundaries(actions) { + if locks { + tables.insert((profile, boundary.membership_entity.as_str()), boundary); + } + } + tables +} + +pub(super) fn append_target_probes( + entity: &CompiledEntity, + profile: &str, + boundaries: &[CompiledMembershipBoundary], + policies: &mut [crate::generated_ddl::DdlPolicy], +) { + if boundaries.is_empty() { + return; + } + let predicate = boundaries + .iter() + .map(|boundary| { + format!( + "registry_context.{}({})", + quote_identifier(&target_function_name(profile, &boundary.membership_entity)), + if boundary.field == CANONICAL_ID { + "record_id".to_owned() + } else { + quote_identifier(&entity.fields[&boundary.field].physical_name) + } + ) + }) + .collect::>() + .join(" AND "); + for policy in policies { + for expression in policy.using_expression.iter_mut().chain( + policy + .check_expression + .iter_mut() + .filter(|check| *check != "false"), + ) { + *expression = format!("({expression}) AND {predicate}"); + } + } +} + +pub(crate) fn index_statement(entity: &CompiledEntity) -> Option<(String, String, String)> { + let declaration = entity.membership.as_ref()?; + let column = |field: &str| quote_identifier(&entity.fields[field].physical_name); + let digest = Sha256::digest(format!("breg/membership-index/v1/{}/key", entity.id).as_bytes()); + let name = format!("breg_membership_key_{}", hex_prefix(&digest, 5)); + // Unique: one live row per key and principal, so a removal that + // deactivates one row always ends that person's access through the key. + let sql = format!( + "CREATE UNIQUE INDEX {} ON registry_data.{} ({}, {}) WHERE {} IS TRUE AND record_lifecycle = 'active'", + quote_identifier(&name), + quote_identifier(&entity.physical_table), + column(&declaration.key), + column(&declaration.principal), + column(&declaration.active) + ); + Some(( + format!("entity.{}.membership.key-index", entity.id), + name, + sql, + )) +} diff --git a/crates/registry-breg/src/metrics.rs b/crates/registry-breg/src/metrics.rs index 482b7821c8..4536b48a49 100644 --- a/crates/registry-breg/src/metrics.rs +++ b/crates/registry-breg/src/metrics.rs @@ -54,7 +54,7 @@ use axum::{ Router, }; -use registry_platform_authcommon::RefusalRecorder; +use registry_platform_authcommon::{FailedCheck, RefusalRecorder}; use registry_platform_metrics::{ sample_error_class, Exposition, HistogramSnapshot, MetricKind, ScrapeDeadline, SumCountOrder, CLASS_NO_TIME_LEFT, CLASS_POOL, CONTENT_TYPE as METRICS_MEDIA_TYPE, @@ -185,15 +185,16 @@ pub struct Metrics { /// The process-wide refusal recorder: the one counter family and the one log /// budget that every refused request in this process shares, whichever router -/// served it. It is built once, from a closed label space the enum owns, so -/// construction cannot fail. +/// served it. It is built once with the shared checks and BReg's membership +/// check, so the closed label space is valid by construction. pub(crate) fn process_refusal_recorder() -> &'static Arc { static RECORDER: OnceLock> = OnceLock::new(); RECORDER.get_or_init(|| Arc::new(new_refusal_recorder())) } fn new_refusal_recorder() -> RefusalRecorder { - RefusalRecorder::new("breg").expect("the refusal counter's closed label space is valid") + RefusalRecorder::with_additional_checks("breg", &[FailedCheck::Membership]) + .expect("the refusal counter's closed label space is valid") } impl Default for Metrics { @@ -1334,7 +1335,6 @@ mod tests { #[test] fn the_refusal_counter_declares_every_check_and_publishes_it_at_zero() { - use registry_platform_authcommon::FailedCheck; let rendered = Metrics::default().render(None); for check in FailedCheck::ALL { assert!( diff --git a/crates/registry-breg/src/migration.rs b/crates/registry-breg/src/migration.rs index 100563c211..69d40735f0 100644 --- a/crates/registry-breg/src/migration.rs +++ b/crates/registry-breg/src/migration.rs @@ -178,6 +178,11 @@ pub enum MigrationError { FieldPatternSyntax { entity_id: String, field_id: String }, #[error("existing rows do not conform to a persisted field pattern")] FieldPatternExistingRows { entity_id: String, field_id: String }, + /// Existing active rows of a membership source repeat a key and + /// principal, so its unique live-row index cannot build. + /// Authored identifiers only. + #[error("existing active rows of membership source `{entity_id}` repeat a key and principal")] + MembershipDuplicateLiveRows { entity_id: String }, /// Authored record identifiers only; field values never cross this boundary. #[error("field-encryption backfill would collide blind indexes of existing records")] FieldEncryptionLookupCollision { @@ -1283,6 +1288,10 @@ async fn activate(request: ApplyVerifiedPackageRequest<'_>, mode: ApplyMode) -> request.package.registry(), &statement.id, ), + membership_source: crate::postgres::compiled_membership_source( + request.package.registry(), + &statement.id, + ), ordinal: i32::try_from(ordinal).map_err(|_| MigrationError::PackageBinding)?, }) }) @@ -2247,6 +2256,9 @@ async fn fail_with_error_and_release( entity_id, field_id, }, + crate::postgres::PostgresKernelError::MembershipDuplicateLiveRows { entity_id } => { + MigrationError::MembershipDuplicateLiveRows { entity_id } + } crate::postgres::PostgresKernelError::FieldEncryptionBlindCollision { entity_id, record_ids, diff --git a/crates/registry-breg/src/migration_reconcile.rs b/crates/registry-breg/src/migration_reconcile.rs index 10bf36ee2b..c4af6e506a 100644 --- a/crates/registry-breg/src/migration_reconcile.rs +++ b/crates/registry-breg/src/migration_reconcile.rs @@ -213,6 +213,7 @@ impl From for ReconcileError { | PostgresKernelError::DatabaseTransport(_) | PostgresKernelError::FieldPatternSyntax { .. } | PostgresKernelError::FieldPatternExistingRows { .. } + | PostgresKernelError::MembershipDuplicateLiveRows { .. } | PostgresKernelError::FieldEncryptionBlindCollision { .. } | PostgresKernelError::FieldEncryptionRetainedProposalSnapshots { .. } | PostgresKernelError::BlindIndexReindexRowLimit { .. } => Self::InvalidInput, @@ -254,6 +255,7 @@ impl From for ReconcileError { | MigrationError::DatabaseUnavailable | MigrationError::FieldPatternSyntax { .. } | MigrationError::FieldPatternExistingRows { .. } + | MigrationError::MembershipDuplicateLiveRows { .. } | MigrationError::FieldEncryptionLookupCollision { .. } | MigrationError::FieldEncryptionRetainedProposalSnapshots { .. } | MigrationError::BlindIndexReindexRowLimit { .. } diff --git a/crates/registry-breg/src/model.rs b/crates/registry-breg/src/model.rs index a4e8c6ec47..17cdefc343 100644 --- a/crates/registry-breg/src/model.rs +++ b/crates/registry-breg/src/model.rs @@ -525,6 +525,13 @@ impl CompiledActionExecution { matches!(self, Self::Proposal { .. }) } } +#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields, rename_all = "camelCase")] +pub struct CompiledAdditionalForm { + pub maximum_count: u8, + pub inputs: Vec, +} + #[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub struct CompiledProposalPolicy { @@ -537,15 +544,30 @@ pub struct CompiledProposalPolicy { pub attachments: BTreeMap, #[serde(default, skip_serializing_if = "Option::is_none")] pub additions: Option, + #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] + pub additional_forms: BTreeMap, /// Proposal files that applied effects reference from record slots, in /// effect order. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub promotions: Vec, pub permissions: Vec, + /// Where the Proposal's subject comes from. Bound once, at the first Submit. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub subject: Option, + /// The Proposal's message thread, when the Action declares one. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub messages: Option, #[serde(default, skip_serializing_if = "Option::is_none")] pub system_apply_grant: Option, } +/// The bounds of one Proposal's message thread. +#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct CompiledProposalMessages { + pub maximum_count: u32, +} + /// Static package-approved scope for the built-in executor. This definition /// alone is inert; application intersects it with a frozen submission scope. #[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] @@ -608,7 +630,7 @@ impl CompiledProposalApplication { } } } -pub use crate::contract::{ProposalOperation, ProposalOwnership}; +pub use crate::contract::{ProposalOperation, ProposalParty, ProposalSubjectSource}; #[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "kebab-case")] pub enum CompiledProposalRetentionMode { @@ -632,22 +654,54 @@ pub struct CompiledProposalPermission { pub required_scopes: BTreeSet, pub required_purposes: BTreeSet, pub operations: BTreeSet, - pub ownership: Option, + /// Packages built before `party` replaced `ownership` stored a caller + /// owned grant as `"ownership": "caller"` and any other as `null`. They + /// still load as predecessors, with the same meaning. + #[serde( + default, + alias = "ownership", + deserialize_with = "compiled_party", + skip_serializing_if = "Option::is_none" + )] + pub party: Option, + /// The grant's Submit may name someone other than the submitter as the + /// Proposal's subject. + #[serde(default, skip_serializing_if = "is_false")] + pub submits_for_anyone: bool, pub targets: Vec, pub readable_context_fields: BTreeSet, #[serde(default)] pub readable_inputs: BTreeSet, pub readable_attachments: BTreeSet, pub writable_attachments: BTreeSet, + #[serde(default, skip_serializing_if = "BTreeSet::is_empty")] + pub readable_forms: BTreeSet, + #[serde(default, skip_serializing_if = "BTreeSet::is_empty")] + pub writable_forms: BTreeSet, #[serde(default, skip_serializing_if = "Option::is_none")] pub writable_inputs: Option>, } +fn compiled_party<'de, D: serde::Deserializer<'de>>( + deserializer: D, +) -> Result, D::Error> { + match Option::::deserialize(deserializer)?.as_deref() { + None => Ok(None), + Some("owner" | "caller") => Ok(Some(ProposalParty::Owner)), + Some("subject") => Ok(Some(ProposalParty::Subject)), + Some(other) => Err(serde::de::Error::unknown_variant( + other, + &["owner", "subject"], + )), + } +} #[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub struct CompiledProposalTargetPermission { #[serde(rename = "recordType")] pub entity_id: String, pub row_boundaries: Vec, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub membership_boundaries: Vec, } #[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] @@ -889,6 +943,8 @@ pub struct CompiledActionTargetPermission { /// The effect or input that identifies this action target use. pub source: CompiledActionTargetUseSource, pub row_boundaries: Vec, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub membership_boundaries: Vec, } impl CompiledActionPermission { @@ -1100,6 +1156,8 @@ pub struct CompiledEntity { #[serde(default, skip_serializing_if = "Option::is_none")] pub access_requirements: Option, #[serde(default, skip_serializing_if = "Option::is_none")] + pub membership: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] pub access_log: Option, #[serde(default, skip_serializing_if = "Option::is_none")] pub geojson: Option, diff --git a/crates/registry-breg/src/mutation.rs b/crates/registry-breg/src/mutation.rs index d75af96ea7..f2bbd8fa78 100644 --- a/crates/registry-breg/src/mutation.rs +++ b/crates/registry-breg/src/mutation.rs @@ -7,10 +7,14 @@ mod action; pub(crate) use action::erase_expired_action_evidence; pub(crate) use action::validate_action_attachments; pub(crate) use action::{HookChangeApplication, HookChangeOutcome}; +mod membership; +mod reference_reach; +pub(crate) use membership::probe_action_memberships; +use membership::RecordMembership; mod proposal; pub(crate) use proposal::{ - link_readable, proposal_http_method, proposal_operation_name, CheckedProposalTaskAuthority, - ProposalApplyPreflight, ProposalReadDisclosure, + link_readable, proposal_http_method, proposal_operation_name, thread_of, + CheckedProposalTaskAuthority, ProposalApplyPreflight, ProposalReadDisclosure, }; pub(crate) use proposal::{PUBLIC_REASON_REFERENCE, REVIEW_PROGRESS_REFERENCE}; mod timer; @@ -90,7 +94,7 @@ use crate::outbox::{ }; use crate::postgres::external_refresh_queue::{capture_local_records, LocalRecordCapture}; use crate::postgres::{ - begin_action_transaction, begin_record_transaction, begin_timer_action_transaction, + begin_action_transaction, begin_record_transaction_for_write, begin_timer_action_transaction, ActionClaimContext, ClaimContext, ExpectedRegistryIdentity, ImmediateActionLinkBinding, ImmediateActionLinkContext, ImmediateActionTargetBinding, ImmediateActionTargetContext, RegistryLockKey, RowBoundaryContext, SqlIdentifier, @@ -380,6 +384,9 @@ pub struct MutationPlan { /// as a direct write: an operator-opened import authority bounds it. imported_item: bool, external_refresh_enabled: bool, + /// The physical table of each Record type a reference field of this + /// Record type names, for the referenced-record read check. + reference_tables: BTreeMap, } impl MutationPlan { @@ -432,6 +439,22 @@ impl MutationPlan { return Err(MutationError::InvalidRequest); } let event_deliveries = exact_entity_event_deliveries(registry, entity)?; + let reference_tables = entity + .fields + .values() + .filter_map(|field| match &field.field_type { + crate::contract::FieldTypeSource::Reference { target, .. } => Some(target), + _ => None, + }) + .map(|target| { + registry + .entities() + .get(target) + .filter(|target| valid_physical_identifier(&target.physical_table)) + .map(|target| (target.id.clone(), target.physical_table.clone())) + .ok_or(MutationError::InvalidRequest) + }) + .collect::, _>>()?; let temporal_exclusion_constraints = temporal_exclusion_constraints(registry, entity, inventory)?; Ok(Self { @@ -443,6 +466,7 @@ impl MutationPlan { temporal_exclusion_constraints, imported_item: false, external_refresh_enabled: crate::postgres::external_projection::enabled(registry), + reference_tables, }) } @@ -506,6 +530,7 @@ impl MutationPlan { temporal_exclusion_constraints: self.temporal_exclusion_constraints.clone(), imported_item: self.route.operation == Operation::Import, external_refresh_enabled: self.external_refresh_enabled, + reference_tables: self.reference_tables.clone(), }) } } @@ -1022,7 +1047,18 @@ impl MutationTransaction { return Err(error); } let _attempt = self.begin_boundary_audit(&request).await?; - let result = self.execute_after_attempt(client, &request, fault).await; + let mut retries = 0; + let result = loop { + let result = self.execute_after_attempt(client, &request, fault).await; + if matches!(result, Err(MutationError::MembershipKeyDrift)) + && retries < 2 + && !fault.is_enabled() + { + retries += 1; + continue; + } + break result; + }; if failure_is_refusal(&result) && !fault.is_enabled() { self.record_boundary_audit(&request, PreIoAuditKind::Refusal) .await?; @@ -1030,9 +1066,9 @@ impl MutationTransaction { // The retry distinction belongs to request actions. Ordinary mutations // retain their existing public failure for aborted SQL transactions. result.map_err(|error| match error { - MutationError::RetryableConflict | MutationError::CommitUnresolved => { - MutationError::Unavailable - } + MutationError::MembershipKeyDrift + | MutationError::RetryableConflict + | MutationError::CommitUnresolved => MutationError::Unavailable, other => other, }) } @@ -1081,17 +1117,28 @@ impl MutationTransaction { return Err(error); } let _attempt = self.begin_batch_boundary_audit(&request).await?; - let result = self - .execute_batch_after_attempt(client, &request, fault) - .await; + let mut retries = 0; + let result = loop { + let result = self + .execute_batch_after_attempt(client, &request, fault) + .await; + if matches!(result, Err(MutationError::MembershipKeyDrift)) + && retries < 2 + && !fault.is_enabled() + { + retries += 1; + continue; + } + break result; + }; if failure_is_refusal(&result) && !fault.is_enabled() { self.record_batch_boundary_audit(&request, PreIoAuditKind::Refusal) .await?; } result.map_err(|error| match error { - MutationError::RetryableConflict | MutationError::CommitUnresolved => { - MutationError::Unavailable - } + MutationError::MembershipKeyDrift + | MutationError::RetryableConflict + | MutationError::CommitUnresolved => MutationError::Unavailable, other => other, }) } @@ -1206,12 +1253,14 @@ impl MutationTransaction { key_domain: IdempotencyKeyDomain::Caller, }, )?; - let transaction = begin_record_transaction( + let transaction = begin_record_transaction_for_write( client, self.lock_key, self.lock_timeout, &self.expected, request.claims, + !crate::membership::boundaries(&request.plan.entity, request.claims.access_profile()) + .is_empty(), ) .await .map_err(|_| MutationError::Unavailable)?; @@ -1228,6 +1277,23 @@ impl MutationTransaction { if !matches!(&stored.metadata, StoredResultMetadata::Record { .. }) { return Err(MutationError::Unavailable); } + if !crate::membership::boundaries(&request.plan.entity, request.claims.access_profile()) + .is_empty() + { + let record_ids = match request.record_id { + Some(id) => { + vec![Uuid::parse_str(id).map_err(|_| MutationError::InvalidRequest)?] + } + None => membership::replayed_record_ids(stored.response.body())?, + }; + membership::recheck_replayed_membership( + transaction.transaction(), + &request.plan.entity, + request.claims.access_profile(), + &record_ids, + ) + .await?; + } let entry = terminal_entry( self.audit.profile(), TerminalAudit { @@ -1283,6 +1349,13 @@ impl MutationTransaction { if request.claims.task_grant().is_some() { return Err(MutationError::PreconditionFailed); } + let membership = RecordMembership::prepare( + transaction.transaction(), + &request.plan.entity, + request.claims.access_profile(), + std::iter::once((request.record_id, request.body.clone())), + ) + .await?; fault.fail_at(MutationFaultPoint::BeforeCurrentRow)?; let current = apply_current_row( transaction.transaction(), @@ -1290,6 +1363,17 @@ impl MutationTransaction { self.audit.profile(), &self.expected.activation_id, self.field_encryption.as_deref(), + membership.as_ref(), + ) + .await?; + // After the row's own authorisation and foreign keys, before commit: + // a refusal here rolls the write back, and the earlier answers keep + // their precedence. + reference_reach::require_readable_references( + transaction.transaction(), + request.plan, + request.claims, + &reference_reach::set_references(&request.plan.entity, &request.body)?, ) .await?; stage_record_timer_rows( @@ -1547,12 +1631,14 @@ impl MutationTransaction { }, }, )?; - let transaction = begin_record_transaction( + let transaction = begin_record_transaction_for_write( client, self.lock_key, self.lock_timeout, &self.expected, request.claims, + !crate::membership::boundaries(&request.plan.entity, request.claims.access_profile()) + .is_empty(), ) .await .map_err(|_| MutationError::Unavailable)?; @@ -1826,6 +1912,17 @@ impl MutationTransaction { let StoredResultMetadata::Batch { result_count } = stored.metadata else { return Err(MutationError::Unavailable); }; + if !crate::membership::boundaries(&request.plan.entity, request.claims.access_profile()) + .is_empty() + { + membership::recheck_replayed_membership( + transaction.transaction(), + &request.plan.entity, + request.claims.access_profile(), + &membership::replayed_record_ids(stored.response.body())?, + ) + .await?; + } let entry = terminal_entry( self.audit.profile(), TerminalAudit { @@ -1885,7 +1982,17 @@ impl MutationTransaction { }); } - prelock_batch_current_rows(transaction.transaction(), request).await?; + let mut membership = RecordMembership::prepare( + transaction.transaction(), + &request.plan.entity, + request.claims.access_profile(), + request.items.iter().map(|item| { + let (id, _, body) = item.request_parts(); + (id, body) + }), + ) + .await?; + prelock_batch_current_rows(transaction.transaction(), request, membership.as_ref()).await?; set_temporal_exclusion_constraints( transaction.transaction(), @@ -1920,8 +2027,22 @@ impl MutationTransaction { self.audit.profile(), &self.expected.activation_id, self.field_encryption.as_deref(), + membership.as_ref(), ) .await?; + // At this item, as for a single write: a missing or tombstoned + // reference fails at this item's row, so an unreadable one must + // fail here too, before any later item can answer instead. + reference_reach::require_readable_references( + transaction.transaction(), + request.plan, + request.claims, + &reference_reach::set_references(&request.plan.entity, &item_request.body)?, + ) + .await?; + if let Some(membership) = &mut membership { + membership.record_batch_write(¤t); + } let record_reference = record_reference( self.audit.profile(), &self.expected.activation_id, @@ -2448,8 +2569,14 @@ pub enum MutationError { /// stale-condition failures, which remain generic precondition refusals. #[error("the resulting record is outside the selected access profile's row boundary")] WriteOutsideBoundary, + #[error("the resulting record is outside the selected access profile's row boundary")] + MembershipWriteOutsideBoundary, #[error("mutation precondition failed")] PreconditionFailed, + #[error("mutation precondition failed")] + MembershipPreconditionFailed, + #[error("a target key changed before the mutation locked the target")] + MembershipKeyDrift, /// An admitted frozen application found a changed target. It keeps the /// ordinary precondition problem, but records Rebase as its recovery. #[error("mutation precondition failed")] @@ -2475,12 +2602,27 @@ pub enum MutationError { /// The review authority rejected the Proposal, and a rejection is terminal. #[error("the review rejected this Proposal")] ProposalRejected, + /// Submit names a subject other than the submitter, and the submitting + /// grant does not say `submitsFor: anyone`. + #[error("the Proposal names someone other than the submitter as its subject")] + ProposalSubjectNotCaller, + /// A later Submit read a different subject than the one bound at the + /// first Submit. + #[error("the Proposal's subject changed since it was first submitted")] + ProposalSubjectChanged, + /// The Proposal's thread holds as many messages as its Action allows. + #[error("the Proposal's message thread is full")] + ProposalMessageLimitReached, /// A record attachment slot already holds a file. Record slots are /// write-once, so a second write is refused whatever its bytes are. #[error("the record attachment slot already holds a file")] AttachmentSlotWriteOnce, #[error("the supporting document slot has reached its file limit")] AttachmentLimitReached, + #[error("the Action does not declare this additional form")] + FormUndeclared, + #[error("the submission has reached the entry limit for this form")] + FormLimitReached, #[error("the required attachment slot is empty")] AttachmentRequired { slot: String }, #[error("the attachment is awaiting verification")] @@ -2560,6 +2702,8 @@ impl MutationError { match self { Self::AuthorizationRefused(check) => Some(*check), Self::WriteOutsideBoundary => Some(FailedCheck::RowBoundary), + Self::ProposalSubjectNotCaller => Some(FailedCheck::Ownership), + Self::MembershipWriteOutsideBoundary => Some(FailedCheck::Membership), Self::FieldGuardFailed { .. } | Self::ProposalGuardFailed(_) => { Some(FailedCheck::ActionGuard) } @@ -2567,14 +2711,20 @@ impl MutationError { | Self::InvalidRequestAt(_) | Self::InvalidTimerWindow { .. } | Self::PreconditionFailed + | Self::MembershipPreconditionFailed + | Self::MembershipKeyDrift | Self::ProposalTargetChanged | Self::ProposalReviewResultMismatch | Self::Conflict | Self::ProposalUniqueConflict | Self::ProposalRejected + | Self::ProposalSubjectChanged + | Self::ProposalMessageLimitReached | Self::AttachmentSlotWriteOnce | Self::AttachmentTooLarge | Self::AttachmentLimitReached + | Self::FormUndeclared + | Self::FormLimitReached | Self::AttachmentRequired { .. } | Self::AttachmentVerificationPending { .. } | Self::AttachmentVerificationRejected { .. } @@ -2917,13 +3067,14 @@ pub(super) async fn capture_external_refresh_rows( Ok(()) } -/// Acquire every existing batch target in canonical UUID order before the +/// Acquire every admitted existing batch target in canonical UUID order before the /// first row is changed. Timer staging takes its shared control lock first, /// so ordinary writers and workers cannot invert control, Record, and /// generation locks when callers submit the same targets in different order. async fn prelock_batch_current_rows( transaction: &Transaction<'_>, request: &BatchMutationRequest<'_>, + membership: Option<&RecordMembership<'_>>, ) -> Result<(), MutationError> { let mut record_ids = BTreeSet::new(); for item in &request.items { @@ -2935,6 +3086,11 @@ async fn prelock_batch_current_rows( if !valid_uuid(record_id) { return Err(MutationError::InvalidRequest); } + if membership + .is_some_and(|membership| membership.authorize_existing(Some(record_id)).is_err()) + { + continue; + } record_ids.insert(Uuid::parse_str(record_id).map_err(|_| MutationError::InvalidRequest)?); } if record_ids.is_empty() { @@ -2964,6 +3120,7 @@ async fn apply_current_row( audit_profile: &AuditProfile, package_revision: &str, field_encryption: Option<&FieldEncryptionService>, + membership: Option<&RecordMembership<'_>>, ) -> Result { if request .plan @@ -2986,6 +3143,18 @@ async fn apply_current_row( return Err(MutationError::InvalidRequest); }; let mut data = data.clone(); + if let Some(membership) = membership { + membership.authorize_proposed(&data)?; + match request.claims.authorizes_record_snapshot_before_allocation( + &request.plan.entity, + &data, + record_uuid, + ) { + Ok(true) => {} + Ok(false) => return Err(MutationError::WriteOutsideBoundary), + Err(_) => return Err(MutationError::Unavailable), + } + } crate::generated_identifiers::reserve_for_create( transaction, &request.plan.entity, @@ -3014,6 +3183,9 @@ async fn apply_current_row( Ok(row) } Operation::Patch => { + if let Some(membership) = membership { + membership.authorize_existing(request.record_id)?; + } let current = load_current_row_for_update(transaction, request).await?; let expected = request .expected_etag @@ -3031,8 +3203,12 @@ async fn apply_current_row( if expected.ct_eq(current_etag.as_bytes()).unwrap_u8() != 1 { return Err(MutationError::PreconditionFailed); } + if let Some(membership) = membership { + membership.verify_locked(¤t)?; + } let before_data = current.data.clone(); - let data = apply_patch_document(transaction, request, ¤t.data).await?; + let data = + apply_patch_document(transaction, request, ¤t.data, membership).await?; let mut admitted_intake = current.data.clone(); admitted_intake.extend(data.clone()); authorize_record_snapshot(request, &admitted_intake, current.record_uuid)?; @@ -3050,6 +3226,9 @@ async fn apply_current_row( Ok(row) } Operation::Tombstone => { + if let Some(membership) = membership { + membership.authorize_existing(request.record_id)?; + } let current = load_tombstone_row_for_update(transaction, request).await?; let expected = request .expected_etag @@ -3067,6 +3246,9 @@ async fn apply_current_row( if expected.ct_eq(current_etag.as_bytes()).unwrap_u8() != 1 { return Err(MutationError::PreconditionFailed); } + if let Some(membership) = membership { + membership.verify_locked(¤t)?; + } match crate::disclosure::plan(&request.plan.entity, request.claims.access_profile()) .refuses_tombstone(¤t.data) { @@ -3136,13 +3318,13 @@ async fn apply_patch_row( ) -> Result { let record_id = request.record_id.ok_or(MutationError::InvalidRequest)?; let profile = selected_profile(request)?; + let disclosure = crate::disclosure::plan(&request.plan.entity, request.claims.access_profile()); + check_update_disclosure(&disclosure, before, &data)?; update_current_row( transaction, &request.plan.entity, - request.claims.access_profile(), record_id, expected_revision, - before, data, field_encryption, Some(ConstraintDisclosure::DeclaredFields { @@ -3188,21 +3370,12 @@ pub(super) async fn write_plan_row( ) .await?; } - // A state a `record` condition withholds from the writer is outside its - // boundary, as for a Patch or a Create, before the restrictive row policy - // can refuse it. A state that cannot be evaluated counts as withheld. - let mut after = before.cloned().unwrap_or_default(); - after.extend( - fields - .iter() - .map(|(field, value)| (field.clone(), value.clone())), - ); - if crate::disclosure::plan(entity, writer) - .withholds_record(&after) - .unwrap_or(true) - { + let disclosure = crate::disclosure::plan(entity, writer); + let PlanWriteDisclosure::RecordVisible { update } = + plan_write_disclosure(&disclosure, before, &fields) + else { return Err(MutationError::WriteOutsideBoundary); - } + }; let record_id = record_uuid.to_string(); let mut current = match expected_revision { None => { @@ -3225,19 +3398,15 @@ pub(super) async fn write_plan_row( .await? } Some(revision) => { - let Some(before) = before else { - return Err(MutationError::InvalidRequest); - }; - if revision < 1 { + if before.is_none() || revision < 1 { return Err(MutationError::InvalidRequest); } + update?; update_current_row( transaction, entity, - writer, &record_id, revision, - before, fields, field_encryption, origin.constraint_disclosure(), @@ -3250,6 +3419,51 @@ pub(super) async fn write_plan_row( Ok(current) } +enum PlanWriteDisclosure { + RecordWithheld, + RecordVisible { update: Result<(), MutationError> }, +} + +fn plan_write_disclosure( + disclosure: &crate::disclosure::DisclosurePlan<'_>, + before: Option<&Map>, + fields: &Map, +) -> PlanWriteDisclosure { + if disclosure.is_empty() { + return PlanWriteDisclosure::RecordVisible { update: Ok(()) }; + } + // A `record` condition withholds the resulting state before the + // restrictive row policy can refuse it. An unevaluable state is withheld. + let mut after = before.cloned().unwrap_or_default(); + after.extend( + fields + .iter() + .map(|(field, value)| (field.clone(), value.clone())), + ); + if disclosure.withholds_record(&after).unwrap_or(true) { + return PlanWriteDisclosure::RecordWithheld; + } + PlanWriteDisclosure::RecordVisible { + update: before.map_or(Ok(()), |before| { + check_update_disclosure(disclosure, before, fields) + }), + } +} + +/// Refuse lifting a disclosure mark or writing a withheld field before +/// persistence can answer with a constraint conflict. +fn check_update_disclosure( + disclosure: &crate::disclosure::DisclosurePlan<'_>, + before: &Map, + data: &Map, +) -> Result<(), MutationError> { + match disclosure.refuses_write(before, data) { + Ok(false) => Ok(()), + Ok(true) => Err(MutationError::WriteOutsideBoundary), + Err(_) => Err(MutationError::Unavailable), + } +} + #[derive(Clone, Copy)] pub(super) enum PlanWriteOrigin { ImmediateAction, @@ -3340,27 +3554,17 @@ async fn insert_current_row( row_to_current(entity, &row) } -/// Write `data` over the current row `before` as the `writer` profile. Every -/// update of an existing record passes here, so a bound writer's attempt to -/// lift a disclosure mark or overwrite a withheld field is refused on each -/// path alike, before the database can answer with a constraint conflict. +/// Persist an update after the caller has checked write disclosure. #[allow(clippy::too_many_arguments)] async fn update_current_row( transaction: &Transaction<'_>, entity: &CompiledEntity, - writer: &str, record_id: &str, expected_revision: i64, - before: &Map, data: Map, field_encryption: Option<&FieldEncryptionService>, constraint_disclosure: Option>, ) -> Result { - match crate::disclosure::plan(entity, writer).refuses_write(before, &data) { - Ok(false) => {} - Ok(true) => return Err(MutationError::WriteOutsideBoundary), - Err(_) => return Err(MutationError::Unavailable), - } let submitted_fields = entity .fields .values() @@ -3764,6 +3968,7 @@ async fn apply_patch_document( transaction: &Transaction<'_>, request: &MutationRequest<'_>, current: &Map, + membership: Option<&RecordMembership<'_>>, ) -> Result, MutationError> { let MutationBody::Patch(operations) = &request.body else { return Err(MutationError::InvalidRequest); @@ -3775,6 +3980,7 @@ async fn apply_patch_document( let mut materialized = current.clone(); let mut changed = Map::new(); let mut mutated = false; + let mut deferred_topology = Vec::new(); for (index, operation) in operations.iter().enumerate() { let at = |member| patch_location(index, member); match operation { @@ -3794,10 +4000,16 @@ async fn apply_patch_document( } written_sql_value(&request.plan.entity, field, value) .map_err(|_| at(PatchMember::Value))?; - validate_polygon_topology(transaction, &field.field_type, value, || { - at(PatchMember::Value) - }) - .await?; + if membership.is_some() + && matches!(field.field_type, FieldTypeSource::Crs84Polygon { .. }) + { + deferred_topology.push((index, &field.field_type, value)); + } else { + validate_polygon_topology(transaction, &field.field_type, value, || { + at(PatchMember::Value) + }) + .await?; + } materialized.insert(field_id.clone(), value.clone()); changed.insert(field_id, value.clone()); mutated = true; @@ -3846,6 +4058,17 @@ async fn apply_patch_document( if !mutated { return Err(MutationError::InvalidRequest); } + if let Some(membership) = membership { + // The patch interpreter has validated the values and run the tests. + // Check its final key before asking PostgreSQL to check topology. + membership.authorize_proposed(&materialized)?; + for (index, field_type, value) in deferred_topology { + validate_polygon_topology(transaction, field_type, value, || { + patch_location(index, PatchMember::Value) + }) + .await?; + } + } Ok(changed) } diff --git a/crates/registry-breg/src/mutation/action.rs b/crates/registry-breg/src/mutation/action.rs index 084c6b8d4e..d3e2c19331 100644 --- a/crates/registry-breg/src/mutation/action.rs +++ b/crates/registry-breg/src/mutation/action.rs @@ -88,10 +88,21 @@ impl ImmediateActionExecutionOutcome { } } +mod membership; +use membership::ActionMembership; + +#[derive(Clone, Copy, Eq, PartialEq)] +enum TargetRead { + Lock, + MembershipPreRead, + EvidencePreflight, +} + struct LockedActionTargets { guard_failure: Option, rows: BTreeMap<(String, Uuid), CurrentRow>, missing_timer_link: bool, + missing_target: bool, } enum TimerActionPreflight { @@ -270,6 +281,7 @@ impl MutationTransaction { None, Some(authority), &[], + None, ) .await; let definite_refusal = failure_is_refusal(&result) && !fault.is_enabled(); @@ -554,6 +566,7 @@ impl MutationTransaction { pub(crate) async fn execute_immediate_action( &self, client: &mut Client, + pool: &crate::postgres::RuntimePool, registry: &CompiledRegistry, input: ImmediateActionInput<'_>, claims: &ActionClaimContext, @@ -602,8 +615,13 @@ impl MutationTransaction { }, )?; let reserved_creates = reserve_action_create_ids(action)?; - self.stage_action_attachments(client, claims, &attachments, deadline) - .await?; + let staging_pool = if claims.locks_membership() { + Some(pool) + } else { + self.stage_action_attachments(client, claims, &attachments, deadline) + .await?; + None + }; let mut candidate = None; let trusted_now = time::OffsetDateTime::now_utc(); let application_id = Uuid::new_v4(); @@ -632,6 +650,7 @@ impl MutationTransaction { None, None, &attachments, + staging_pool, ) .await; if matches!(attempt, Err(MutationError::RetryableConflict)) @@ -694,20 +713,100 @@ impl MutationTransaction { .set_statement_budget(deadline.saturating_duration_since(tokio::time::Instant::now())) .await .map_err(|_| MutationError::Unavailable)?; + self.stage_attachment_rows(guarded.transaction(), attachments) + .await?; + guarded + .commit() + .await + .map_err(|_| MutationError::Unavailable) + } + + async fn stage_membership_action_attachments( + &self, + pool: &crate::postgres::RuntimePool, + claims: &ActionClaimContext, + attachments: &[ActionRequestAttachment], + deadline: tokio::time::Instant, + ) -> Result<(), MutationError> { + if attachments.is_empty() + || !matches!( + self.attachment_storage, + crate::attachment_storage::AttachmentStorage::S3(_) + ) + { + return Ok(()); + } + // The parent has admitted the package and holds the target and + // membership locks. Holding that package lock across staging also + // avoids joining a queue behind a waiting exclusive activation. + tokio::time::timeout_at(deadline, async { + let mut staging = pool + .attachment_staging_connection() + .await + .map_err(|_| MutationError::Unavailable)?; + let result = async { + let transaction = staging + .client() + .transaction() + .await + .map_err(map_database_error)?; + let remaining = deadline.saturating_duration_since(tokio::time::Instant::now()); + if remaining < Duration::from_millis(1) { + return Err(MutationError::Unavailable); + } + crate::postgres::set_transaction_statement_budget(&transaction, remaining) + .await + .map_err(|_| MutationError::Unavailable)?; + transaction + .execute( + "SELECT set_config('lock_timeout', $1, true), + set_config('registry.principal', $2, true), + set_config('registry.active_package_revision', $3, true)", + &[ + &format!("{}ms", self.lock_timeout.as_millis()), + &claims.principal(), + &self.expected.activation_id, + ], + ) + .await + .map_err(map_database_error)?; + crate::postgres::verify_registry_transaction_identity( + &transaction, + self.lock_key, + &self.expected, + ) + .await + .map_err(|_| MutationError::Unavailable)?; + self.stage_attachment_rows(&transaction, attachments) + .await?; + transaction.commit().await.map_err(map_database_error) + } + .await; + staging.disarm(); + result + }) + .await + .map_err(|_| MutationError::Unavailable)? + } + + async fn stage_attachment_rows( + &self, + transaction: &Transaction<'_>, + attachments: &[ActionRequestAttachment], + ) -> Result<(), MutationError> { + let backend = self.attachment_storage.binding_digest(); + let verification = self.attachment_verification.binding_digest(); for attachment in attachments_in_lock_order(attachments) { crate::attachment_store::stage_external( - guarded.transaction(), + transaction, &attachment.sha256, attachment.content.len() as u64, - &self.attachment_storage.binding_digest(), - &self.attachment_verification.binding_digest(), + &backend, + &verification, ) .await?; } - guarded - .commit() - .await - .map_err(|_| MutationError::Unavailable) + Ok(()) } /// Fill each record slot the Action declares from its file, in the @@ -1176,17 +1275,12 @@ impl MutationTransaction { }; // A hook holds no claims, so a grant that row-boundaries its targets // can never be satisfied by this path and is refused outright. - let mut target_authority = BTreeMap::>::new(); - for target in grant.entity_target_locks() { - if target.row_boundaries.is_empty() { - target_authority.insert(target.entity_id.clone(), Vec::new()); - } else { - return refused_proposal( - "hook.proposal.boundaries-unsatisfiable", - "The declared principal's grant carries row boundaries a hook holds no claims to satisfy.", - ); - } - } + let Some(target_authority) = hook_target_authority(grant) else { + return refused_proposal( + "hook.proposal.boundaries-unsatisfiable", + "The declared principal's grant carries row boundaries a hook holds no claims to satisfy.", + ); + }; if validate_action_claims(action, &claims, Operation::Invoke).is_err() { return refused_proposal( "hook.proposal.unauthorized", @@ -1342,6 +1436,7 @@ impl MutationTransaction { Some(&causation), None, &[], + None, ) .await; if matches!(attempt, Err(MutationError::RetryableConflict)) @@ -1383,7 +1478,11 @@ impl MutationTransaction { // applies again either. return conflicting_hook_answer(); } - Err(MutationError::PreconditionFailed | MutationError::FieldGuardFailed { .. }) => { + Err( + MutationError::PreconditionFailed + | MutationError::MembershipPreconditionFailed + | MutationError::FieldGuardFailed { .. }, + ) => { return refused_proposal( "hook.proposal.precondition-failed", "The proposed mutation found its target in an unexpected state.", @@ -1541,6 +1640,7 @@ impl MutationTransaction { causation: Option<&Causation>, timer_authority: Option<&TimerActionAuthority>, attachments: &[ActionRequestAttachment], + staging_pool: Option<&crate::postgres::RuntimePool>, ) -> Result { if tokio::time::Instant::now() >= deadline { return Err(MutationError::Unavailable); @@ -1555,12 +1655,13 @@ impl MutationTransaction { ) .await } else { - begin_action_transaction( + crate::postgres::begin_action_transaction_for_write( client, self.lock_key, self.lock_timeout, &self.expected, claims, + claims.locks_membership(), ) .await } @@ -1635,6 +1736,7 @@ impl MutationTransaction { preconditions, timer_authority, trusted_now, + TargetRead::Lock, ) .await?; let entity = registry @@ -1737,8 +1839,38 @@ impl MutationTransaction { application_id, )?; - let guard_failure = match locked_timer_targets.take() { - Some(locked) => locked.guard_failure, + let mut membership = if claims.locks_membership() { + let observed = self + .lock_existing_action_targets( + transaction.transaction(), + registry, + action, + claims, + target_authority, + input_values, + application_id, + preconditions, + None, + trusted_now, + TargetRead::MembershipPreRead, + ) + .await?; + Some( + ActionMembership::acquire( + transaction.transaction(), + claims, + &observed, + effects, + input_values, + reserved_creates, + ) + .await?, + ) + } else { + None + }; + let locked_targets = match locked_timer_targets.take() { + Some(locked) => locked, None => { self.lock_existing_action_targets( transaction.transaction(), @@ -1751,9 +1883,9 @@ impl MutationTransaction { preconditions, timer_authority, trusted_now, + TargetRead::Lock, ) .await? - .guard_failure } }; @@ -1784,6 +1916,7 @@ impl MutationTransaction { claims, target_authority, input_values, + true, ) .await?; } @@ -1799,8 +1932,12 @@ impl MutationTransaction { preconditions, application_id, timer_authority, + true, ) .await?; + if let Some(membership) = &membership { + membership.verify_current(claims, &locked_targets)?; + } if let Some(timer) = timer_authority { let anchor = locked_timer_anchor .as_ref() @@ -1835,16 +1972,61 @@ impl MutationTransaction { // Before surfacing a failed guard, finish every current-target and // admission precheck above and recheck the grant. Effect application and // proposed-value authorization below run only after guards pass. - if let Some(input) = guard_failure { + if let Some(input) = locked_targets.guard_failure { check_current_action_grant(claims)?; return Err(MutationError::FieldGuardFailed { input }); } let ordered = ordered_action_effects(effects)?; let groups = ordered_action_effect_groups(&ordered, &patch_bases, reserved_creates)?; - let mut rows = BTreeMap::::new(); + if let Some(membership) = &mut membership { + for group in &groups { + let effect = group[0]; + let entity = registry + .entities() + .get(&effect.target.entity_id) + .ok_or(MutationError::InvalidRequest)?; + let (_, id) = action_effect_target_key(effect, &patch_bases, reserved_creates)?; + let base = patch_bases.get(&effect.id); + let target = action_target_group_context( + registry, + action, + group, + claims, + target_authority, + id, + base.map(|row| row.record_revision), + false, + Some(application_id), + &self.expected.activation_id, + None, + )?; + let mut preview = base.map(|row| row.data.clone()).unwrap_or_default(); + preview.extend(action_effect_group_document( + action, + entity, + group, + input_values, + reserved_creates, + )?); + membership.authorize_effect( + claims.access_profile(), + target.membership_boundaries(), + &preview, + )?; + match effect.operation { + Operation::Create => { + target.authorize_create_before_allocation(entity, &preview, id) + } + _ => target.authorize_rows(entity, base.map(|row| &row.data), &preview, id), + } + .map_err(|_| MutationError::PreconditionFailed)?; + } + } + let mut rows = BTreeMap::::new(); let mut timer_rows = BTreeMap::<(String, Uuid), CurrentRow>::new(); let mut results = Vec::::new(); for effects in groups { + let effect = effects[0]; fault.fail_at(MutationFaultPoint::BeforeCurrentRow)?; let current = self .apply_action_effect_group( @@ -1862,7 +2044,15 @@ impl MutationTransaction { timer_authority, ) .await?; - let effect = effects[0]; + if let Some(membership) = &membership { + if claims.is_membership_source(&effect.target.entity_id) { + // The locks fence other transactions. This transaction + // can change its own proof before a later effect uses it. + membership + .recheck_used_authority(transaction.transaction()) + .await?; + } + } let record_reference = record_reference( self.audit.profile(), &self.expected.activation_id, @@ -1947,7 +2137,7 @@ impl MutationTransaction { record_reference: record_reference.clone(), operation: effect.operation, }); - rows.insert(effect.id.clone(), current.clone()); + rows.insert(effect.id.clone(), current.record_uuid); } let timer_key = (entity.id.clone(), current.record_uuid); if let Some(previous) = timer_rows.insert(timer_key, current.clone()) { @@ -1987,6 +2177,24 @@ impl MutationTransaction { ) .await?; + // Like Proposal Apply, finish attachment work before taking the history + // head. Membership staging must also finish before the parent takes + // any attachment hash lock. + if let Some(pool) = staging_pool { + check_current_action_grant(claims)?; + self.stage_membership_action_attachments(pool, claims, attachments, deadline) + .await?; + } + self.write_action_attachments( + transaction.transaction(), + action, + claims, + binding, + &results, + attachments, + ) + .await?; + // Several effects may share one final record revision. Index each // distinct revision once, under the action transaction's one commit, // just as the single-record and batch mutation paths do. @@ -2022,15 +2230,6 @@ impl MutationTransaction { }, ) .await?; - self.write_action_attachments( - transaction.transaction(), - action, - claims, - binding, - &results, - attachments, - ) - .await?; let held = action_held_response(action, claims, application_id, &results)?; let public_result_count = u16::try_from( @@ -2219,7 +2418,7 @@ impl MutationTransaction { input_values: &ActionInputs, patch_bases: &BTreeMap, reserved_creates: &BTreeMap, - prior_results: &BTreeMap, + prior_results: &BTreeMap, application_id: Uuid, timer_authority: Option<&TimerActionAuthority>, ) -> Result { @@ -2276,22 +2475,8 @@ impl MutationTransaction { ) .await .map_err(map_database_error)?; - let mut fields = Map::new(); - for effect in effects { - let effect_fields = action_effect_document( - action, - entity, - effect, - input_values, - prior_results, - before, - )?; - for (field, value) in effect_fields { - if fields.insert(field, value).is_some() { - return Err(MutationError::InvalidRequest); - } - } - } + let mut fields = + action_effect_group_document(action, entity, effects, input_values, prior_results)?; if effect.operation == Operation::Create { crate::generated_identifiers::reserve_for_create(transaction, entity, &mut fields) .await?; @@ -2348,6 +2533,7 @@ impl MutationTransaction { preconditions: &BTreeMap, timer_authority: Option<&TimerActionAuthority>, trusted_now: time::OffsetDateTime, + read: TargetRead, ) -> Result { #[derive(Clone, Copy)] enum Role<'a> { @@ -2363,6 +2549,7 @@ impl MutationTransaction { let mut guard_failure = None; let mut rows = BTreeMap::new(); let mut missing_timer_link = false; + let mut missing_target = false; for effect in &action.effects { if let CompiledPlanTargetBinding::Existing { input } = &effect.target.binding { let record_id = Uuid::parse_str(&input_record_id(input_values, input)?) @@ -2507,17 +2694,27 @@ impl MutationTransaction { ) .await .map_err(map_database_error)?; - let mut current = - match load_action_row(transaction, entity, &record_id.to_string(), true).await { - Ok(current) => current, - Err(MutationError::PreconditionFailed) - if timer_authority.is_some() && matches!(role, Role::Link(_)) => - { - missing_timer_link = true; - continue; - } - Err(error) => return Err(error), - }; + let mut current = match load_action_row( + transaction, + entity, + &record_id.to_string(), + read == TargetRead::Lock, + ) + .await + { + Ok(current) => current, + Err(MutationError::PreconditionFailed) + if timer_authority.is_some() && matches!(role, Role::Link(_)) => + { + missing_timer_link = true; + continue; + } + Err(MutationError::PreconditionFailed) if read == TargetRead::MembershipPreRead => { + missing_target = true; + continue; + } + Err(error) => return Err(error), + }; if let (Role::Link(input), Some(timer)) = (role, timer_authority) { let fields = timer.read_fields_for_input(action, input, entity_id)?; timer.materialize_read_fields( @@ -2527,18 +2724,30 @@ impl MutationTransaction { self.field_encryption.as_deref(), )?; } - verify_action_requirements( - entity, - action, - input_values, - record_id, - ¤t, - self.audit.profile(), - registry, - trusted_now, - preconditions, - &mut guard_failure, - )?; + if read == TargetRead::EvidencePreflight { + probe_action_memberships( + transaction, + claims.access_profile(), + claims.target_membership(entity_id), + Some(current.record_uuid), + ¤t.data, + ) + .await?; + } + if read != TargetRead::MembershipPreRead { + verify_action_requirements( + entity, + action, + input_values, + record_id, + ¤t, + self.audit.profile(), + registry, + trusted_now, + preconditions, + &mut guard_failure, + )?; + } rows.insert((entity_id.to_owned(), record_id), current); } transaction @@ -2553,6 +2762,7 @@ impl MutationTransaction { guard_failure, rows, missing_timer_link, + missing_target, }) } @@ -2568,6 +2778,7 @@ impl MutationTransaction { preconditions: &BTreeMap, application_id: Uuid, timer_authority: Option<&TimerActionAuthority>, + lock: bool, ) -> Result, MutationError> { let mut patch_targets = BTreeMap::<(String, Uuid), Vec<(&str, &CompiledPlanEffect, String)>>::new(); @@ -2614,7 +2825,7 @@ impl MutationTransaction { ) .await .map_err(map_database_error)?; - let current = load_action_row(transaction, entity, &target_effects[0].2, true).await?; + let current = load_action_row(transaction, entity, &target_effects[0].2, lock).await?; // A `current-revision` Action sends no condition: its commit guards // were evaluated against this same locked row. if timer_authority.is_none() && action.concurrency.is_condition_required() { @@ -2657,6 +2868,16 @@ impl MutationTransaction { current.record_uuid, ) .map_err(|_| MutationError::PreconditionFailed)?; + if !lock { + probe_action_memberships( + transaction, + claims.access_profile(), + target_context.membership_boundaries(), + Some(current.record_uuid), + ¤t.data, + ) + .await?; + } for (_, effect, _) in target_effects { bases.insert(effect.id.clone(), current.clone()); } @@ -2739,6 +2960,14 @@ impl MutationTransaction { current.record_uuid, ) .map_err(|_| MutationError::PreconditionFailed)?; + probe_action_memberships( + transaction.transaction(), + claims.access_profile(), + target_context.membership_boundaries(), + Some(current.record_uuid), + ¤t.data, + ) + .await?; current } else { let link_context = action_link_context( @@ -2760,6 +2989,14 @@ impl MutationTransaction { link_context .authorize_row(entity, ¤t.data, current.record_uuid) .map_err(|_| MutationError::PreconditionFailed)?; + probe_action_memberships( + transaction.transaction(), + claims.access_profile(), + link_context.membership_boundaries(), + Some(current.record_uuid), + ¤t.data, + ) + .await?; current }; conditions.insert( @@ -2812,6 +3049,7 @@ impl MutationTransaction { Ok(held) } + #[allow(clippy::too_many_arguments)] // The read mode and authority belong to one Action invocation. async fn verify_action_link_references( &self, transaction: &Transaction<'_>, @@ -2820,6 +3058,7 @@ impl MutationTransaction { claims: &ActionClaimContext, target_authority: &BTreeMap>, input_values: &ActionInputs, + lock: bool, ) -> Result<(), MutationError> { let mut refs = Vec::new(); for target_use in &action.target_uses { @@ -2863,10 +3102,20 @@ impl MutationTransaction { ) .await .map_err(map_database_error)?; - let current = load_action_row(transaction, entity, &record_id, true).await?; + let current = load_action_row(transaction, entity, &record_id, lock).await?; link_context .authorize_row(entity, ¤t.data, current.record_uuid) .map_err(|_| MutationError::PreconditionFailed)?; + if !lock { + probe_action_memberships( + transaction, + claims.access_profile(), + link_context.membership_boundaries(), + Some(current.record_uuid), + ¤t.data, + ) + .await?; + } } Ok(()) } @@ -2962,6 +3211,14 @@ impl MutationTransaction { current.record_uuid, ) .map_err(|_| MutationError::PreconditionFailed)?; + probe_action_memberships( + transaction, + claims.access_profile(), + target_context.membership_boundaries(), + Some(current.record_uuid), + ¤t.data, + ) + .await?; } } Ok(()) @@ -3031,6 +3288,18 @@ fn conflicting_hook_answer() -> Result { ) } +fn hook_target_authority( + grant: &crate::model::CompiledActionPermission, +) -> Option>> { + grant + .entity_target_locks() + .map(|target| { + (target.row_boundaries.is_empty() && target.membership_boundaries.is_empty()) + .then(|| (target.entity_id.clone(), Vec::new())) + }) + .collect() +} + fn hook_change_idempotency_key(event_id: Uuid, compiled_delivery_id: &str) -> String { // The application identity is the hook delivery identity, // domain-separated. No attempt, generation, or answer component enters @@ -3569,12 +3838,32 @@ fn action_effect_target_key( Ok((effect.target.entity_id.clone(), record_uuid)) } +fn action_effect_group_document( + action: &CompiledAction, + entity: &CompiledEntity, + effects: &[&CompiledPlanEffect], + inputs: &ActionInputs, + references: &BTreeMap, +) -> Result, MutationError> { + let mut fields = Map::new(); + for effect in effects { + for (field, value) in + action_effect_document(action, entity, effect, inputs, references, None)? + { + if fields.insert(field, value).is_some() { + return Err(MutationError::InvalidRequest); + } + } + } + Ok(fields) +} + fn action_effect_document( action: &CompiledAction, entity: &CompiledEntity, effect: &CompiledPlanEffect, input_values: &ActionInputs, - prior_results: &BTreeMap, + prior_results: &BTreeMap, _before: Option<&CurrentRow>, ) -> Result, MutationError> { let mut data = Map::new(); @@ -3616,10 +3905,10 @@ fn action_effect_document( if target_entity_id != &source.target.entity_id { return Err(MutationError::InvalidRequest); } - let row = prior_results + let id = prior_results .get(effect) .ok_or(MutationError::InvalidRequest)?; - Value::String(row.record_id.clone()) + Value::String(id.to_string()) } }; if !validate_field_value(FieldValue::Json(&value), &field_source.field_type) @@ -4056,6 +4345,16 @@ impl MutationTransaction { context .authorize_row(entity, ¤t.data, uuid) .map_err(|_| MutationError::PreconditionFailed)?; + // At READ COMMITTED this read can see a different revision from + // the earlier Link check. Authorize the exact selector snapshot. + probe_action_memberships( + transaction, + claims.access_profile(), + context.membership_boundaries(), + Some(uuid), + ¤t.data, + ) + .await?; let values = fields .into_iter() .map(|field| { @@ -4258,6 +4557,7 @@ impl MutationTransaction { &input.preconditions, None, trusted_now, + TargetRead::EvidencePreflight, ) .await? .guard_failure; @@ -4268,20 +4568,23 @@ impl MutationTransaction { claims, target_authority, &normalized, + false, ) .await?; - self.lock_action_patch_targets( - transaction.transaction(), - registry, - action, - claims, - target_authority, - &normalized, - &input.preconditions, - application_id, - None, - ) - .await?; + let patch_bases = self + .lock_action_patch_targets( + transaction.transaction(), + registry, + action, + claims, + target_authority, + &normalized, + &input.preconditions, + application_id, + None, + false, + ) + .await?; let commit_requests = self .action_commit_evidence_requests( transaction.transaction(), @@ -4299,6 +4602,19 @@ impl MutationTransaction { if let Some(input) = guard_failure { return Err(MutationError::FieldGuardFailed { input }); } + if claims.locks_membership() { + membership::preflight_evidence( + transaction.transaction(), + registry, + action, + claims, + target_authority, + &normalized, + &patch_bases, + &reserved_creates, + ) + .await?; + } transaction .commit() .await @@ -4359,6 +4675,7 @@ impl MutationTransaction { None, None, &[], + None, ) .await; if matches!(result, Err(MutationError::RetryableConflict)) @@ -4499,6 +4816,56 @@ pub(crate) async fn erase_expired_action_evidence( mod tests { use super::*; + #[test] + fn hooks_refuse_claim_and_membership_boundaries_on_the_same_path() { + use crate::model::{ + CompiledActionPermission, CompiledActionTargetPermission, + CompiledActionTargetUseSource, CompiledMembershipBoundary, + }; + let mut grant = CompiledActionPermission { + profile_id: "operator".into(), + default: false, + actor_kind: None, + task_grant: None, + requester_clients: BTreeSet::new(), + principal_claim: Some("sub".into()), + required_scopes: BTreeSet::from(["records:write".into()]), + required_purposes: BTreeSet::new(), + operations: BTreeSet::from([Operation::Invoke]), + targets: vec![CompiledActionTargetPermission { + entity_id: "target".into(), + operation: Operation::Create, + source: CompiledActionTargetUseSource::Effect { + effect: "create".into(), + }, + row_boundaries: Vec::new(), + membership_boundaries: Vec::new(), + }], + results: BTreeSet::from(["create".into()]), + }; + assert!(hook_target_authority(&grant).is_some()); + grant.targets[0] + .row_boundaries + .push(crate::contract::RowBoundarySource { + field: "owner".into(), + claim: "sub".into(), + operator: crate::contract::BoundaryOperator::Equals, + }); + assert!(hook_target_authority(&grant).is_none()); + grant.targets[0].row_boundaries.clear(); + grant.targets[0] + .membership_boundaries + .push(CompiledMembershipBoundary { + field: "owner".into(), + membership_entity: "members".into(), + membership_table: "members".into(), + membership_key_column: "key".into(), + principal_column: "principal".into(), + active_column: "active".into(), + }); + assert!(hook_target_authority(&grant).is_none()); + } + #[test] fn ordinary_action_binding_keeps_the_released_canonical_shape() { let profile = AuditProfile::unkeyed_dev_only(); diff --git a/crates/registry-breg/src/mutation/action/membership.rs b/crates/registry-breg/src/mutation/action/membership.rs new file mode 100644 index 0000000000..35cd670677 --- /dev/null +++ b/crates/registry-breg/src/mutation/action/membership.rs @@ -0,0 +1,713 @@ +// SPDX-License-Identifier: Apache-2.0 + +use super::*; +use crate::action_outcome::{decode_slot_mutations, ProposedValue}; +use crate::membership::target_function_name; +use crate::model::{CompiledMembershipBoundary, CompiledPlanWrite}; +use crate::mutation::membership::{ + json_key, keys_for_row, probe, probe_action_membership, probe_action_memberships, LockKey, + MembershipLocks, +}; +use crate::postgres::snapshot_matches_boundaries; + +pub(super) struct ActionMembership { + keys: BTreeMap<(String, Uuid), Vec>>, + locks: MembershipLocks, + used: BTreeSet, +} + +impl ActionMembership { + pub(super) async fn acquire( + transaction: &Transaction<'_>, + claims: &ActionClaimContext, + observed: &LockedActionTargets, + effects: &[CompiledPlanEffect], + inputs: &ActionInputs, + reserved: &BTreeMap, + ) -> Result { + let profile = claims.access_profile(); + let mut needed = BTreeSet::new(); + let mut keys = BTreeMap::new(); + for ((entity, id), row) in &observed.rows { + let boundaries = claims.target_membership(entity); + if boundaries.is_empty() { + continue; + } + let existing = keys_for_row(boundaries, Some(*id), &row.data); + for (boundary, key) in boundaries.iter().zip(&existing) { + MembershipLocks::collect(&mut needed, profile, boundary, *key); + } + keys.insert((entity.clone(), *id), existing); + } + for effect in effects { + for boundary in claims.target_membership(&effect.target.entity_id) { + for mutation in &effect.mutations { + if let CompiledPlanMutation::Set { field, value } = mutation { + if field == &boundary.field { + let key = match value { + CompiledPlanValue::FromInput { input } => { + json_key(inputs.get(input)) + } + CompiledPlanValue::FromEffect { effect, .. } => { + reserved.get(effect).copied() + } + CompiledPlanValue::Literal { value } => json_key(Some(value)), + }; + MembershipLocks::collect(&mut needed, profile, boundary, key); + } + } + } + } + } + let mut membership = Self { + keys, + locks: MembershipLocks::acquire(transaction, needed).await?, + used: BTreeSet::new(), + }; + if observed.missing_target { + return Err(MutationError::PreconditionFailed); + } + for ((entity, _), keys) in &membership.keys { + for (boundary, key) in claims.target_membership(entity).iter().zip(keys) { + record_admission( + &membership.locks, + &mut membership.used, + profile, + boundary, + *key, + )?; + } + } + Ok(membership) + } + + pub(super) fn verify_current( + &self, + claims: &ActionClaimContext, + current: &LockedActionTargets, + ) -> Result<(), MutationError> { + for ((entity, id), expected) in &self.keys { + let row = current + .rows + .get(&(entity.clone(), *id)) + .ok_or(MutationError::MembershipPreconditionFailed)?; + if keys_for_row(claims.target_membership(entity), Some(*id), &row.data) != *expected { + return Err(MutationError::RetryableConflict); + } + } + Ok(()) + } + + pub(super) fn authorize_effect( + &mut self, + profile: &str, + boundaries: &[CompiledMembershipBoundary], + proposed: &Map, + ) -> Result<(), MutationError> { + for (boundary, key) in boundaries + .iter() + .zip(keys_for_row(boundaries, None, proposed)) + { + record_admission(&self.locks, &mut self.used, profile, boundary, key)?; + } + Ok(()) + } + + pub(super) async fn recheck_used_authority( + &self, + transaction: &Transaction<'_>, + ) -> Result<(), MutationError> { + for (helper, key) in &self.used { + if !probe(transaction, helper, *key).await? { + return Err(MutationError::MembershipPreconditionFailed); + } + } + Ok(()) + } +} + +fn record_admission( + locks: &MembershipLocks, + used: &mut BTreeSet, + profile: &str, + boundary: &CompiledMembershipBoundary, + key: Option, +) -> Result<(), MutationError> { + let key = key + .filter(|key| locks.allows(profile, boundary, Some(*key))) + .ok_or(MutationError::MembershipPreconditionFailed)?; + used.insert(( + target_function_name(profile, &boundary.membership_entity), + key, + )); + Ok(()) +} + +#[allow(clippy::too_many_arguments)] +pub(super) async fn preflight_evidence( + transaction: &Transaction<'_>, + registry: &CompiledRegistry, + action: &CompiledAction, + claims: &ActionClaimContext, + target_authority: &BTreeMap>, + inputs: &ActionInputs, + patch_bases: &BTreeMap, + reserved: &BTreeMap, +) -> Result<(), MutationError> { + let profile = claims.access_profile(); + if let Some(handler) = &action.handler { + for slot in &handler.writes { + let entity_id = &slot.ceiling.target_entity_id; + let entity = registry + .entities() + .get(entity_id) + .ok_or(MutationError::InvalidRequest)?; + let disclosure = crate::disclosure::plan(entity, profile); + let base = patch_bases.get(&slot.id); + if function_slot_can_write( + &slot.ceiling, + claims.target_membership(entity_id), + base.map(|base| &base.data), + inputs, + |field| { + entity + .fields + .get(field) + .is_some_and(|field| field.encryption.is_some()) + }, + |field, value| { + let (Some(boundaries), Some(base)) = (target_authority.get(entity_id), base) + else { + return false; + }; + permits_patch_value(entity, &disclosure, boundaries, base, field, value) + }, + |boundary, key| probe_action_membership(transaction, profile, boundary, Some(key)), + ) + .await? + { + return Ok(()); + } + } + return Err(MutationError::MembershipPreconditionFailed); + } + let ordered = ordered_action_effects(&action.effects)?; + for group in ordered_action_effect_groups(&ordered, patch_bases, reserved)? { + let effect = group[0]; + let entity = registry + .entities() + .get(&effect.target.entity_id) + .ok_or(MutationError::InvalidRequest)?; + let mut preview = patch_bases + .get(&effect.id) + .map(|base| base.data.clone()) + .unwrap_or_default(); + preview.extend(action_effect_group_document( + action, entity, &group, inputs, reserved, + )?); + probe_action_memberships( + transaction, + profile, + claims.target_membership(&entity.id), + None, + &preview, + ) + .await?; + } + Ok(()) +} + +fn permits_patch_value( + entity: &CompiledEntity, + disclosure: &crate::disclosure::DisclosurePlan<'_>, + boundaries: &[RowBoundaryContext], + base: &CurrentRow, + field: &str, + value: &Value, +) -> bool { + if link_key_refused(entity, field, value) { + return false; + } + // The base row already passed its claim boundaries. Only predicates on + // the emitted field need to be checked against the candidate value. + let changed = Map::from_iter([(field.to_owned(), value.clone())]); + boundaries + .iter() + .filter(|boundary| boundary.field() == field) + .all(|boundary| { + snapshot_matches_boundaries( + entity, + &changed, + base.record_uuid, + std::slice::from_ref(boundary), + ) + .is_ok_and(|matches| matches) + }) + && matches!( + plan_write_disclosure(disclosure, Some(&base.data), &changed), + PlanWriteDisclosure::RecordVisible { update: Ok(()) } + ) +} + +async fn function_slot_can_write<'a, F>( + ceiling: &CompiledPlanWrite, + boundaries: &'a [CompiledMembershipBoundary], + base: Option<&Map>, + inputs: &ActionInputs, + is_encrypted: impl Fn(&str) -> bool, + permits_value: impl Fn(&str, &Value) -> bool, + mut probe_membership: impl FnMut(&'a CompiledMembershipBoundary, Uuid) -> F, +) -> Result +where + F: std::future::Future> + Send, +{ + let patch = ceiling.operation == Operation::Patch; + let mut has_mutation = !patch; + let mut by_field = BTreeMap::<&str, Vec<&CompiledMembershipBoundary>>::new(); + for boundary in boundaries { + by_field.entry(&boundary.field).or_default().push(boundary); + } + for (&field, boundaries) in &by_field { + // A covered field can be set from a declared input or retained by + // omission. A fresh create ID cannot supply current membership. + let mut candidates = reference_input_values(ceiling, field, inputs) + .filter(|value| !patch || permits_value(field, value)) + .filter_map(|value| json_key(Some(value)).map(|key| (key, true))) + .collect::>(); + if let Some(existing) = base.and_then(|base| json_key(base.get(field))) { + candidates.entry(existing).or_insert(false); + } + let mut authorized = false; + for (key, emits_mutation) in candidates { + let mut permitted = true; + for &boundary in boundaries { + if !probe_membership(boundary, key).await? { + permitted = false; + break; + } + } + if permitted { + authorized = true; + has_mutation |= emits_mutation; + if has_mutation { + break; + } + } + } + if !authorized { + return Ok(false); + } + } + // Every membership constraint is satisfiable. A Patch still needs a + // permitted set or clear somewhere in its authored ceiling. + Ok(has_mutation + || base.is_some_and(|base| { + ceiling.fields.iter().any(|field| { + !by_field.contains_key(field.as_str()) + && independent_patch_mutation( + ceiling, + field, + base, + inputs, + is_encrypted(field), + &permits_value, + ) + }) + })) +} + +fn reference_input_values<'a>( + ceiling: &'a CompiledPlanWrite, + field: &str, + inputs: &'a ActionInputs, +) -> impl Iterator { + ceiling + .reference_sources + .get(field) + .filter(|_| ceiling.fields.contains(field)) + .into_iter() + .flat_map(|sources| &sources.inputs) + .filter_map(|input| inputs.get(input)) +} + +fn independent_patch_mutation( + ceiling: &CompiledPlanWrite, + field: &str, + base: &Map, + inputs: &ActionInputs, + encrypted: bool, + permits_value: &impl Fn(&str, &Value) -> bool, +) -> bool { + if !ceiling.required_fields.contains(field) && permits_value(field, &Value::Null) { + return true; + } + if matches!( + ceiling.field_types.get(field), + Some(FieldTypeSource::Reference { .. }) + ) { + // FromEffect requires an emitted Create slot. A permitted Create can + // satisfy preflight itself, independently of this dependent Patch. + return reference_input_values(ceiling, field, inputs) + .any(|value| json_key(Some(value)).is_some() && permits_value(field, value)); + } + let permits_literal = |value: &Value| { + let members = [( + "set".to_owned(), + ProposedValue::Object(vec![(field.to_owned(), json_document(value.clone()))]), + )]; + decode_slot_mutations(ceiling, &members).is_ok() && permits_value(field, value) + }; + // Encrypted members in a stored row are opaque envelopes. Use a fresh + // typed witness when one is available without opening the stored value. + if !encrypted && base.get(field).is_some_and(permits_literal) { + return true; + } + // A previously stored string can exceed the Function ABI's byte bound + // even when a shorter literal of the same field type is representable. + let witness = match ceiling.field_types.get(field) { + Some(FieldTypeSource::String { min_length, .. }) + if *min_length as usize <= crate::rhai_planner::MAXIMUM_STRING_BYTES => + { + "a".repeat((*min_length as usize).max(1)) + } + Some(FieldTypeSource::Text { .. }) => "a".to_owned(), + Some(FieldTypeSource::Date) if encrypted => "2000-01-01".to_owned(), + Some(FieldTypeSource::Decimal { + scale, + minimum, + maximum, + .. + }) if encrypted => minimum + .as_ref() + .or(maximum.as_ref()) + .cloned() + .unwrap_or_else(|| { + if *scale == 0 { + "0".to_owned() + } else { + format!("0.{}", "0".repeat(usize::from(*scale))) + } + }), + _ => return false, + }; + permits_literal(&Value::String(witness)) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::model::CompiledPlanReferenceSources; + + const RETAINED: Uuid = Uuid::from_u128(1); + const ALLOWED: Uuid = Uuid::from_u128(2); + const REFUSED: Uuid = Uuid::from_u128(3); + + fn boundary(field: &str, source: &str) -> CompiledMembershipBoundary { + CompiledMembershipBoundary { + field: field.to_owned(), + membership_entity: source.to_owned(), + membership_table: String::new(), + membership_key_column: String::new(), + principal_column: String::new(), + active_column: String::new(), + } + } + + fn ceiling(fields: &[&str]) -> CompiledPlanWrite { + let reference = FieldTypeSource::Reference { + target: "key".to_owned(), + on_delete: Default::default(), + }; + CompiledPlanWrite { + target_entity_id: "target".to_owned(), + target_from_input: None, + operation: Operation::Patch, + fields: fields.iter().map(|field| (*field).to_owned()).collect(), + field_types: fields + .iter() + .map(|field| ((*field).to_owned(), reference.clone())) + .collect(), + required_fields: fields.iter().map(|field| (*field).to_owned()).collect(), + reference_sources: fields + .iter() + .map(|field| { + ( + (*field).to_owned(), + CompiledPlanReferenceSources { + inputs: BTreeSet::from([format!("{field}-input")]), + create_entities: BTreeSet::new(), + }, + ) + }) + .collect(), + } + } + + fn references(fields: &[(&str, Uuid)]) -> Map { + fields + .iter() + .map(|(field, key)| ((*field).to_owned(), Value::String(key.to_string()))) + .collect() + } + + async fn admits( + ceiling: &CompiledPlanWrite, + boundaries: &[CompiledMembershipBoundary], + base: &Map, + inputs: &ActionInputs, + ) -> bool { + function_slot_can_write( + ceiling, + boundaries, + Some(base), + inputs, + |_| false, + |_, _| true, + |boundary, key| { + std::future::ready(Ok( + key != REFUSED && !(boundary.membership_entity == "other" && key == ALLOWED) + )) + }, + ) + .await + .unwrap() + } + + #[tokio::test] + async fn omitting_covered_fields_cannot_supply_the_only_mutation() { + let ceiling = ceiling(&["first", "second"]); + let boundaries = [boundary("first", "source"), boundary("second", "source")]; + let base = references(&[("first", RETAINED), ("second", RETAINED)]); + let inputs = references(&[("first-input", REFUSED), ("second-input", REFUSED)]); + + assert!(!admits(&ceiling, &boundaries, &base, &inputs).await); + } + + #[tokio::test] + async fn one_covered_field_can_be_emitted_while_another_is_retained() { + let ceiling = ceiling(&["first", "second"]); + let boundaries = [boundary("first", "source"), boundary("second", "source")]; + let base = references(&[("first", RETAINED), ("second", RETAINED)]); + let inputs = references(&[("first-input", REFUSED), ("second-input", ALLOWED)]); + + assert!(admits(&ceiling, &boundaries, &base, &inputs).await); + } + + #[tokio::test] + async fn a_covered_field_must_satisfy_all_its_boundaries() { + let ceiling = ceiling(&["first", "second"]); + let boundaries = [ + boundary("first", "source"), + boundary("first", "other"), + boundary("second", "source"), + ]; + let base = references(&[("first", RETAINED), ("second", RETAINED)]); + let inputs = references(&[("first-input", ALLOWED), ("second-input", REFUSED)]); + + assert!(!admits(&ceiling, &boundaries, &base, &inputs).await); + } + + #[tokio::test] + async fn an_independently_writable_literal_allows_membership_keys_to_be_retained() { + let mut ceiling = ceiling(&["first", "second", "flag"]); + ceiling + .field_types + .insert("flag".to_owned(), FieldTypeSource::Boolean); + ceiling.reference_sources.remove("flag"); + let boundaries = [boundary("first", "source"), boundary("second", "source")]; + let mut base = references(&[("first", RETAINED), ("second", RETAINED)]); + base.insert("flag".to_owned(), Value::Bool(true)); + let inputs = references(&[("first-input", REFUSED), ("second-input", REFUSED)]); + + assert!(admits(&ceiling, &boundaries, &base, &inputs).await); + base.remove("second"); + assert!(!admits(&ceiling, &boundaries, &base, &inputs).await); + } + + #[tokio::test] + async fn an_independent_reference_requires_an_available_source_or_a_permitted_clear() { + let mut ceiling = ceiling(&["first", "other"]); + let boundaries = [boundary("first", "source")]; + let base = references(&[("first", RETAINED), ("other", RETAINED)]); + let mut inputs = references(&[("first-input", REFUSED)]); + assert!(!admits(&ceiling, &boundaries, &base, &inputs).await); + + inputs.extend(references(&[("other-input", ALLOWED)])); + assert!(admits(&ceiling, &boundaries, &base, &inputs).await); + + inputs.remove("other-input"); + ceiling.required_fields.remove("other"); + assert!(!independent_patch_mutation( + &ceiling, + "other", + &base, + &inputs, + false, + &|_, _| false, + )); + assert!(admits(&ceiling, &boundaries, &base, &inputs).await); + } + + #[tokio::test] + async fn a_single_covered_field_can_set_an_authorized_reference_input() { + let ceiling = ceiling(&["first"]); + let boundaries = [boundary("first", "source")]; + let base = references(&[("first", RETAINED)]); + + for key in [ALLOWED, RETAINED] { + let inputs = references(&[("first-input", key)]); + assert!(admits(&ceiling, &boundaries, &base, &inputs).await); + } + let inputs = references(&[("first-input", REFUSED)]); + assert!(!admits(&ceiling, &boundaries, &base, &inputs).await); + } + + #[test] + fn a_patch_candidate_obeys_the_selected_profiles_write_disclosure() { + let source = json!({ + "apiVersion":"id.registrystack.org/formats/breg/project/v1alpha1", + "kind":"BRegProject", + "project":{"id":"write-disclosure","version":"1","defaultLanguage":"en", + "canonicalBaseIri":"https://unit.example.test"}, + "datasets":{"example":{}}, + "recordTypes":{"entry":{"primaryDataset":"example","route":"entries", + "mutationMode":"mutable","fields":[ + {"id":"mark","type":"string","maximumLength":20,"classification":"internal"}, + {"id":"note","type":"string","maximumLength":20,"classification":"internal"}, + {"id":"flag","type":"boolean","classification":"internal"} + ], + "disclosureConditions":{ + "hide-row":{"when":[{"type":"field-equals","field":"mark","value":"closed"}], + "withhold":"record","exemptProfiles":["officer"]}, + "hide-note":{"when":[{"type":"field-equals","field":"mark","value":"marked"}], + "withhold":"fields","fields":["note"],"exemptProfiles":["officer"]} + } + }}, + "accessProfiles":{ + "clerk":{"default":true,"principalClaim":"sub","requiredScopes":["records:write"], + "permissions":{"records":[{"recordType":"entry","operations":["get"], + "rowBoundaries":"unrestricted","readableFields":["mark","note","flag"]}]}}, + "officer":{"principalClaim":"sub","requiredScopes":["records:write"], + "permissions":{"records":[{"recordType":"entry","operations":["get"], + "rowBoundaries":"unrestricted","readableFields":["mark","note","flag"]}]}} + } + }); + let project = crate::contract::parse_project_json(&serde_json::to_vec(&source).unwrap()) + .expect("write disclosure project parses"); + let registry = crate::compiler::compile_project( + &project, + &[], + crate::compiler::CompileProfile::Authoring, + ) + .expect("write disclosure project compiles"); + let entity = ®istry.entities()["entry"]; + let mut base = CurrentRow { + record_uuid: RETAINED, + record_id: RETAINED.to_string(), + record_revision: 1, + predecessor_revision: None, + record_lifecycle: "active".to_owned(), + before_data: None, + data: Map::from_iter([ + ("mark".to_owned(), json!("marked")), + ("note".to_owned(), json!("retained")), + ("flag".to_owned(), json!(false)), + ]), + }; + let permits = |profile, base: &CurrentRow, field, value: Value| { + permits_patch_value( + entity, + &crate::disclosure::plan(entity, profile), + &[], + base, + field, + &value, + ) + }; + assert!(permits("clerk", &base, "flag", json!(true))); + for (field, value) in [ + ("note", json!("retained")), + ("note", Value::Null), + ("mark", json!("open")), + ] { + assert!(permits("officer", &base, field, value.clone())); + assert!(!permits("clerk", &base, field, value)); + } + base.data.insert("mark".to_owned(), json!("open")); + assert!(permits("officer", &base, "mark", json!("closed"))); + assert!(!permits("clerk", &base, "mark", json!("closed"))); + base.data.insert("mark".to_owned(), json!(false)); + assert!(!permits("clerk", &base, "flag", json!(true))); + } + + #[test] + fn required_encrypted_scalars_have_typed_plaintext_witnesses() { + let mut ceiling = ceiling(&["value"]); + let stored = registry_platform_crypto::field_encryption::envelope_member_json(&[1; 40]); + let base = Map::from_iter([("value".to_owned(), stored)]); + for (field_type, expected) in [ + (FieldTypeSource::Date, "2000-01-01"), + ( + FieldTypeSource::Decimal { + precision: 4, + scale: 2, + minimum: Some("1.25".to_owned()), + maximum: Some("3.00".to_owned()), + }, + "1.25", + ), + ( + FieldTypeSource::Decimal { + precision: 3, + scale: 3, + minimum: None, + maximum: Some("-0.125".to_owned()), + }, + "-0.125", + ), + ( + FieldTypeSource::Decimal { + precision: 2, + scale: 2, + minimum: None, + maximum: None, + }, + "0.00", + ), + ] { + ceiling.field_types.insert("value".to_owned(), field_type); + assert!(independent_patch_mutation( + &ceiling, + "value", + &base, + &ActionInputs::new(), + true, + &|_, value| value.as_str() == Some(expected), + )); + } + } + + #[test] + fn a_stored_envelope_cannot_supply_a_structured_literal() { + let mut ceiling = ceiling(&["value"]); + ceiling.field_types.insert( + "value".to_owned(), + FieldTypeSource::Structured { + max_bytes: 1024, + schema: json!({"type":"object", "additionalProperties":true}), + }, + ); + let stored = registry_platform_crypto::field_encryption::envelope_member_json(&[1; 40]); + let base = Map::from_iter([("value".to_owned(), stored)]); + let inputs = ActionInputs::new(); + + assert!(!independent_patch_mutation( + &ceiling, + "value", + &base, + &inputs, + true, + &|_, _| true, + )); + } +} diff --git a/crates/registry-breg/src/mutation/membership.rs b/crates/registry-breg/src/mutation/membership.rs new file mode 100644 index 0000000000..31f6926fd3 --- /dev/null +++ b/crates/registry-breg/src/mutation/membership.rs @@ -0,0 +1,356 @@ +// SPDX-License-Identifier: Apache-2.0 + +use super::*; +use crate::membership::lock_function_name; +use crate::model::CompiledMembershipBoundary; + +pub(super) type LockKey = (String, Uuid); + +#[derive(Default)] +pub(super) struct MembershipLocks(BTreeMap); + +impl MembershipLocks { + pub(super) fn collect( + keys: &mut BTreeSet, + profile: &str, + boundary: &CompiledMembershipBoundary, + key: Option, + ) { + if let Some(key) = key { + keys.insert(( + lock_function_name(profile, &boundary.membership_entity), + key, + )); + } + } + + pub(super) async fn acquire( + transaction: &Transaction<'_>, + keys: BTreeSet, + ) -> Result { + let mut answers = BTreeMap::new(); + for (helper, key) in keys { + let answer = probe(transaction, &helper, key).await?; + answers.insert((helper, key), answer); + } + Ok(Self(answers)) + } + + pub(super) fn allows( + &self, + profile: &str, + boundary: &CompiledMembershipBoundary, + key: Option, + ) -> bool { + key.is_some_and(|key| { + self.0.get(&( + lock_function_name(profile, &boundary.membership_entity), + key, + )) == Some(&true) + }) + } +} + +pub(super) async fn probe( + transaction: &Transaction<'_>, + helper: &str, + key: Uuid, +) -> Result { + transaction + .query_one( + &format!("SELECT registry_context.{}($1)", quote_identifier(helper)), + &[&key], + ) + .await + .map_err(map_database_error)? + .try_get(0) + .map_err(map_database_error) +} + +pub(crate) async fn probe_action_memberships( + transaction: &Transaction<'_>, + profile: &str, + boundaries: &[CompiledMembershipBoundary], + record_id: Option, + snapshot: &Map, +) -> Result<(), MutationError> { + for boundary in boundaries { + if !probe_action_membership( + transaction, + profile, + boundary, + boundary_key(boundary, record_id, snapshot), + ) + .await? + { + return Err(MutationError::MembershipPreconditionFailed); + } + } + Ok(()) +} + +pub(super) async fn probe_action_membership( + transaction: &Transaction<'_>, + profile: &str, + boundary: &CompiledMembershipBoundary, + key: Option, +) -> Result { + let Some(key) = key else { + return Ok(false); + }; + probe( + transaction, + &crate::membership::target_function_name(profile, &boundary.membership_entity), + key, + ) + .await +} + +pub(super) fn json_key(value: Option<&Value>) -> Option { + value + .and_then(Value::as_str) + .and_then(|value| Uuid::parse_str(value).ok()) +} + +/// The membership key one boundary reads from a row. The canonical +/// identifier names the row itself, so its key is the row's own UUID, which +/// a proposed write that has none cannot supply. +pub(super) fn boundary_key( + boundary: &CompiledMembershipBoundary, + record_id: Option, + row: &Map, +) -> Option { + if boundary.field == crate::membership::CANONICAL_ID { + record_id + } else { + json_key(row.get(&boundary.field)) + } +} + +pub(super) fn keys_for_row( + boundaries: &[CompiledMembershipBoundary], + record_id: Option, + row: &Map, +) -> Vec> { + boundaries + .iter() + .map(|boundary| boundary_key(boundary, record_id, row)) + .collect() +} + +pub(super) struct RecordMembership<'a> { + profile: &'a str, + boundaries: &'a [CompiledMembershipBoundary], + observed: BTreeMap>>, + locks: MembershipLocks, +} + +impl<'a> RecordMembership<'a> { + pub(super) async fn prepare( + transaction: &Transaction<'_>, + entity: &'a CompiledEntity, + profile: &'a str, + items: impl IntoIterator, MutationBody)>, + ) -> Result, MutationError> { + let boundaries = crate::membership::boundaries(entity, profile); + if boundaries.is_empty() { + return Ok(None); + } + let mut record_ids = BTreeSet::new(); + let mut keys = BTreeSet::new(); + for (id, body) in items { + if let Some(id) = id { + record_ids.insert(Uuid::parse_str(id).map_err(|_| MutationError::InvalidRequest)?); + } + for boundary in boundaries { + match &body { + MutationBody::Create(data) => MembershipLocks::collect( + &mut keys, + profile, + boundary, + boundary_key(boundary, None, data), + ), + MutationBody::Patch(operations) => { + for operation in operations { + if let PatchOperation::Add { path, value } + | PatchOperation::Replace { path, value } = operation + { + if patch_field(path)? == boundary.field { + MembershipLocks::collect( + &mut keys, + profile, + boundary, + json_key(Some(value)), + ); + } + } + } + } + MutationBody::Tombstone => {} + } + } + } + let mut observed = BTreeMap::new(); + if !record_ids.is_empty() { + let columns = boundaries + .iter() + .map(|boundary| { + if boundary.field == crate::membership::CANONICAL_ID { + "record_id".to_owned() + } else { + quote_identifier(&entity.fields[&boundary.field].physical_name) + } + }) + .collect::>() + .join(", "); + let table = quote_identifier(&entity.physical_table); + let ids = record_ids.into_iter().collect::>(); + let rows = transaction + .query( + &format!( + "SELECT record_id, {columns} FROM registry_data.{table} + WHERE record_id = ANY($1::uuid[]) AND record_lifecycle = 'active'" + ), + &[&ids], + ) + .await + .map_err(map_database_error)?; + for row in rows { + let current = boundaries + .iter() + .enumerate() + .map(|(index, boundary)| { + let key = row.try_get(index + 1).map_err(map_database_error)?; + MembershipLocks::collect(&mut keys, profile, boundary, key); + Ok(key) + }) + .collect::, MutationError>>()?; + observed.insert(row.try_get(0).map_err(map_database_error)?, current); + } + } + Ok(Some(Self { + profile, + boundaries, + observed, + locks: MembershipLocks::acquire(transaction, keys).await?, + })) + } + + pub(super) fn authorize_existing(&self, id: Option<&str>) -> Result<(), MutationError> { + let id = Uuid::parse_str(id.ok_or(MutationError::InvalidRequest)?) + .map_err(|_| MutationError::InvalidRequest)?; + let keys = self + .observed + .get(&id) + .ok_or(MutationError::PreconditionFailed)?; + if self.allows(keys) { + Ok(()) + } else { + Err(MutationError::MembershipPreconditionFailed) + } + } + + pub(super) fn verify_locked(&self, current: &CurrentRow) -> Result<(), MutationError> { + let keys = keys_for_row(self.boundaries, Some(current.record_uuid), ¤t.data); + if self.observed.get(¤t.record_uuid) != Some(&keys) { + return Err(MutationError::MembershipKeyDrift); + } + if !self.allows(&keys) { + return Err(MutationError::MembershipPreconditionFailed); + } + Ok(()) + } + + pub(super) fn record_batch_write(&mut self, current: &CurrentRow) { + if let Some(keys) = self.observed.get_mut(¤t.record_uuid) { + *keys = keys_for_row(self.boundaries, Some(current.record_uuid), ¤t.data); + } + } + + pub(super) fn authorize_proposed( + &self, + data: &Map, + ) -> Result<(), MutationError> { + if self.allows(&keys_for_row(self.boundaries, None, data)) { + Ok(()) + } else { + Err(MutationError::MembershipWriteOutsideBoundary) + } + } + + fn allows(&self, keys: &[Option]) -> bool { + self.boundaries + .iter() + .zip(keys) + .all(|(boundary, key)| self.locks.allows(self.profile, boundary, *key)) + } +} + +/// The records a stored Record or Batch response names, by `recordId`. +pub(super) fn replayed_record_ids(body: &[u8]) -> Result, MutationError> { + let value: Value = serde_json::from_slice(body).map_err(|_| MutationError::Unavailable)?; + let ids = match value.get("results").and_then(Value::as_array) { + Some(results) => results + .iter() + .map(|result| result.get("recordId")) + .collect(), + None => vec![value.get("data").and_then(|data| data.get("recordId"))], + }; + ids.into_iter() + .map(|id| json_key(id).ok_or(MutationError::Unavailable)) + .collect() +} + +/// A replay returns a stored write only while the caller still holds the +/// membership each written row needs now. A removed member who resends a +/// key gets the refusal a fresh request would. +/// +/// The key comes from the record's latest revision, not the live row: a +/// tombstoned row, or one a create-only profile cannot read back, still has +/// its key there. A revision whose snapshot was erased cannot be rechecked, +/// so its replay is refused. +pub(super) async fn recheck_replayed_membership( + transaction: &Transaction<'_>, + entity: &CompiledEntity, + profile: &str, + record_ids: &[Uuid], +) -> Result<(), MutationError> { + let boundaries = crate::membership::boundaries(entity, profile); + if boundaries.is_empty() { + return Ok(()); + } + for record_id in record_ids { + let snapshot: Option = transaction + .query_opt( + "SELECT convert_from(snapshot, 'UTF8') + FROM registry_internal.registry_revisions + WHERE entity_id = $1::text AND record_id = $2::uuid + ORDER BY record_revision DESC + LIMIT 1", + &[&entity.id, record_id], + ) + .await + .map_err(map_database_error)? + .map(|row| row.try_get(0)) + .transpose() + .map_err(map_database_error)? + .flatten(); + let snapshot: Map = snapshot + .as_deref() + .and_then(|text| serde_json::from_str(text).ok()) + .ok_or(MutationError::MembershipPreconditionFailed)?; + for (index, key) in keys_for_row(boundaries, Some(*record_id), &snapshot) + .into_iter() + .enumerate() + { + let Some(key) = key else { + return Err(MutationError::MembershipPreconditionFailed); + }; + let helper = crate::membership::function_name(&entity.id, profile, index); + if !probe(transaction, &helper, key).await? { + return Err(MutationError::MembershipPreconditionFailed); + } + } + } + Ok(()) +} diff --git a/crates/registry-breg/src/mutation/proposal.rs b/crates/registry-breg/src/mutation/proposal.rs index 3dfb4a13cd..87737f6e35 100644 --- a/crates/registry-breg/src/mutation/proposal.rs +++ b/crates/registry-breg/src/mutation/proposal.rs @@ -4,8 +4,10 @@ use super::*; mod additions; mod asks; +mod forms; pub(crate) use asks::ProposalReadDisclosure; mod context_projection; +mod messages; use crate::api::proposals::ProposalMutationInput; use crate::lifecycle::{ proposal_status_and_turn, ProposalApplicationProgress, ProposalAvailability, @@ -13,12 +15,13 @@ use crate::lifecycle::{ ProposalReviewProgress, ProposalStatus, ProposalTurn, ProposalTurnContext, }; use crate::model::{ - CompiledActionExecution, CompiledProposalReview, ProposalOperation, ProposalOwnership, + CompiledActionExecution, CompiledProposalReview, ProposalOperation, ProposalParty, }; use crate::postgres::{ begin_proposal_transaction, ActionClaimContext, ProposalAuthority, ProposalAuthorityOperation, ProposalTargetPhase, }; +use crate::proposal_messages::Side; use crate::proposal_prepare::{self, ProposalTargetSnapshot}; use crate::proposal_store::{self, ProposalDocument}; use crate::proposal_workflow::{ @@ -26,6 +29,8 @@ use crate::proposal_workflow::{ ProposalDigest, ProposalState, RecordId, RecordRevision, TrustedActorRef, TrustedTimestamp, TrustedTransitionContext, }; +use messages::hold_proposal_response; +pub(crate) use messages::thread_of; // Both branches are short-lived admission results with bounded protocol data. #[allow(clippy::large_enum_variant)] @@ -92,6 +97,46 @@ fn check_current_proposal_grant(authority: &ProposalAuthority) -> Result<(), Mut Ok(()) } +async fn require_proposal_target_snapshot( + tx: &Transaction<'_>, + authority: &ProposalAuthority, + entity: &CompiledEntity, + id: Uuid, + snapshot: &Map, +) -> Result<(), MutationError> { + if !authority + .authorizes_snapshot(entity, id, snapshot) + .map_err(|_| MutationError::PreconditionFailed)? + { + return Err(MutationError::PreconditionFailed); + } + super::membership::probe_action_memberships( + tx, + authority.common.access_profile(), + authority.target_membership(&entity.id), + Some(id), + snapshot, + ) + .await +} + +fn proposal_mutation_target_error( + operation: ProposalAuthorityOperation, + error: MutationError, +) -> MutationError { + match (operation, error) { + ( + ProposalAuthorityOperation::Lifecycle( + ProposalOperation::Answer | ProposalOperation::Add, + ), + MutationError::PreconditionFailed, + ) => MutationError::AuthorizationRefused( + registry_platform_authcommon::FailedCheck::Visibility, + ), + (_, error) => error, + } +} + /// The answer to a target context the database refused to install. A context /// `install_target` rejects means the caller may not read that target. A /// store failure means nobody knows yet, so it answers 503 instead of being @@ -103,6 +148,25 @@ fn target_install_error(error: crate::postgres::PostgresKernelError) -> Mutation } } +struct ProposalMembershipLocks { + document_revision: i64, + observed: BTreeMap<(String, Uuid), Vec>>, + candidate_refusal: Option, + proofs: BTreeSet, + sources: BTreeSet, +} + +impl ProposalMembershipLocks { + async fn recheck(&self, tx: &Transaction<'_>) -> Result<(), MutationError> { + for (helper, key) in &self.proofs { + if !super::membership::probe(tx, helper, *key).await? { + return Err(MutationError::MembershipPreconditionFailed); + } + } + Ok(()) + } +} + fn validate_attachment_authority( action: &CompiledAction, authority: &ProposalAuthority, @@ -122,6 +186,7 @@ fn validate_attachment_authority( .iter() .find(|grant| { grant.profile_id == authority.common.access_profile() + && grant.party == authority.party && grant.operations.contains(&operation) }) .ok_or(MutationError::PreconditionFailed)?; @@ -215,10 +280,8 @@ fn validate_input_write_authority( let CompiledActionExecution::Proposal { proposal } = &action.execution else { return Err(MutationError::InvalidRequest); }; - let Some(writable) = proposal - .permissions - .iter() - .find(|grant| grant.profile_id == authority.common.access_profile()) + let Some(writable) = authority + .permission(proposal) .and_then(|grant| grant.writable_inputs.as_ref()) else { return Ok(()); @@ -231,6 +294,36 @@ fn validate_input_write_authority( } } +/// Once a subject is bound, Edit, Revise and Rebase restate its input exactly: +/// answers, files and messages on the Proposal belong to one person. To name +/// someone else, cancel and file again. +fn validate_bound_subject_input( + action: &CompiledAction, + document: &ProposalDocument, + values: &Map, +) -> Result<(), MutationError> { + let CompiledActionExecution::Proposal { proposal } = &action.execution else { + return Err(MutationError::InvalidRequest); + }; + let (Some(subject), Some(_)) = (&proposal.subject, &document.header.subject_reference) else { + return Ok(()); + }; + let Some(declared) = action.inputs.iter().find(|input| input.id == subject.input) else { + return Err(MutationError::InvalidRequest); + }; + if values.get(&declared.id) + != document + .input + .as_ref() + .and_then(|prior| prior.get(&declared.id)) + { + return Err(MutationError::InvalidRequestAt( + crate::problem_location::RequestLocation::action_input(&declared.api_name), + )); + } + Ok(()) +} + /// The API name of the first declared input outside `writable` whose value /// differs from `base`. Presence is part of the handler input ABI, so an /// explicit null differs from an absent optional input. @@ -274,6 +367,7 @@ pub(crate) fn proposal_operation_name(operation: ProposalAuthorityOperation) -> ProposalAuthorityOperation::Lifecycle(ProposalOperation::GetApplicationActor) => { "get-application-actor" } + ProposalAuthorityOperation::Lifecycle(ProposalOperation::Message) => "message", } } @@ -389,6 +483,7 @@ impl MutationTransaction { from_state: "submitted", state: workflow.state().as_storage(), transition, + message_from: None, effect_digest: workflow .current_proposal() .map(|proposal| proposal.effect_digest().as_str()), @@ -471,7 +566,8 @@ impl MutationTransaction { let document = proposal_store::load_document(tx, id, proposal_store::DocumentLock::Update).await?; self.authorize_proposal_document(tx, registry, &document, input.authority) - .await?; + .await + .map_err(|error| proposal_mutation_target_error(input.operation, error))?; let (binding, _) = self .proposal_document_binding(tx, registry, input, Some(&document)) .await?; @@ -620,6 +716,18 @@ impl MutationTransaction { }, )?; let entry = disclosure.annotate(entry, correlation); + let entry = match authority.party { + Some(party) => { + let mut record = entry.record().clone(); + record["partyRole"] = json!(party); + registry_platform_audit::AuditEntry::response( + crate::audit::AUDIT_SCHEMA, + correlation.request_id().to_string(), + record, + ) + } + None => entry, + }; self.audit .append(entry) .await @@ -706,6 +814,12 @@ impl MutationTransaction { answer.ask_id ); } + if input.message.is_some() { + route = format!( + "/v1/proposals/{}/messages", + input.proposal_id.ok_or(MutationError::InvalidRequest)? + ); + } let method = if let Some(attachment) = &input.attachment { route = format!( "/v1/proposals/{}/{}/{}", @@ -731,8 +845,7 @@ impl MutationTransaction { let CompiledActionExecution::Proposal { proposal: policy } = &action.execution else { return Err(MutationError::InvalidRequest); }; - let response_contract=policy.permissions.iter().find(|permission| - permission.profile_id==input.authority.common.access_profile()) + let response_contract=input.authority.permission(policy) .map(|permission|{ let mut contract=json!({"operations":permission.operations, "readableAttachments":permission.readable_attachments,"writableAttachments":permission.writable_attachments}); @@ -745,6 +858,23 @@ impl MutationTransaction { if !permission.readable_inputs.is_empty() { contract["readableInputs"]=json!(permission.readable_inputs); } + if input.message.is_some() && permission.operations.contains(&ProposalOperation::GetReviewContext) + && !permission.operations.contains(&ProposalOperation::Get) + { + contract["readableContextFields"] = json!(permission.readable_context_fields); + } + for (key, forms) in [ + ("readableForms", &permission.readable_forms), + ("writableForms", &permission.writable_forms), + ] { + if !forms.is_empty() { + contract[key] = json!(forms.iter().filter_map(|id| { + policy.additional_forms.get(id).map(|form| { + (id, crate::artifacts::additional_form_contract(&action.id, id, &form.inputs)) + }) + }).collect::>()); + } + } contract }); let mut canonical_request = json!({ @@ -756,9 +886,20 @@ impl MutationTransaction { "contentType":attachment.content_type,"sha256":attachment.sha256(), "byteSize":attachment.bytes.as_ref().map(Vec::len)})), }); + if let Some(form) = &input.form { + route = format!( + "/v1/proposals/{}/additional-forms/{}", + input.proposal_id.ok_or(MutationError::InvalidRequest)?, + form.id + ); + canonical_request["form"] = json!({"id":form.id,"input":form.values}); + } if let Some(answer) = &input.answer { canonical_request["answer"] = json!(answer); } + if let Some(message) = &input.message { + canonical_request["message"] = json!(message); + } let digest = Sha256::digest( canonicalize_json(&canonical_request).map_err(|_| MutationError::InvalidRequest)?, ) @@ -818,6 +959,62 @@ impl MutationTransaction { ) } + /// The internal reference a bound subject is stored and matched under. + /// + /// Never project this value in a response, event, export or log. Like + /// the owner reference it is an unkeyed hash, and person identifiers are + /// often a small enough space to enumerate. No issuer takes part: the + /// stored value comes from the register, not from a token. + pub(crate) fn proposal_subject_reference(&self, value: &str) -> String { + crate::idempotency::sha256_reference( + "breg-proposal-subject-reference-v1", + &[&self.expected.database_id, value], + ) + } + + /// The keyed, database-scoped pseudonym audit records for a bound subject. + pub(crate) fn proposal_subject_pseudonym(&self, value: &str) -> Result { + self.audit + .profile() + .key_hasher() + .audit_reference_hash( + "breg-proposal-subject-v1", + &self.expected.database_id, + value, + ) + .map_err(|_| MutationError::Unavailable) + } + + /// Whether `principal` is the subject bound as `subject_reference`. Only + /// a person acting for themselves is ever matched: `person` carries the + /// admission's human test. + pub(crate) fn proposal_subject_matches( + &self, + subject_reference: Option<&str>, + principal: &str, + person: bool, + ) -> bool { + person + && subject_reference + .is_some_and(|stored| stored == self.proposal_subject_reference(principal)) + } + + /// The entry of the caller's profile that governs them on `document`. + pub(crate) fn party_selection( + &self, + document: &ProposalDocument, + authority: &ProposalAuthority, + ) -> crate::api::proposals::PartySelection { + crate::api::proposals::PartySelection::Proposal { + owner: document.header.owner_reference == self.proposal_owner_of(&authority.common), + subject: self.proposal_subject_matches( + document.header.subject_reference.as_deref(), + authority.common.principal(), + authority.person, + ), + } + } + /// The owner reference of the caller `authority` names. pub(crate) fn proposal_owner_of(&self, authority: &ActionClaimContext) -> String { self.proposal_owner_reference( @@ -927,18 +1124,37 @@ impl MutationTransaction { authority: &ProposalAuthority, lock_targets: bool, ) -> Result<(), MutationError> { - let action = proposal_action(registry, &document.action_id)?; if let Some(check) = proposal_document_refusal( &document.action_id, authority.common.action_id(), authority.proposal_scope.as_ref(), document.proposal_id, - authority.ownership, + authority.party, &document.header.owner_reference, || self.proposal_owner_of(&authority.common), + || { + self.proposal_subject_matches( + document.header.subject_reference.as_deref(), + authority.common.principal(), + authority.person, + ) + }, ) { return Err(MutationError::AuthorizationRefused(check)); } + self.check_proposal_targets(tx, registry, document, authority, lock_targets) + .await + } + + async fn check_proposal_targets( + &self, + tx: &Transaction<'_>, + registry: &CompiledRegistry, + document: &ProposalDocument, + authority: &ProposalAuthority, + lock_targets: bool, + ) -> Result<(), MutationError> { + let action = proposal_action(registry, &document.action_id)?; for (entity_id, id) in &document.input_targets { let entity = registry .entities() @@ -1017,12 +1233,7 @@ impl MutationTransaction { ) ); let row = load_proposal_row(tx, entity, *id, lock).await?; - if !authority - .authorizes_snapshot(entity, *id, &row.data) - .map_err(|_| MutationError::PreconditionFailed)? - { - return Err(MutationError::PreconditionFailed); - } + require_proposal_target_snapshot(tx, authority, entity, *id, &row.data).await?; } if document.header.state == "submitted" && !document.header.current_proposal_erased { let workflow = @@ -1061,12 +1272,14 @@ impl MutationTransaction { .entities() .get(&target.entity_id) .ok_or(MutationError::PreconditionFailed)?; - if !authority - .authorizes_snapshot(entity, target.record_id, &target.after) - .map_err(|_| MutationError::PreconditionFailed)? - { - return Err(MutationError::PreconditionFailed); - } + require_proposal_target_snapshot( + tx, + authority, + entity, + target.record_id, + &target.after, + ) + .await?; } } if document.header.state == "applied" { @@ -1104,12 +1317,7 @@ impl MutationTransaction { .await .map_err(target_install_error)?; let current = load_proposal_row(tx, entity, id, false).await?; - if !authority - .authorizes_snapshot(entity, id, ¤t.data) - .map_err(|_| MutationError::PreconditionFailed)? - { - return Err(MutationError::PreconditionFailed); - } + require_proposal_target_snapshot(tx, authority, entity, id, ¤t.data).await?; } } Ok(()) @@ -1134,17 +1342,29 @@ impl MutationTransaction { .await .map_err(|_| MutationError::Unavailable)?; let tx = guarded.transaction(); - let document = - proposal_store::load_document(tx, id, proposal_store::DocumentLock::None).await?; - self.authorize_proposal_document(tx, registry, &document, input.authority) - .await?; + // Message receipt checks and erasure serialize on the Proposal state + // row. Take that lock before looking up a possible Apply receipt. + let lock = if thread_of(action).is_some() { + proposal_store::DocumentLock::Share + } else { + proposal_store::DocumentLock::None + }; + let document = proposal_store::load_document(tx, id, lock).await?; + self.check_proposal_document( + tx, + registry, + &document, + input.authority, + !input.authority.locks_membership(), + ) + .await?; let (binding, _) = self .proposal_document_binding(tx, registry, input, Some(&document)) .await?; if let Some(stored) = lock_and_load(tx, &binding).await? { - let StoredResultMetadata::Proposal { .. } = stored.metadata else { - return Err(MutationError::Unavailable); - }; + let disclosure = self + .replay_proposal_disclosure(tx, registry, action, &document, input, &stored) + .await?; let entry = self.proposal_terminal( input, &binding, @@ -1152,7 +1372,9 @@ impl MutationTransaction { TerminalAuditOutcome::Replayed, 0, &[], - replayed_public_reason(stored.response.body())?, + disclosure, + None, + None, )?; check_current_proposal_grant(input.authority)?; guarded @@ -1321,28 +1543,39 @@ impl MutationTransaction { } else { None }; + let membership = if input.authority.locks_membership() { + self.lock_apply_memberships( + tx, + registry, + action, + input.authority, + input.proposal_id.ok_or(MutationError::InvalidRequest)?, + ) + .await? + } else { + None + }; let existing = if let Some(id) = input.proposal_id { let document = proposal_store::load_document(tx, id, proposal_store::DocumentLock::Update).await?; - if let Err(error) = self - .authorize_proposal_document(tx, registry, &document, input.authority) - .await + if membership + .as_ref() + .is_some_and(|locks| locks.document_revision != document.header.workflow_revision) + || (input.authority.locks_membership() + && document.header.state == "submitted" + && membership.is_none()) { - if matches!( - (&error, input.operation), - ( - MutationError::PreconditionFailed, - ProposalAuthorityOperation::Lifecycle( - ProposalOperation::Answer | ProposalOperation::Add - ) - ) - ) { - return Err(MutationError::AuthorizationRefused( - registry_platform_authcommon::FailedCheck::Visibility, - )); - } - return Err(error); + return Err(MutationError::PreconditionFailed); } + self.check_proposal_document( + tx, + registry, + &document, + input.authority, + !input.authority.locks_membership(), + ) + .await + .map_err(|error| proposal_mutation_target_error(input.operation, error))?; Some(document) } else { None @@ -1351,9 +1584,6 @@ impl MutationTransaction { .proposal_document_binding(tx, registry, &input, existing.as_ref()) .await?; if let Some(stored) = lock_and_load(tx, &binding).await? { - let StoredResultMetadata::Proposal { .. } = stored.metadata else { - return Err(MutationError::Unavailable); - }; let document = if let Some(document) = existing { document } else { @@ -1371,6 +1601,9 @@ impl MutationTransaction { .await?; document }; + let disclosure = self + .replay_proposal_disclosure(tx, registry, action, &document, &input, &stored) + .await?; let entry = self.proposal_terminal( &input, &binding, @@ -1378,7 +1611,9 @@ impl MutationTransaction { TerminalAuditOutcome::Replayed, 0, &[], - replayed_public_reason(stored.response.body())?, + disclosure, + None, + None, )?; check_current_proposal_grant(input.authority)?; guarded @@ -1398,7 +1633,10 @@ impl MutationTransaction { let actor = self.proposal_actor_of(&input.authority.common)?; let mut result_count = 0u16; let mut changed_inputs = Vec::new(); + let mut added_form_entry = None; let mut terminal_error = None; + let mut bound_subject = None; + let mut message_id = None; let (id, from_state, transition) = match input.operation { ProposalAuthorityOperation::Start => { if existing.is_some() { @@ -1439,8 +1677,15 @@ impl MutationTransaction { ProposalAuthorityOperation::Lifecycle(operation) => { let document = existing.as_ref().ok_or(MutationError::InvalidRequest)?; let id = document.proposal_id; - if input.expected_etag - != Some(self.proposal_etag(document, input.authority)?.as_str()) + // Only the automatic worker's Apply goes without an ETag: its + // claimed lease is verified under lock before any effect. + let leased_apply = input.expected_etag.is_none() + && input.executor_lease.is_some() + && input.authority.is_system() + && operation == ProposalOperation::Apply; + if !leased_apply + && input.expected_etag + != Some(self.proposal_etag(document, input.authority)?.as_str()) { return Err(MutationError::PreconditionFailed); } @@ -1464,9 +1709,13 @@ impl MutationTransaction { { return Err(MutationError::PreconditionFailed); } + // A message does not depend on the Action revision, so a + // package block leaves the thread open. if !matches!( operation, - ProposalOperation::Cancel | ProposalOperation::Rebase + ProposalOperation::Cancel + | ProposalOperation::Rebase + | ProposalOperation::Message ) { let compatible = if matches!( operation, @@ -1526,6 +1775,44 @@ impl MutationTransaction { proposal_store::save(tx, &action.id, id, previous, &workflow).await?; (workflow, "answered") } + ProposalOperation::Add if input.form.is_some() => { + ensure_additions_open(tx, document, &workflow).await?; + let form = input.form.as_ref().ok_or(MutationError::InvalidRequest)?; + added_form_entry = Some( + forms::insert(tx, action, document, input.authority, form, &actor) + .await?, + ); + let workflow = workflow + .record_addition(context) + .map_err(workflow_error)? + .into_workflow(); + proposal_store::save(tx, &action.id, id, previous, &workflow).await?; + (workflow, "added") + } + ProposalOperation::Message => { + let message = input + .message + .as_deref() + .ok_or(MutationError::InvalidRequest)?; + message_id = Some( + self.commit_message( + tx, + action, + document, + &workflow, + input.authority, + &actor, + message, + ) + .await?, + ); + let workflow = workflow + .record_message(context) + .map_err(workflow_error)? + .into_workflow(); + proposal_store::save(tx, &action.id, id, previous, &workflow).await?; + (workflow, "messaged") + } ProposalOperation::Add => { ensure_additions_open(tx, document, &workflow).await?; check_addition_count(tx, action, document).await?; @@ -1657,7 +1944,7 @@ impl MutationTransaction { let resolved = proposal_prepare::resolve_targets( registry, action, &values, effects, &creates, )?; - let (bases, guards) = self + let (bases, guards, subject_field) = self .load_submission_bases( tx, registry, @@ -1669,6 +1956,16 @@ impl MutationTransaction { trusted_now, ) .await?; + bound_subject = self + .bind_proposal_subject( + tx, + action, + document, + input.authority, + &values, + subject_field, + ) + .await?; // The exact-command replay lookup ran before plan evaluation. // Reserve only for this fresh Submit, then include every // generated value in the frozen effects and digest. Apply @@ -1677,6 +1974,16 @@ impl MutationTransaction { let mut create_fields = proposal_prepare::materialize_create_fields( registry, &values, &resolved, )?; + proposal_prepare::authorize_candidates_before_allocation( + tx, + registry, + input.authority, + &values, + &resolved, + &create_fields, + &bases, + ) + .await?; for effect in resolved .effects .iter() @@ -1836,6 +2143,7 @@ impl MutationTransaction { &values, document.input.as_ref(), )?; + validate_bound_subject_input(action, document, &values)?; changed_inputs = action .inputs .iter() @@ -2079,6 +2387,8 @@ impl MutationTransaction { document, input.authority, frozen, + membership.as_ref(), + &targets, ) .await?; self.verify_frozen_guards( @@ -2090,6 +2400,12 @@ impl MutationTransaction { frozen, ) .await?; + if let Some(error) = membership + .as_ref() + .and_then(|locks| locks.candidate_refusal.as_ref()) + { + return Err(error.clone()); + } self.apply_frozen_proposal( tx, registry, @@ -2100,6 +2416,7 @@ impl MutationTransaction { &binding, application_id, timer_staging.as_ref(), + membership.as_ref(), ) .await } @@ -2198,6 +2515,8 @@ impl MutationTransaction { 0, &[], ProposalReadDisclosure::default(), + None, + None, )?; if tokio::time::Instant::now() >= deadline { return Err(MutationError::Unavailable); @@ -2237,6 +2556,8 @@ impl MutationTransaction { from_state: &from_state, state: workflow.state().as_storage(), transition, + message_from: message_id + .map(|_| crate::proposal_messages::Side::of(input.authority.party).as_str()), effect_digest: workflow .current_proposal() .map(|proposal| proposal.effect_digest().as_str()), @@ -2254,9 +2575,31 @@ impl MutationTransaction { }, ) .await?; - let value = self - .proposal_public_value(tx, registry, &document, input.claims, input.authority) - .await?; + let review_receipt = if input.message.is_some() { + self.message_review_receipt(tx, registry, action, &document, &input) + .await? + } else { + None + }; + let (mut value, thread_side) = match review_receipt { + Some(review) => (review, Some(Side::of(input.authority.party))), + None => { + self.proposal_public_projection( + tx, + registry, + &document, + input.claims, + input.authority, + ) + .await? + } + }; + if input.message.is_some() && thread_side.is_none() { + return Err(MutationError::Unavailable); + } + if let Some((entry, _)) = &added_form_entry { + value["formEntryId"] = json!(entry); + } let mut headers = BTreeMap::from([ ( PermittedResponseHeader::ContentType, @@ -2273,14 +2616,15 @@ impl MutationTransaction { format!("/v1/proposals/{id}").into_bytes(), ); } - let held = HeldResponse::from_json( + let (held, disclosure) = hold_proposal_response( if input.operation == ProposalAuthorityOperation::Start { 201 } else { 200 }, - &value, + value, headers, + thread_side, )?; insert_result( tx, @@ -2290,6 +2634,7 @@ impl MutationTransaction { record_revision: document.header.workflow_revision, submission_version: document.header.submission_version, result_count, + thread_side, }, &held, ) @@ -2310,8 +2655,25 @@ impl MutationTransaction { TerminalAuditOutcome::Committed, result_count, &changed_inputs, - ProposalReadDisclosure::for_value(&value), + disclosure, + bound_subject.as_deref(), + added_form_entry, )?; + // A write records which message and which side, never its text. + let entry = match message_id { + Some(message_id) => { + let mut record = entry.record().clone(); + record["messageId"] = json!(message_id); + record["messageFrom"] = + json!(crate::proposal_messages::Side::of(input.authority.party).as_str()); + AuditEntry::response( + crate::audit::AUDIT_SCHEMA, + input.correlation.request_id().to_string(), + record, + ) + } + None => entry, + }; if tokio::time::Instant::now() >= deadline { return Err(MutationError::Unavailable); } @@ -2395,6 +2757,8 @@ impl MutationTransaction { count: u16, changed_inputs: &[String], disclosure: ProposalReadDisclosure, + bound_subject: Option<&str>, + added_form_entry: Option<(Uuid, Vec)>, ) -> Result { let terminal = TerminalAudit { context: input.authority.common.audit_context().cloned(), @@ -2440,6 +2804,11 @@ impl MutationTransaction { { record["changedInputs"] = json!(changed_inputs); } + if let (Some((entry, ids)), Some(form)) = (added_form_entry, &input.form) { + record["additionalFormId"] = json!(form.id); + record["formEntryId"] = json!(entry); + record["formInputIds"] = json!(ids); + } if let Some(answer) = &input.answer { record["reviewAskId"] = json!(answer.ask_id); record["citedAdditionIds"] = json!(answer.body.additions); @@ -2452,6 +2821,12 @@ impl MutationTransaction { if let Some(revision) = input.authority.system_grant_revision() { record["systemApplyGrantRevision"] = json!(revision); } + if let Some(party) = input.authority.party { + record["partyRole"] = json!(party); + } + if let Some(pseudonym) = bound_subject { + record["subjectPseudonym"] = json!(pseudonym); + } Ok(disclosure.annotate( registry_platform_audit::AuditEntry::response( crate::audit::AUDIT_SCHEMA, @@ -2502,14 +2877,8 @@ impl MutationTransaction { .await .map_err(|_| MutationError::PreconditionFailed)?; let row = load_proposal_row(tx, entity, *id, true).await?; - if !authority - .authorizes_snapshot(entity, *id, &row.data) - .map_err(|_| MutationError::PreconditionFailed)? - { - return Err(MutationError::PreconditionFailed); - } + require_proposal_target_snapshot(tx, authority, entity, *id, &row.data).await?; } - let _ = action; Ok(()) } @@ -2527,8 +2896,9 @@ impl MutationTransaction { trusted_now: time::OffsetDateTime, ) -> Result< ( - BTreeMap<(String, Uuid), (i64, Map)>, + proposal_prepare::ProposalPatchBases, BTreeMap)>, + Option, ), MutationError, > { @@ -2573,12 +2943,7 @@ impl MutationTransaction { .await .map_err(|_| MutationError::PreconditionFailed)?; let row = load_proposal_row(tx, entity, id, true).await?; - if !authority - .authorizes_snapshot(entity, id, &row.data) - .map_err(|_| MutationError::PreconditionFailed)? - { - return Err(MutationError::PreconditionFailed); - } + require_proposal_target_snapshot(tx, authority, entity, id, &row.data).await?; rows.insert((entity_id, id), (row.record_revision, row.data)); } for ((entity, id), operation) in &resolved.records { @@ -2629,51 +2994,227 @@ impl MutationTransaction { .clone(); guards.insert(input_id.clone(), (id, revision, row)); } - Ok((bases, guards)) + // The `field` form of a subject reads the referenced Record's field + // under the same Preparation read a commit guard uses. The value is + // compared and hashed, never returned to the submitter. + let subject_field = match &action.execution { + CompiledActionExecution::Proposal { proposal } => match &proposal.subject { + Some(crate::contract::ProposalSubjectSource { + input: input_id, + field: Some(field), + }) => { + let entity = reference_input_entity(action, input_id)?; + let id = input + .get(input_id) + .and_then(Value::as_str) + .and_then(|id| Uuid::parse_str(id).ok()) + .ok_or(MutationError::InvalidRequest)?; + let (_, row) = rows + .get(&(entity.to_owned(), id)) + .ok_or(MutationError::PreconditionFailed)?; + Some(row.get(field).cloned().unwrap_or(Value::Null)) + } + _ => None, + }, + CompiledActionExecution::Immediate => None, + }; + Ok((bases, guards, subject_field)) } - async fn lock_frozen_scope( + /// Bind the Proposal's subject at Submit, or confirm the bound one. The + /// subject is the declared input's value, or the field the reference + /// input's Record holds. A Submit that names someone other than the + /// submitter needs `submitsFor: anyone`. Returns the subject pseudonym + /// audit records when this Submit bound it. + async fn bind_proposal_subject( &self, tx: &Transaction<'_>, - registry: &CompiledRegistry, action: &CompiledAction, document: &ProposalDocument, authority: &ProposalAuthority, - frozen: &crate::proposal_workflow::ProposalSnapshot, - ) -> Result<(), MutationError> { - let mut targets = BTreeMap::new(); - for target in frozen.input_targets() { - let id = Uuid::parse_str(target.record_id.as_str()) - .map_err(|_| MutationError::PreconditionFailed)?; - targets.insert((target.record_type.clone(), id), None); + values: &Map, + subject_field: Option, + ) -> Result, MutationError> { + let CompiledActionExecution::Proposal { proposal } = &action.execution else { + return Err(MutationError::InvalidRequest); + }; + let Some(subject) = &proposal.subject else { + return Ok(None); + }; + let declared = action + .inputs + .iter() + .find(|input| input.id == subject.input) + .ok_or(MutationError::InvalidRequest)?; + let at_input = || { + MutationError::InvalidRequestAt(crate::problem_location::RequestLocation::action_input( + &declared.api_name, + )) + }; + let value = match subject_field { + Some(field) => field, + None => values.get(&subject.input).cloned().unwrap_or(Value::Null), + }; + let value = value.as_str().unwrap_or_default(); + // A submitter who files only for themselves learns one thing: whether + // the subject is them. An empty value answers as anyone else does. + if value != authority.common.principal() && !authority.submits_for_anyone { + return Err(MutationError::ProposalSubjectNotCaller); } - for effect in frozen.effects() { - if let Some(id) = effect.target().existing_record_id() { - targets.insert( - ( - effect.target().entity_id().as_str().to_owned(), - Uuid::parse_str(id.as_str()) - .map_err(|_| MutationError::PreconditionFailed)?, - ), - effect - .target() - .base_revision() - .map(|revision| revision.get()), - ); + if value.is_empty() { + return Err(at_input()); + } + let reference = self.proposal_subject_reference(value); + match &document.header.subject_reference { + Some(stored) if *stored == reference => Ok(None), + Some(_) => Err(MutationError::ProposalSubjectChanged), + None => { + proposal_store::bind_subject(tx, &action.id, document.proposal_id, &reference) + .await?; + Ok(Some(self.proposal_subject_pseudonym(value)?)) } } - if let Some(guards) = frozen.application_preconditions() { - for target in &guards.targets { - targets.insert( - ( - target.entity_id.clone(), - Uuid::parse_str(target.record_id.as_str()) - .map_err(|_| MutationError::PreconditionFailed)?, - ), - Some(target.expected_revision), - ); + } + + async fn lock_apply_memberships( + &self, + tx: &Transaction<'_>, + registry: &CompiledRegistry, + action: &CompiledAction, + authority: &ProposalAuthority, + id: Uuid, + ) -> Result, MutationError> { + use super::membership::{keys_for_row, MembershipLocks}; + + let document = + proposal_store::load_document(tx, id, proposal_store::DocumentLock::None).await?; + self.check_proposal_visibility(tx, registry, &document, authority) + .await?; + if document.header.state != "submitted" || document.header.current_proposal_erased { + return Ok(None); + } + let workflow = proposal_store::load(tx, &document.action_id, id, false).await?; + let frozen = workflow + .current_proposal() + .ok_or(MutationError::PreconditionFailed)?; + let targets = proposal_store::load_targets( + tx, + &document.action_id, + id, + document.header.submission_version, + ) + .await?; + proposal_prepare::validate_frozen_targets(frozen, &targets)?; + + let profile = authority.common.access_profile(); + let mut needed = BTreeSet::new(); + let mut observed = BTreeMap::new(); + let mut proofs = BTreeSet::new(); + let mut sources = BTreeSet::new(); + for ((entity_id, record_id), revision) in frozen_scope(frozen)? { + let boundaries = authority.target_membership(&entity_id); + if boundaries.is_empty() { + continue; + } + let entity = ®istry.entities()[&entity_id]; + authority + .install_target( + tx, + registry, + id, + frozen.version().get(), + ProposalTargetPhase::Application, + &entity_id, + record_id, + Operation::Get, + &proposal_read_fields(action, &entity_id), + revision, + Some(frozen.effect_digest().as_str()), + ) + .await + .map_err(target_install_error)?; + let row = load_proposal_row(tx, entity, record_id, false).await?; + let keys = keys_for_row(boundaries, Some(record_id), &row.data); + for (boundary, key) in boundaries.iter().zip(&keys) { + MembershipLocks::collect(&mut needed, profile, boundary, *key); + } + observed.insert((entity_id, record_id), keys); + } + for target in &targets { + let boundaries = authority.target_membership(&target.entity_id); + for (boundary, key) in + boundaries + .iter() + .zip(keys_for_row(boundaries, None, &target.after)) + { + MembershipLocks::collect(&mut needed, profile, boundary, key); } } + // The shared package lock is already held. Take source locks before + // locking the Proposal state or any target row. + let locks = MembershipLocks::acquire(tx, needed).await?; + let mut admit = |entity: &str, keys: &[Option]| { + let boundaries = authority.target_membership(entity); + if !boundaries + .iter() + .zip(keys) + .all(|(boundary, key)| locks.allows(profile, boundary, *key)) + { + return false; + } + for (boundary, key) in boundaries.iter().zip(keys.iter().flatten()) { + proofs.insert(( + crate::membership::target_function_name(profile, &boundary.membership_entity), + *key, + )); + sources.insert(boundary.membership_entity.clone()); + } + true + }; + for ((entity, _), keys) in &observed { + if !admit(entity, keys) { + return Err(MutationError::MembershipPreconditionFailed); + } + } + let mut candidate_refusal = None; + for target in &targets { + if !admit( + &target.entity_id, + &keys_for_row( + authority.target_membership(&target.entity_id), + None, + &target.after, + ), + ) { + if target.operation != Operation::Patch { + candidate_refusal = Some(MutationError::MembershipPreconditionFailed); + } else if candidate_refusal.is_none() { + candidate_refusal = Some(MutationError::MembershipWriteOutsideBoundary); + } + } + } + Ok(Some(ProposalMembershipLocks { + document_revision: document.header.workflow_revision, + observed, + candidate_refusal, + proofs, + sources, + })) + } + + #[allow(clippy::too_many_arguments)] + async fn lock_frozen_scope( + &self, + tx: &Transaction<'_>, + registry: &CompiledRegistry, + action: &CompiledAction, + document: &ProposalDocument, + authority: &ProposalAuthority, + frozen: &crate::proposal_workflow::ProposalSnapshot, + membership: Option<&ProposalMembershipLocks>, + snapshots: &[ProposalTargetSnapshot], + ) -> Result<(), MutationError> { + let targets = frozen_scope(frozen)?; for ((entity_id, id), revision) in targets { let entity = registry .entities() @@ -2696,12 +3237,38 @@ impl MutationTransaction { .await .map_err(|_| MutationError::PreconditionFailed)?; let row = load_proposal_row(tx, entity, id, true).await?; + if let Some(expected) = + membership.and_then(|locks| locks.observed.get(&(entity_id.clone(), id))) + { + if super::membership::keys_for_row( + authority.target_membership(&entity_id), + Some(id), + &row.data, + ) != *expected + { + return Err(MutationError::PreconditionFailed); + } + } if !authority .authorizes_snapshot(entity, id, &row.data) .map_err(|_| MutationError::PreconditionFailed)? { return Err(MutationError::PreconditionFailed); } + // A known candidate refusal prevents all writes. Check the frozen + // Patch bases here because the effect loop will never reach them. + if membership.is_some_and(|locks| locks.candidate_refusal.is_some()) + && snapshots.iter().any(|snapshot| { + snapshot.entity_id == entity_id + && snapshot.record_id == id + && snapshot.expected_revision.is_some_and(|revision| { + revision != row.record_revision + || snapshot.before.as_ref() != Some(&row.data) + }) + }) + { + return Err(MutationError::ProposalTargetChanged); + } } Ok(()) } @@ -2852,6 +3419,7 @@ impl MutationTransaction { binding: &crate::idempotency::ResolvedIdempotencyBinding, application_id: Uuid, timer_staging: Option<&RecordTimerStaging>, + membership: Option<&ProposalMembershipLocks>, ) -> Result<(Vec, Vec), MutationError> { let action = proposal_action(registry, &document.action_id)?; let mut observed = Vec::new(); @@ -3007,6 +3575,9 @@ impl MutationTransaction { PlanWriteOrigin::ProposalApplication, ) .await?; + if let Some(locks) = membership.filter(|locks| locks.sources.contains(&entity.id)) { + locks.recheck(tx).await?; + } let reference = record_reference( self.audit.profile(), &self.expected.activation_id, @@ -3236,10 +3807,8 @@ impl MutationTransaction { let CompiledActionExecution::Proposal { proposal } = &action.execution else { return Err(MutationError::PreconditionFailed); }; - let permission = proposal - .permissions - .iter() - .find(|permission| permission.profile_id == authority.common.access_profile()) + let permission = authority + .permission(proposal) .ok_or(MutationError::PreconditionFailed)?; if authority.operation == ProposalAuthorityOperation::Lifecycle(ProposalOperation::GetTaskGrantContext) @@ -3288,7 +3857,7 @@ impl MutationTransaction { || document.action_id != authority.common.action_id() || document.header.current_proposal_erased || !permission.targets.is_empty() - || permission.ownership.is_some() + || permission.party.is_some() || authority .proposal_scope .as_ref() @@ -3576,6 +4145,8 @@ impl MutationTransaction { if accepted.request_id != request.request_id || accepted.policy != request.policy { return Err(MutationError::PreconditionFailed); } + self.check_proposal_targets(tx, registry, document, authority, false) + .await?; value["policy"] = json!(accepted.policy); } match authority.operation { @@ -3633,6 +4204,20 @@ impl MutationTransaction { ) .await?, ); + if authority.operation + == ProposalAuthorityOperation::Lifecycle(ProposalOperation::GetReviewContext) + && authority.receives_form_values + { + if let CompiledActionExecution::Proposal { proposal } = &action.execution { + if !proposal.additional_forms.is_empty() { + value["context"]["additionalForms"] = json!(proposal + .additional_forms + .keys() + .map(|id| (id, id)) + .collect::>()); + } + } + } // Answers are served to human reviewers of the current // binding only; see `receives_review_answers`. if authority.operation @@ -3651,6 +4236,25 @@ impl MutationTransaction { .intrinsic_asks(tx, registry, document, authority, frozen, &schema) .await?; } + // The thread sits beside the asks: its text for a context + // read that asked for it, its counts for the inbox batch. + if let Some((thread, text)) = &authority.review_messages { + if link_readable( + self.check_proposal_document(tx, registry, document, thread, false) + .await, + )? { + if let Some(mut messages) = self + .proposal_messages_member(tx, action, document, thread, *text) + .await? + { + if !*text { + let side = crate::proposal_messages::Side::of(thread.party); + messages["readerSide"] = json!(side.as_str()); + } + value["context"]["messages"] = messages; + } + } + } } _ => return Err(MutationError::PreconditionFailed), } @@ -3665,6 +4269,19 @@ impl MutationTransaction { claims: Option<&crate::api::VerifiedRequestClaims>, current: &ProposalAuthority, ) -> Result { + self.proposal_public_projection(tx, registry, document, claims, current) + .await + .map(|(value, _)| value) + } + + async fn proposal_public_projection( + &self, + tx: &Transaction<'_>, + registry: &CompiledRegistry, + document: &ProposalDocument, + claims: Option<&crate::api::VerifiedRequestClaims>, + current: &ProposalAuthority, + ) -> Result<(Value, Option), MutationError> { let action = proposal_action(registry, &document.action_id)?; let mut value = json!({"id":document.proposal_id,"actionId":document.action_id, "actionRevision":document.action_revision,"submissionVersion":document.header.submission_version, @@ -3673,6 +4290,10 @@ impl MutationTransaction { if let Some(title) = &document.action_title { value["title"] = json!(title); } + // The party whose entry admitted the caller; staff reads carry none. + if let Some(party) = current.party { + value["partyRole"] = json!(party); + } // `blockedReason` is the public package-compatibility marker. A // refused manual application is exposed through `applicationStatus` // instead, whose reason vocabulary already includes that outcome. @@ -3720,7 +4341,16 @@ impl MutationTransaction { ); } let Some(claims) = claims else { - return Ok(value); + return Ok((value, None)); + }; + let thread_side = if let Some((messages, side)) = self + .public_messages(tx, registry, action, document, claims, current) + .await? + { + value["messages"] = messages; + Some(side) + } else { + None }; // A command response discloses the decision, the hand-off refusal, // the inputs and the attachments to a caller whose selected access @@ -3735,6 +4365,7 @@ impl MutationTransaction { Some(current.common.access_profile()), ProposalAuthorityOperation::Lifecycle(ProposalOperation::Get), Some(document.proposal_id), + self.party_selection(document, current), ) { Some(authority) => link_readable( self.check_proposal_document(tx, registry, document, &authority, false) @@ -3794,11 +4425,7 @@ impl MutationTransaction { let CompiledActionExecution::Proposal { proposal } = &action.execution else { return Err(MutationError::InvalidRequest); }; - if let Some(permission) = proposal - .permissions - .iter() - .find(|permission| permission.profile_id == get_authority.common.access_profile()) - { + if let Some(permission) = get_authority.permission(proposal) { if let Some(inputs) = public_inputs(action, &permission.readable_inputs, document.input.as_ref()) { @@ -3891,6 +4518,7 @@ impl MutationTransaction { Some(current.common.access_profile()), ProposalAuthorityOperation::Lifecycle(operation), Some(document.proposal_id), + self.party_selection(document, current), ) }; let Some(authority) = authority else { @@ -3904,6 +4532,7 @@ impl MutationTransaction { Some(current.common.access_profile()), ProposalAuthorityOperation::Start, None, + crate::api::proposals::PartySelection::Any, ) .is_none() { @@ -3964,7 +4593,9 @@ impl MutationTransaction { document.header.state != "draft" && !document.header.current_proposal_erased } ProposalOperation::GetApplicationActor => false, - ProposalOperation::Add | ProposalOperation::Answer => false, + ProposalOperation::Add | ProposalOperation::Answer | ProposalOperation::Message => { + false + } ProposalOperation::List => false, }; if !available @@ -4069,10 +4700,7 @@ impl MutationTransaction { let CompiledActionExecution::Proposal { proposal: policy } = &action.execution else { return Err(MutationError::Unavailable); }; - let permission = policy - .permissions - .iter() - .find(|permission| permission.profile_id == current.common.access_profile()); + let permission = current.permission(policy); if let Some(permission) = permission { // Attachments are Get-scoped like the inputs: the same gate decides them. let read = get_authority.as_ref(); @@ -4083,6 +4711,7 @@ impl MutationTransaction { Some(current.common.access_profile()), ProposalAuthorityOperation::Lifecycle(ProposalOperation::Edit), Some(document.proposal_id), + self.party_selection(document, current), ); let write = match write { Some(authority) => link_readable( @@ -4139,12 +4768,16 @@ impl MutationTransaction { if !slots.is_empty() { value["attachments"] = Value::Object(slots); } + self.append_forms( + tx, registry, action, document, current, claims, permission, read, &mut value, + ) + .await?; self.append_additions( tx, registry, action, document, current, claims, permission, read, &mut value, ) .await?; } - Ok(value) + Ok((value, thread_side)) } } @@ -4403,6 +5036,7 @@ fn application_actor_disclosed( }; Ok(proposal.permissions.iter().any(|permission| { permission.profile_id == authority.common.access_profile() + && permission.party == authority.party && permission .operations .contains(&ProposalOperation::GetApplicationActor) @@ -4424,6 +5058,44 @@ fn public_application( value } +fn frozen_scope( + frozen: &crate::proposal_workflow::ProposalSnapshot, +) -> Result>, MutationError> { + let mut targets = BTreeMap::new(); + for target in frozen.input_targets() { + let id = Uuid::parse_str(target.record_id.as_str()) + .map_err(|_| MutationError::PreconditionFailed)?; + targets.insert((target.record_type.clone(), id), None); + } + for effect in frozen.effects() { + if let Some(id) = effect.target().existing_record_id() { + targets.insert( + ( + effect.target().entity_id().as_str().to_owned(), + Uuid::parse_str(id.as_str()).map_err(|_| MutationError::PreconditionFailed)?, + ), + effect + .target() + .base_revision() + .map(|revision| revision.get()), + ); + } + } + if let Some(guards) = frozen.application_preconditions() { + for target in &guards.targets { + targets.insert( + ( + target.entity_id.clone(), + Uuid::parse_str(target.record_id.as_str()) + .map_err(|_| MutationError::PreconditionFailed)?, + ), + Some(target.expected_revision), + ); + } + } + Ok(targets) +} + fn proposal_action<'a>( registry: &'a CompiledRegistry, id: &str, @@ -4553,6 +5225,7 @@ async fn current_turn_context( let mut context = proposal_turn_context(document.blocked_reason.is_some(), review, &application); context.ask_open = document.ask_open; + context.message_unread = document.party_message_unread; Ok((state, context)) } @@ -4595,6 +5268,7 @@ fn proposal_turn_context( submission_blocked: blocked, review, ask_open: false, + message_unread: false, application, } } @@ -4604,28 +5278,21 @@ fn proposal_turn_context( pub(crate) const PUBLIC_REASON_REFERENCE: &str = "proposal-review-public-reason"; pub(crate) const REVIEW_PROGRESS_REFERENCE: &str = "proposal-review-progress"; -/// Whether a Get-authority document check lets the caller read the Proposal. -/// Only the two refusals a Proposal read gives a caller who may not read it -/// withhold what Get serves. A conflict, a retryable conflict or any other -/// failure stays an error, so nobody takes a failure for a refusal that would -/// silently omit what the caller may read. +/// Whether the document check lets the caller see a Proposal in a projection. +/// A refusal omits the candidate from a collection or a link. A store failure +/// still fails the request, since the caller may be entitled to the candidate. pub(crate) fn link_readable(outcome: Result<(), MutationError>) -> Result { match outcome { Ok(()) => Ok(true), - Err(MutationError::AuthorizationRefused(_) | MutationError::PreconditionFailed) => { - Ok(false) - } + Err( + MutationError::AuthorizationRefused(_) + | MutationError::PreconditionFailed + | MutationError::MembershipPreconditionFailed, + ) => Ok(false), Err(error) => Err(error), } } -/// The audit marker a replay records when the stored response it serves -/// again holds a decision's public reason. -fn replayed_public_reason(body: &[u8]) -> Result { - let response: Value = serde_json::from_slice(body).map_err(|_| MutationError::Unavailable)?; - Ok(ProposalReadDisclosure::for_value(&response)) -} - /// Why the review authority refused one submission's hand-off for good, as /// the allowlisted code recorded when it refused. A hand-off still pending, /// accepted, retrying or withdrawn names no refusal, and neither does a @@ -4917,6 +5584,36 @@ async fn load_proposal_row( #[cfg(test)] mod disclosure_tests { use super::*; + + #[test] + fn attachment_and_answer_target_concealment_keeps_the_observed_cause() { + use registry_platform_authcommon::FailedCheck; + + for operation in [ProposalOperation::Answer, ProposalOperation::Add] { + let operation = ProposalAuthorityOperation::Lifecycle(operation); + assert_eq!( + proposal_mutation_target_error(operation, MutationError::PreconditionFailed), + MutationError::AuthorizationRefused(FailedCheck::Visibility), + ); + for error in [ + MutationError::MembershipPreconditionFailed, + MutationError::Unavailable, + ] { + assert_eq!( + proposal_mutation_target_error(operation, error.clone()), + error + ); + } + } + assert_eq!( + proposal_mutation_target_error( + ProposalAuthorityOperation::Lifecycle(ProposalOperation::Edit), + MutationError::PreconditionFailed, + ), + MutationError::PreconditionFailed, + ); + } + fn coordinator(database: &str, activation: &str, key: u8, issuer: &str) -> MutationTransaction { let (audit, _capture) = crate::audit::test_support::capturing( registry_platform_audit::AuditProfile::production_from_secret_bytes( @@ -5121,6 +5818,7 @@ mod disclosure_tests { input_targets: Vec::new(), blocked_reason: None, ask_open: false, + party_message_unread: false, created_at: "2026-10-14T00:00:00Z".to_owned(), header: crate::proposal_store::ProposalWorkflowHeader { owner_reference: "owner".to_owned(), @@ -5130,6 +5828,7 @@ mod disclosure_tests { current_proposal_erased: false, applier_reference: None, application_reason_present: false, + subject_reference: None, }, }; let authority_for = |issuer: Option<&str>| { @@ -5139,6 +5838,7 @@ mod disclosure_tests { ProposalAuthorityOperation::Lifecycle(ProposalOperation::Get), "alice", "directory-editor", + Some(ProposalParty::Owner), Some("directory-administration"), BTreeMap::from([( "contact".to_owned(), @@ -5222,14 +5922,16 @@ mod disclosure_tests { /// The check a Proposal document fails against the caller's authority, if /// any: another action, a Proposal outside the grant's bound scope, or a /// Proposal another caller owns. +#[allow(clippy::too_many_arguments)] fn proposal_document_refusal( document_action_id: &str, authority_action_id: &str, scope: Option<&BTreeSet>, proposal_id: Uuid, - ownership: Option, + party: Option, document_owner: &str, caller_owner: impl FnOnce() -> String, + caller_subject: impl FnOnce() -> bool, ) -> Option { use registry_platform_authcommon::FailedCheck; if document_action_id != authority_action_id { @@ -5238,8 +5940,14 @@ fn proposal_document_refusal( if scope.is_some_and(|scope| !scope.contains(&proposal_id)) { return Some(FailedCheck::TaskGrantScope); } - if ownership == Some(ProposalOwnership::Caller) && document_owner != caller_owner() { - return Some(FailedCheck::Ownership); + match party { + Some(ProposalParty::Owner) if document_owner != caller_owner() => { + return Some(FailedCheck::Ownership); + } + Some(ProposalParty::Subject) if !caller_subject() => { + return Some(FailedCheck::Ownership); + } + _ => {} } None } @@ -5257,7 +5965,14 @@ mod document_refusal_tests { let check = |action: &str, scope: Option<&BTreeSet>, proposal: Uuid, ownership, who: &str| { proposal_document_refusal( - action, "action-a", scope, proposal, ownership, who, owner, + action, + "action-a", + scope, + proposal, + ownership, + who, + owner, + || false, ) }; assert_eq!( @@ -5279,7 +5994,7 @@ mod document_refusal_tests { "action-a", Some(&scope), id, - Some(ProposalOwnership::Caller), + Some(ProposalParty::Owner), "owner-b" ), Some(FailedCheck::Ownership) @@ -5289,13 +6004,35 @@ mod document_refusal_tests { "action-a", Some(&scope), id, - Some(ProposalOwnership::Caller), + Some(ProposalParty::Owner), "owner-a" ), None ); // Another owner's Proposal is admitted when ownership is not the caller's. assert_eq!(check("action-a", None, id, None, "owner-b"), None); + // A subject entry admits only the bound subject, whoever owns it. + assert_eq!( + check( + "action-a", + None, + id, + Some(ProposalParty::Subject), + "owner-a" + ), + Some(FailedCheck::Ownership) + ); + let subject = proposal_document_refusal( + "action-a", + "action-a", + None, + id, + Some(ProposalParty::Subject), + "owner-b", + owner, + || true, + ); + assert_eq!(subject, None); } } @@ -5397,7 +6134,7 @@ mod input_write_tests { {"id":"value","type":"string","required":true,"maximumLength":64,"classification":"internal"}, {"id":"licence-number","type":"string","required":false,"maximumLength":64,"classification":"internal"}], "plan":{"type":"fixed","effects":[{"id":"name","target":{"fromInput":"target"},"operation":"patch","set":{"name":{"fromInput":"value"}}}]}}}, - "accessProfiles":{"clerk": {"default":true,"principalClaim":"sub","requiredScopes":"unrestricted","permissions":{ + "accessProfiles":{"clerk": {"default":true,"principalClaim":"sub","requiredScopes":["records:write"],"permissions":{ "actions":[{"action":"correct-name","operations":["start"],"targets":[{"recordType":"target","rowBoundaries":"unrestricted"}]}]}}}}); let project = crate::contract::parse_project_json(&serde_json::to_vec(&source).unwrap()).unwrap(); diff --git a/crates/registry-breg/src/mutation/proposal/additions.rs b/crates/registry-breg/src/mutation/proposal/additions.rs index 5ff58fe47a..9239e3b403 100644 --- a/crates/registry-breg/src/mutation/proposal/additions.rs +++ b/crates/registry-breg/src/mutation/proposal/additions.rs @@ -29,6 +29,7 @@ impl MutationTransaction { Some(current.common.access_profile()), ProposalAuthorityOperation::Lifecycle(ProposalOperation::Add), Some(document.proposal_id), + self.party_selection(document, current), ) .filter(|_| permission.writable_attachments.contains(&slot.id)); let write = match write { diff --git a/crates/registry-breg/src/mutation/proposal/asks.rs b/crates/registry-breg/src/mutation/proposal/asks.rs index 76297ccd1e..d37222a3a6 100644 --- a/crates/registry-breg/src/mutation/proposal/asks.rs +++ b/crates/registry-breg/src/mutation/proposal/asks.rs @@ -42,10 +42,10 @@ impl MutationTransaction { let wants: Vec = serde_json::from_value(row.get(2)).map_err(|_| MutationError::Unavailable)?; answer.body.validate(&wants).map_err(|field| { - MutationError::InvalidRequestAt(if field == "text" { - RequestLocation::proposal_answer_text() - } else { - RequestLocation::proposal_answer_additions() + MutationError::InvalidRequestAt(match field { + "text" => RequestLocation::proposal_answer_text(), + "formEntries" => RequestLocation::proposal_answer_form_entries(), + _ => RequestLocation::proposal_answer_additions(), }) })?; let asked: DateTime = row @@ -76,6 +76,32 @@ impl MutationTransaction { RequestLocation::proposal_answer_additions(), )); } + let requested_forms = wants + .iter() + .filter_map(|want| match want { + registry_review_client::ReviewAskWant::Form { form } => Some(form.as_str()), + _ => None, + }) + .collect::>(); + let cited = tx.query( + "SELECT f.form_id + FROM registry_internal.registry_proposal_form_entries f + WHERE f.action_id=$1 AND f.proposal_id=$2 AND f.submission_version=$3 + AND f.entry_id=ANY($4) AND f.detail_erased_at IS NULL + AND NOT EXISTS (SELECT 1 FROM registry_internal.registry_proposal_review_ask_form_entries c + WHERE c.action_id=f.action_id AND c.proposal_id=f.proposal_id + AND c.submission_version=f.submission_version AND c.entry_id=f.entry_id)", + &[&document.action_id,&document.proposal_id,&document.header.submission_version,&answer.body.form_entries], + ).await.map_err(map_database_error)?; + let cited_forms = cited + .iter() + .map(|row| row.get::<_, &str>(0)) + .collect::>(); + if cited.len() != answer.body.form_entries.len() || cited_forms != requested_forms { + return Err(MutationError::InvalidRequestAt( + RequestLocation::proposal_answer_form_entries(), + )); + } let key_material = canonicalize_json( &json!({"authority":authority,"requestId":request,"askId":answer.ask_id}), ) @@ -88,6 +114,15 @@ impl MutationTransaction { for addition in &answer.body.additions { tx.execute("INSERT INTO registry_internal.registry_proposal_review_ask_files(authority,review_request_id,ask_id,action_id,proposal_id,submission_version,addition_id) VALUES($1,$2,$3,$4,$5,$6,$7)",&[&authority,&request,&answer.ask_id,&document.action_id,&document.proposal_id,&document.header.submission_version,addition]).await.map_err(map_database_error)?; } + for entry in &answer.body.form_entries { + tx.execute( + "INSERT INTO registry_internal.registry_proposal_review_ask_form_entries + (authority,review_request_id,ask_id,action_id,proposal_id,submission_version,entry_id) + VALUES($1,$2,$3,$4,$5,$6,$7)", + &[&authority,&request,&answer.ask_id,&document.action_id,&document.proposal_id, + &document.header.submission_version,entry], + ).await.map_err(map_database_error)?; + } // The mirror keeps the provider's state. The local answer row makes // the applicant document answered and ends the party's turn immediately. Ok(()) @@ -95,6 +130,53 @@ impl MutationTransaction { } impl MutationTransaction { + pub(super) async fn check_message_receipt_ask_binding( + &self, + tx: &Transaction<'_>, + registry: &CompiledRegistry, + document: &ProposalDocument, + held: &Value, + ) -> Result<(), MutationError> { + let Some(asks) = held + .get("asks") + .and_then(Value::as_array) + .filter(|asks| !asks.is_empty()) + else { + return Ok(()); + }; + let workflow = + proposal_store::load(tx, &document.action_id, document.proposal_id, false).await?; + let frozen = workflow + .current_proposal() + .ok_or(MutationError::IdempotencyConflict)?; + let CompiledProposalReview::Required { authority, .. } = frozen.review_requirement() else { + return Err(MutationError::IdempotencyConflict); + }; + let binding = crate::review_store::load_task_context_binding( + tx, + registry, + &document.action_id, + document.proposal_id, + frozen, + ) + .await + .map_err(|error| match error { + MutationError::PreconditionFailed => MutationError::IdempotencyConflict, + other => other, + })?; + let rows = ask_rows(tx, document, Some((authority, binding.request_id))).await?; + if asks.iter().all(|ask| { + ask.get("id") + .and_then(Value::as_str) + .and_then(|id| Uuid::parse_str(id).ok()) + .is_some_and(|id| rows.iter().any(|row| row.get::<_, Uuid>(0) == id)) + }) { + Ok(()) + } else { + Err(MutationError::IdempotencyConflict) + } + } + #[allow(clippy::too_many_arguments)] pub(super) async fn append_public_asks( &self, @@ -118,6 +200,7 @@ impl MutationTransaction { Some(current.common.access_profile()), ProposalAuthorityOperation::Lifecycle(ProposalOperation::Answer), Some(document.proposal_id), + self.party_selection(document, current), ); // Questions and answers reach only the party who may answer on this // Proposal. The Answer admission carries the human test, so other Get @@ -202,6 +285,7 @@ impl MutationTransaction { pub(crate) struct ProposalReadDisclosure { pub(crate) field_set_reference: Option<&'static str>, pub(crate) asks: bool, + pub(crate) message_text_count: usize, pub(crate) ask_download: Option<(Uuid, Uuid)>, } const ASK_REFERENCE: &str = "proposal-review-ask"; @@ -217,6 +301,17 @@ impl ProposalReadDisclosure { .or_else(|| value.pointer("/context/asks")) .and_then(Value::as_array) .is_some_and(|asks| !asks.is_empty()), + message_text_count: value + .pointer("/messages/items") + .or_else(|| value.pointer("/context/messages/items")) + .or_else(|| value.get("count").and_then(|_| value.get("items"))) + .and_then(Value::as_array) + .map_or(0, |items| { + items + .iter() + .filter(|item| item.get("text").is_some()) + .count() + }), ask_download: None, } } @@ -247,6 +342,10 @@ impl ProposalReadDisclosure { record["fieldSetReference"] = json!(ASK_REFERENCE); } } + if self.message_text_count != 0 { + record["messageFieldSetReference"] = json!("proposal-messages"); + record["messageTextCount"] = json!(self.message_text_count); + } if let Some((ask, file)) = self.ask_download { record["reviewAskId"] = json!(ask); record["additionId"] = json!(file); @@ -264,7 +363,10 @@ async fn ask_rows( document: &ProposalDocument, binding: Option<(&str, Uuid)>, ) -> Result, MutationError> { - tx.query("SELECT a.ask_id,a.text,a.wants,a.asked_at_wire,a.due_at_wire,a.state,x.ask_id IS NOT NULL,x.text,x.answered_at,ARRAY(SELECT c.addition_id FROM registry_internal.registry_proposal_review_ask_files c WHERE c.authority=a.authority AND c.review_request_id=a.review_request_id AND c.ask_id=a.ask_id ORDER BY c.addition_id) FROM registry_internal.registry_proposal_review_asks a LEFT JOIN registry_internal.registry_proposal_review_ask_answers x USING(authority,review_request_id,ask_id) WHERE a.action_id=$1 AND a.proposal_id=$2 AND a.submission_version=$3 AND a.text IS NOT NULL AND a.detail_erased_at IS NULL AND ($4::text IS NULL OR (a.authority=$4 AND a.review_request_id=$5 AND EXISTS (SELECT 1 FROM registry_internal.registry_proposal_review_submissions s WHERE s.action_id=a.action_id AND s.proposal_id=a.proposal_id AND s.submission_version=a.submission_version AND s.authority=a.authority AND s.accepted_binding->>'requestId'=a.review_request_id::text AND NOT s.withdrawn AND s.state='accepted'))) ORDER BY a.asked_at DESC,a.ask_id DESC LIMIT $6",&[&document.action_id,&document.proposal_id,&document.header.submission_version,&binding.map(|b|b.0),&binding.map(|b|b.1),&(crate::contract::MAX_MIRRORED_REVIEW_ASKS as i64)]).await.map_err(map_database_error) + tx.query("SELECT a.ask_id,a.text,a.wants,a.asked_at_wire,a.due_at_wire,a.state,x.ask_id IS NOT NULL,x.text,x.answered_at,ARRAY(SELECT c.addition_id FROM registry_internal.registry_proposal_review_ask_files c WHERE c.authority=a.authority AND c.review_request_id=a.review_request_id AND c.ask_id=a.ask_id ORDER BY c.addition_id), + ARRAY(SELECT c.entry_id FROM registry_internal.registry_proposal_review_ask_form_entries c + WHERE c.authority=a.authority AND c.review_request_id=a.review_request_id AND c.ask_id=a.ask_id + ORDER BY c.entry_id) FROM registry_internal.registry_proposal_review_asks a LEFT JOIN registry_internal.registry_proposal_review_ask_answers x USING(authority,review_request_id,ask_id) WHERE a.action_id=$1 AND a.proposal_id=$2 AND a.submission_version=$3 AND a.text IS NOT NULL AND a.detail_erased_at IS NULL AND ($4::text IS NULL OR (a.authority=$4 AND a.review_request_id=$5 AND EXISTS (SELECT 1 FROM registry_internal.registry_proposal_review_submissions s WHERE s.action_id=a.action_id AND s.proposal_id=a.proposal_id AND s.submission_version=a.submission_version AND s.authority=a.authority AND s.accepted_binding->>'requestId'=a.review_request_id::text AND NOT s.withdrawn AND s.state='accepted'))) ORDER BY a.asked_at DESC,a.ask_id DESC LIMIT $6",&[&document.action_id,&document.proposal_id,&document.header.submission_version,&binding.map(|b|b.0),&binding.map(|b|b.1),&(crate::contract::MAX_MIRRORED_REVIEW_ASKS as i64)]).await.map_err(map_database_error) } fn ask_value(row: &tokio_postgres::Row) -> Value { @@ -281,6 +383,10 @@ fn ask_value(row: &tokio_postgres::Row) -> Value { if let Some(text) = row.get::<_, Option>(7) { answer["text"] = json!(text); } + let entries: Vec = row.get(10); + if !entries.is_empty() { + answer["formEntries"] = json!(entries); + } value["answer"] = answer; } value @@ -361,6 +467,22 @@ impl MutationTransaction { documents.push(descriptor); } answer.insert("documents".into(), json!(documents)); + let entries: Vec = row.get(10); + if !entries.is_empty() { + let action = proposal_action(registry, &document.action_id)?; + let CompiledActionExecution::Proposal { proposal } = &action.execution else { + return Err(MutationError::Unavailable); + }; + let entries = super::forms::items( + tx, + document, + None, + Some(&entries), + &proposal.additional_forms, + ) + .await?; + answer.insert("formEntries".into(), json!(entries)); + } } asks.push(ask); } diff --git a/crates/registry-breg/src/mutation/proposal/context_projection.rs b/crates/registry-breg/src/mutation/proposal/context_projection.rs index 489b642fcd..260982e53f 100644 --- a/crates/registry-breg/src/mutation/proposal/context_projection.rs +++ b/crates/registry-breg/src/mutation/proposal/context_projection.rs @@ -27,24 +27,30 @@ pub(super) async fn fields( .iter() .find(|permission| { permission.profile_id == authority.common.access_profile() + && permission.party == authority.party && permission.operations.contains(&match authority.operation { ProposalAuthorityOperation::Lifecycle(operation) => operation, ProposalAuthorityOperation::Start => return false, }) }) .ok_or(MutationError::PreconditionFailed)?; - let document_contract = if mapping + let fields = mapping .fields .iter() - .filter(|(field, _)| selected_fields.is_none_or(|selected| selected.contains(*field))) - .map(|(_, source)| source) - .any(|source| { - matches!( - source, - ProposalContextValueSource::Document { .. } - | ProposalContextValueSource::Additions { .. } - ) - }) { + .filter(|(field, _)| selected_fields.is_none_or(|selected| selected.contains(*field))); + if fields + .clone() + .any(|(field, _)| !permission.readable_context_fields.contains(field)) + { + return Err(MutationError::PreconditionFailed); + } + let document_contract = if fields.clone().any(|(_, source)| { + matches!( + source, + ProposalContextValueSource::Document { .. } + | ProposalContextValueSource::Additions { .. } + ) + }) { Some( crate::compiler::review_context::compile_schema(registry, action) .map_err(|_| MutationError::Unavailable)? @@ -64,12 +70,9 @@ pub(super) async fn fields( { return Err(MutationError::PreconditionFailed); } - let targets = if mapping - .fields - .iter() - .filter(|(field, _)| selected_fields.is_none_or(|selected| selected.contains(*field))) - .map(|(_, source)| source) - .any(|source| matches!(source, ProposalContextValueSource::Changes { .. })) + let targets = if fields + .clone() + .any(|(_, source)| matches!(source, ProposalContextValueSource::Changes { .. })) { frozen .verify_digest(&crate::proposal_workflow::ProposalKey::new( @@ -89,15 +92,37 @@ pub(super) async fn fields( } else { Vec::new() }; - let mut projected = Map::new(); - for (field, source) in &mapping.fields { - if selected_fields.is_some_and(|selected| !selected.contains(field)) { - continue; - } - if !permission.readable_context_fields.contains(field) { - return Err(MutationError::PreconditionFailed); - } + // Resolve the selected Record scopes before acquiring document metadata. + // Keep the canonical field order independently of acquisition order. + let record_source = |source: &ProposalContextValueSource| { + matches!( + source, + ProposalContextValueSource::Record { .. } | ProposalContextValueSource::Changes { .. } + ) + }; + let mut projected = BTreeMap::new(); + for (field, source) in fields + .clone() + .filter(|(_, source)| record_source(source)) + .chain(fields.filter(|(_, source)| !record_source(source))) + { let resolved = match source { + ProposalContextValueSource::AdditionalForm { form } => { + if authority.operation + != ProposalAuthorityOperation::Lifecycle(ProposalOperation::GetReviewContext) + || !authority.receives_form_values + { + return Err(MutationError::PreconditionFailed); + } + Value::Array( + super::forms::items(tx, document, Some(form), None, &proposal.additional_forms) + .await? + .into_iter() + .filter(|item| item.get("input").is_some()) + .collect(), + ) + } + ProposalContextValueSource::Additions { slot } => { let schema = document_contract .as_ref() @@ -192,12 +217,7 @@ pub(super) async fn fields( .and_then(|id| Uuid::parse_str(id).ok()) .ok_or(MutationError::PreconditionFailed)?; let row = load_proposal_row(tx, entity, id, false).await?; - if !authority - .authorizes_snapshot(entity, id, &row.data) - .map_err(|_| MutationError::PreconditionFailed)? - { - return Err(MutationError::PreconditionFailed); - } + require_snapshot(tx, entity, record, authority, id, &row.data).await?; let optional = !entity .fields .get(field) @@ -293,7 +313,7 @@ pub(super) async fn fields( }; projected.insert(field.clone(), resolved); } - Ok(projected) + Ok(projected.into_iter().collect()) } /// Prepare refuses a submission that omits a required input, so the frozen @@ -345,13 +365,10 @@ async fn require_snapshot( id: Uuid, snapshot: &Map, ) -> Result<(), MutationError> { - if !authority - .authorizes_snapshot(entity, id, snapshot) + if !record + .context + .authorizes_record_snapshot(entity, snapshot, id) .map_err(|_| MutationError::PreconditionFailed)? - || !record - .context - .authorizes_record_snapshot(entity, snapshot, id) - .map_err(|_| MutationError::PreconditionFailed)? { return Err(MutationError::PreconditionFailed); } @@ -379,7 +396,7 @@ async fn require_snapshot( return Err(MutationError::PreconditionFailed); } } - Ok(()) + require_proposal_target_snapshot(tx, authority, entity, id, snapshot).await } /// The members the profile may not see on `state`. A record the profile diff --git a/crates/registry-breg/src/mutation/proposal/forms.rs b/crates/registry-breg/src/mutation/proposal/forms.rs new file mode 100644 index 0000000000..7a9400044d --- /dev/null +++ b/crates/registry-breg/src/mutation/proposal/forms.rs @@ -0,0 +1,391 @@ +// SPDX-License-Identifier: Apache-2.0 +use super::*; +use crate::{ + api::proposals::FormMutation, + contract::{ProposalContextValueSource, ProposalReviewContextSource, MAX_MIRRORED_REVIEW_ASKS}, + data::{validate_field_value, FieldValue}, + model::CompiledAdditionalForm, + problem_location::RequestLocation, +}; +use registry_platform_authcommon::FailedCheck; + +// Reserve the largest supported lifecycle projection outside the submitted +// inputs and form items. One ask can include 2,000 bytes each of question and +// answer text (up to 2x and 6x in JSON), eight wants, citations and an answer +// link. Each inline message can include 2,000 bytes of text (up to 2x in +// JSON), sender metadata and an ID. The remaining reserve covers Proposal +// state and links, decisions, application results, attachment and addition +// descriptors, and the form descriptors and Add result ID. +const LIFECYCLE_METADATA_BYTES: usize = 128 * 1024 + + MAX_MIRRORED_REVIEW_ASKS * 20 * 1024 + + crate::proposal_messages::DOCUMENT_ITEMS as usize * 5 * 1024; +// Covers the entry's UUID, timestamp, submission version, member names and +// separator, including a contract-changed marker for a small retained input. +const FORM_ENTRY_FRAMING_BYTES: usize = 128; + +fn digest(action: &str, id: &str, form: &CompiledAdditionalForm) -> String { + crate::artifacts::additional_form_contract(action, id, &form.inputs)["digest"] + .as_str() + .expect("an additional form contract has a digest") + .to_owned() +} + +pub(super) async fn insert( + tx: &Transaction<'_>, + action: &CompiledAction, + document: &ProposalDocument, + authority: &ProposalAuthority, + entry: &FormMutation<'_>, + actor: &str, +) -> Result<(Uuid, Vec), MutationError> { + let CompiledActionExecution::Proposal { proposal } = &action.execution else { + return Err(MutationError::InvalidRequest); + }; + let form = proposal + .additional_forms + .get(entry.id) + .ok_or(MutationError::FormUndeclared)?; + if !authority + .permission(proposal) + .is_some_and(|grant| grant.writable_forms.contains(entry.id)) + { + return Err(MutationError::AuthorizationRefused( + FailedCheck::AccessProfile, + )); + } + 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 + .values + .get(&input.api_name) + .map_or(!input.required, |value| { + validate_field_value(FieldValue::Json(value), &input.field_type) + }); + if !valid { + return Err(MutationError::InvalidRequestAt( + RequestLocation::action_input(&input.api_name), + )); + } + } + if entry.values.is_empty() { + return Err(MutationError::InvalidRequest); + } + let input_ids = form + .inputs + .iter() + .filter(|input| entry.values.contains_key(&input.api_name)) + .map(|input| input.id.clone()) + .collect(); + let count = count(tx, document, entry.id).await?; + if count >= i64::from(form.maximum_count) { + return Err(MutationError::FormLimitReached); + } + let id = Uuid::new_v4(); + tx.execute( + "INSERT INTO registry_internal.registry_proposal_form_entries + (action_id,proposal_id,submission_version,form_id,entry_id,input,contract_digest,added_by) + VALUES ($1,$2,$3,$4,$5,$6,$7,$8)", + &[&document.action_id,&document.proposal_id,&document.header.submission_version, + &entry.id,&id,&json!(entry.values),&digest(&action.id,entry.id,form),&actor], + ).await.map_err(map_database_error)?; + // Measure the tentative entry as PostgreSQL will return it. The caller + // holds the Proposal state lock and rolls back the insert on refusal. + let rows = tx + .query( + "SELECT form_id,input FROM registry_internal.registry_proposal_form_entries + WHERE action_id=$1 AND proposal_id=$2 AND submission_version=$3 + AND detail_erased_at IS NULL + LIMIT $4", + &[ + &document.action_id, + &document.proposal_id, + &document.header.submission_version, + // This many entries already exceed the budget from framing alone. + &((form_budget(0) / FORM_ENTRY_FRAMING_BYTES + 1) as i64), + ], + ) + .await + .map_err(map_database_error)?; + check_aggregate_budget( + public_input_bytes(document.input.as_ref())?, + proposal.review_context.as_ref(), + rows.into_iter().map(|row| (row.get(0), row.get(1))), + )?; + Ok((id, input_ids)) +} + +async fn count( + tx: &Transaction<'_>, + document: &ProposalDocument, + form: &str, +) -> Result { + Ok(tx + .query_one( + "SELECT count(*) FROM registry_internal.registry_proposal_form_entries + WHERE action_id=$1 AND proposal_id=$2 AND submission_version=$3 AND form_id=$4", + &[ + &document.action_id, + &document.proposal_id, + &document.header.submission_version, + &form, + ], + ) + .await + .map_err(map_database_error)? + .get(0)) +} + +pub(super) async fn items( + tx: &Transaction<'_>, + document: &ProposalDocument, + form_id: Option<&str>, + cited: Option<&[Uuid]>, + forms: &BTreeMap, +) -> Result, MutationError> { + let rows = tx + .query( + "SELECT entry_id,form_id,input,contract_digest,added_at + FROM registry_internal.registry_proposal_form_entries + WHERE action_id=$1 AND proposal_id=$2 AND submission_version=$3 + AND detail_erased_at IS NULL AND ($4::text IS NULL OR form_id=$4) + AND ($5::uuid[] IS NULL OR entry_id=ANY($5)) + ORDER BY added_at,entry_id", + &[ + &document.action_id, + &document.proposal_id, + &document.header.submission_version, + &form_id, + &cited, + ], + ) + .await + .map_err(map_database_error)?; + Ok(rows + .into_iter() + .map(|row| { + let id: Uuid = row.get(0); + let form_id: String = row.get(1); + let retained_digest: String = row.get(3); + let mut item = json!({"id":id,"addedAt":row.get::<_,chrono::DateTime>(4)}); + if forms + .get(&form_id) + .is_some_and(|form| digest(&document.action_id, &form_id, form) == retained_digest) + { + item["input"] = row.get(2); + } else { + item["contractChanged"] = json!(true); + } + item + }) + .collect()) +} + +impl MutationTransaction { + #[allow(clippy::too_many_arguments)] + pub(super) async fn append_forms( + &self, + tx: &Transaction<'_>, + registry: &CompiledRegistry, + action: &CompiledAction, + document: &ProposalDocument, + current: &ProposalAuthority, + claims: &crate::api::VerifiedRequestClaims, + permission: &crate::model::CompiledProposalPermission, + read: Option<&ProposalAuthority>, + value: &mut Value, + ) -> Result<(), MutationError> { + let CompiledActionExecution::Proposal { proposal } = &action.execution else { + return Ok(()); + }; + if proposal.additional_forms.is_empty() { + return Ok(()); + } + let write = crate::api::proposals::authorize( + registry, + action, + claims, + Some(current.common.access_profile()), + ProposalAuthorityOperation::Lifecycle(ProposalOperation::Add), + Some(document.proposal_id), + self.party_selection(document, current), + ); + let write = match write { + Some(authority) if !permission.writable_forms.is_empty() => link_readable( + self.check_proposal_document(tx, registry, document, &authority, false) + .await, + )? + .then_some(authority), + _ => None, + }; + let refusal = if write.is_none() { + None + } else if document.header.state == "applied" { + Some(LinkRefusal::AlreadyApplied) + } else if document.header.state == "rejected" { + Some(LinkRefusal::Rejected) + } else if document.header.state != "submitted" || document.header.current_proposal_erased { + Some(LinkRefusal::WrongState) + } else if document.blocked_reason.as_deref() == Some("application-refused") { + Some(LinkRefusal::ReviseInput) + } else if document.blocked_reason.as_deref() == Some("application-rebase") { + Some(LinkRefusal::TargetChanged) + } else if document.blocked_reason.is_some() + || document.action_revision != action.definition_revision + { + Some(LinkRefusal::PackageChanged) + } else { + let workflow = + proposal_store::load(tx, &action.id, document.proposal_id, false).await?; + match workflow.current_proposal() { + Some(frozen) => match review_progress(tx, document, frozen).await? { + ProposalReviewProgress::Pending | ProposalReviewProgress::Retrying => None, + ProposalReviewProgress::Rejected => Some(LinkRefusal::ReviewRejected), + ProposalReviewProgress::ChangesRequested => Some(LinkRefusal::ChangesRequested), + _ => Some(LinkRefusal::ReviewEnded), + }, + None => Some(LinkRefusal::WrongState), + } + }; + let mut visible = Map::new(); + for (id, form) in &proposal.additional_forms { + let mut description = json!({"id":id,"maximumCount":form.maximum_count}); + if read.is_some() && permission.readable_forms.contains(id) { + let mut entries = + items(tx, document, Some(id), None, &proposal.additional_forms).await?; + for entry in &mut entries { + entry["submissionVersion"] = json!(document.header.submission_version); + } + description["items"] = json!(entries); + } + if let Some(write) = write + .as_ref() + .filter(|_| permission.writable_forms.contains(id)) + { + let refusal = match refusal { + None if count(tx, document, id).await? >= i64::from(form.maximum_count) => { + Some(LinkRefusal::LimitReached) + } + other => other, + }; + description["links"] = json!({"add":{ + "method":"POST","path":format!("/v1/proposals/{}/additional-forms/{id}",document.proposal_id), + "accessProfile":write.common.access_profile(),"operation":"add", + "ifMatch":self.proposal_etag(document,write)?, + "availability":ProposalAvailability::new(document.header.workflow_revision as u64,refusal) + }}); + } + if description.get("items").is_some() || description.get("links").is_some() { + visible.insert(id.clone(), description); + } + } + if !visible.is_empty() { + value["additionalForms"] = Value::Object(visible); + } + Ok(()) + } +} + +fn public_input_bytes(input: Option<&Map>) -> Result { + let Some(input) = input else { + return Ok(0); + }; + // Every input could be disclosed. Reserve the full valid API name width + // for a successor package that projects the retained inputs under new names. + let api_name_growth: usize = input + .keys() + .map(|id| 64_usize.saturating_sub(id.len())) + .sum(); + Ok(canonicalize_json(&Value::Object(input.clone())) + .map_err(|_| MutationError::InvalidRequest)? + .len() + + api_name_growth) +} + +fn form_budget(input_bytes: usize) -> usize { + (MAX_HELD_BODY_BYTES - LIFECYCLE_METADATA_BYTES).saturating_sub(input_bytes) +} + +fn check_aggregate_budget( + input_bytes: usize, + context: Option<&ProposalReviewContextSource>, + entries: impl Iterator, +) -> Result<(), MutationError> { + let mut review_copies = BTreeMap::new(); + if let Some(context) = context { + for source in context.fields.values() { + if let ProposalContextValueSource::AdditionalForm { form } = source { + *review_copies.entry(form.as_str()).or_insert(0) += 1; + } + } + } + let mut public_remaining = form_budget(input_bytes); + let mut review_remaining = public_remaining; + for (form, input) in entries { + let bytes = canonicalize_json(&input) + .map_err(|_| MutationError::InvalidRequest)? + .len() + + FORM_ENTRY_FRAMING_BYTES; + public_remaining = public_remaining + .checked_sub(bytes) + .ok_or(MutationError::FormLimitReached)?; + review_remaining = review_remaining + .checked_sub(bytes * review_copies.get(form.as_str()).copied().unwrap_or(0)) + .ok_or(MutationError::FormLimitReached)?; + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn aggregate_form_budget_counts_every_form_and_reserves_lifecycle_response_space() { + // A maximum-sized synthetic entry includes escaped and multibyte text. + let input = json!({"note": "\"é".repeat(4000)}); + assert!(canonicalize_json(&input).unwrap().len() < 16 * 1024); + let entries = |count| { + ["first", "second", "third", "fourth", "fifth", "sixth"] + .into_iter() + .cycle() + .take(count) + .map(|form| (form.to_owned(), input.clone())) + }; + + let frozen_input_bytes = 160 * 1024; + assert_eq!( + check_aggregate_budget(frozen_input_bytes, None, entries(106)), + Ok(()) + ); + assert_eq!( + check_aggregate_budget(frozen_input_bytes, None, entries(107)), + Err(MutationError::FormLimitReached) + ); + } + + #[test] + fn aggregate_form_budget_charges_each_review_context_mapping() { + let context = serde_json::from_value(json!({"id":"review","fields":{ + "first":{"type":"additional-form","form":"note"}, + "duplicate":{"type":"additional-form","form":"note"} + }})) + .unwrap(); + let input = json!({"note": "x".repeat(15_000)}); + let entries = || (0..32).map(|_| ("note".to_owned(), input.clone())); + let frozen_input_bytes = 1024 * 1024; + assert_eq!( + check_aggregate_budget(frozen_input_bytes, None, entries()), + Ok(()) + ); + assert_eq!( + check_aggregate_budget(frozen_input_bytes, Some(&context), entries()), + Err(MutationError::FormLimitReached) + ); + } +} diff --git a/crates/registry-breg/src/mutation/proposal/messages.rs b/crates/registry-breg/src/mutation/proposal/messages.rs new file mode 100644 index 0000000000..a671419d08 --- /dev/null +++ b/crates/registry-breg/src/mutation/proposal/messages.rs @@ -0,0 +1,1023 @@ +// SPDX-License-Identifier: Apache-2.0 +//! The Proposal message thread: the write inside the Proposal transaction and +//! the `messages` member each caller's Message admission may read. +use super::*; +use crate::contract::ProposalContextValueSource; +use crate::idempotency::StoredMutationResult; +use crate::proposal_messages::{self, NewMessage, Side}; + +impl MutationTransaction { + pub(super) async fn replay_proposal_disclosure( + &self, + tx: &Transaction<'_>, + registry: &CompiledRegistry, + action: &CompiledAction, + document: &ProposalDocument, + input: &ProposalMutationInput<'_>, + stored: &StoredMutationResult, + ) -> Result { + let StoredResultMetadata::Proposal { thread_side, .. } = &stored.metadata else { + return Err(MutationError::Unavailable); + }; + let held: Value = serde_json::from_slice(stored.response.body()) + .map_err(|_| MutationError::Unavailable)?; + let disclosure = ProposalReadDisclosure::for_value(&held); + if input.message.is_some() { + check_receipt_side(*thread_side, Side::of(input.authority.party))?; + self.authorize_message_receipt(tx, registry, action, document, input, &held) + .await?; + } else if let Some(path) = receipt_thread_items_path(&held) { + let claims = input.claims.ok_or(MutationError::IdempotencyConflict)?; + let authority = self + .public_message_authority(tx, registry, action, document, claims, input.authority) + .await? + .ok_or(MutationError::IdempotencyConflict)?; + check_receipt_side(*thread_side, Side::of(authority.party))?; + self.check_message_receipt_items(tx, document, &authority, &held, path) + .await?; + } + Ok(disclosure) + } + + /// The no-Get reviewer receives an exact review response from the same + /// transaction as the write. Replay rechecks current disclosure before + /// returning the held bytes. + pub(super) async fn message_review_receipt( + &self, + tx: &Transaction<'_>, + registry: &CompiledRegistry, + action: &CompiledAction, + document: &ProposalDocument, + input: &ProposalMutationInput<'_>, + ) -> Result, MutationError> { + let claims = input.claims.ok_or(MutationError::InvalidRequest)?; + let admit = |operation| { + crate::api::proposals::authorize( + registry, + action, + claims, + Some(input.authority.common.access_profile()), + ProposalAuthorityOperation::Lifecycle(operation), + Some(document.proposal_id), + self.party_selection(document, input.authority), + ) + }; + if admit(ProposalOperation::Get).is_some() { + return Ok(None); + } + let Some(mut review) = admit(ProposalOperation::GetReviewContext) else { + return Ok(None); + }; + // Between review rounds, or after the Action changed, no review + // context is readable: the reviewer is answered with the thread. + if !review_context_readable(tx, action, document).await? { + return self + .proposal_messages_member(tx, action, document, input.authority, true) + .await; + } + review.receives_review_answers = false; + review.review_messages = Some((Box::new(input.authority.clone()), true)); + self.authorize_proposal_review_read(tx, registry, document, &review) + .await?; + let records = crate::api::proposals::review_record_authorities( + registry, + action, + claims, + &review, + ProposalOperation::GetReviewContext, + None, + ) + .ok_or(MutationError::PreconditionFailed)?; + self.proposal_review_value(tx, registry, document, &review, &records, None, None) + .await + .map(Some) + } + + async fn authorize_message_receipt( + &self, + tx: &Transaction<'_>, + registry: &CompiledRegistry, + action: &CompiledAction, + document: &ProposalDocument, + input: &ProposalMutationInput<'_>, + held: &Value, + ) -> Result<(), MutationError> { + let shape = message_receipt_shape(held).ok_or(MutationError::IdempotencyConflict)?; + // The exact key binding has already matched the selected profile. + // Reuse its current read path for the shape of the held response. + let current = if shape == MessageReceiptShape::Thread { + // Message authority still covers the thread when a review resumes. + self.proposal_messages_member(tx, action, document, input.authority, true) + .await? + } else { + match self + .message_review_receipt(tx, registry, action, document, input) + .await? + { + Some(review_or_thread) => Some(review_or_thread), + None if shape == MessageReceiptShape::Proposal => Some( + self.proposal_public_value( + tx, + registry, + document, + input.claims, + input.authority, + ) + .await?, + ), + None => None, + } + }; + let current = current.ok_or(MutationError::IdempotencyConflict)?; + let context_fields = match &action.execution { + CompiledActionExecution::Proposal { proposal } => proposal + .review_context + .as_ref() + .map(|context| &context.fields), + CompiledActionExecution::Immediate => None, + }; + if !message_receipt_projection_allows(held, ¤t, context_fields) { + return Err(MutationError::IdempotencyConflict); + } + if shape == MessageReceiptShape::Proposal { + self.check_message_receipt_ask_binding(tx, registry, document, held) + .await?; + } + let path = receipt_thread_items_path(held).ok_or(MutationError::IdempotencyConflict)?; + if !current.pointer(path).is_some_and(Value::is_array) { + return Err(MutationError::IdempotencyConflict); + } + self.check_message_receipt_items(tx, document, input.authority, held, path) + .await + } + + async fn check_message_receipt_items( + &self, + tx: &Transaction<'_>, + document: &ProposalDocument, + authority: &ProposalAuthority, + held: &Value, + path: &str, + ) -> Result<(), MutationError> { + if !authority.receives_review_answers { + return Err(MutationError::IdempotencyConflict); + } + let held_items = held + .pointer(path) + .and_then(Value::as_array) + .filter(|items| items.len() <= proposal_messages::DOCUMENT_ITEMS as usize) + .ok_or(MutationError::IdempotencyConflict)?; + if held_items.is_empty() { + return Ok(()); + } + // A held page can outlive the newest-items window. Check its exact + // items against the live thread, including items whose detail was erased. + let reader = self.proposal_actor_of(&authority.common)?; + if proposal_messages::receipt_items_match( + tx, + &document.action_id, + document.proposal_id, + held_items, + &reader, + ) + .await? + { + Ok(()) + } else { + Err(MutationError::IdempotencyConflict) + } + } + + /// Append one message under the Proposal's state row lock. The thread + /// opens at the first Submit and closes when the Proposal ends; a package + /// block leaves it open. + #[allow(clippy::too_many_arguments)] + pub(super) async fn commit_message( + &self, + tx: &Transaction<'_>, + action: &CompiledAction, + document: &ProposalDocument, + workflow: &crate::proposal_workflow::ProposalWorkflow, + authority: &ProposalAuthority, + actor: &str, + text: &str, + ) -> Result { + let thread = thread_of(action).ok_or(MutationError::PreconditionFailed)?; + if !matches!( + workflow.state(), + ProposalState::Draft | ProposalState::Submitted + ) || !proposal_messages::opened(tx, &document.action_id, document.proposal_id).await? + { + return Err(MutationError::PreconditionFailed); + } + proposal_messages::append( + tx, + NewMessage { + action_id: &document.action_id, + proposal_id: document.proposal_id, + submission_version: document.header.submission_version, + side: Side::of(authority.party), + party_role: authority.party, + sent_by: actor, + text, + maximum_count: thread.maximum_count, + }, + ) + .await + } + + /// Move the caller's side of the thread forward through `through`, under + /// the Proposal's state row lock. A move advances an open Proposal's + /// revision, so the turn and every ETag follow; it emits no event. + pub(crate) async fn record_messages_read( + &self, + tx: &Transaction<'_>, + document: &ProposalDocument, + authority: &ProposalAuthority, + through: Uuid, + ) -> Result { + let moved = proposal_messages::mark_read( + tx, + &document.action_id, + document.proposal_id, + Side::of(authority.party), + through, + ) + .await?; + if moved && matches!(document.header.state.as_str(), "draft" | "submitted") { + let workflow = + proposal_store::load(tx, &document.action_id, document.proposal_id, false).await?; + let previous = i64::try_from(workflow.workflow_revision().get()) + .map_err(|_| MutationError::Unavailable)?; + let actor = self.proposal_actor_of(&authority.common)?; + let workflow = workflow + .record_message(transition_context(&actor)?) + .map_err(workflow_error)? + .into_workflow(); + proposal_store::save( + tx, + &document.action_id, + document.proposal_id, + previous, + &workflow, + ) + .await?; + } + Ok(moved) + } + + /// The `messages` member for a caller admitted to `message` on this + /// Proposal. With `items` it carries the newest messages and the thread's + /// links; without, only the counts a list or an inbox shows. Only a person + /// acting for themselves reads the thread. + pub(crate) async fn proposal_messages_member( + &self, + tx: &Transaction<'_>, + action: &CompiledAction, + document: &ProposalDocument, + authority: &ProposalAuthority, + items: bool, + ) -> Result, MutationError> { + if thread_of(action).is_none() { + return Ok(None); + } + if !authority.receives_review_answers { + return Ok(None); + } + let side = Side::of(authority.party); + let summary = + proposal_messages::summary(tx, &document.action_id, document.proposal_id, side).await?; + let mut member = summary.to_json(); + if !items { + return Ok(Some(member)); + } + let reader = self.proposal_actor_of(&authority.common)?; + member["items"] = Value::Array( + proposal_messages::page( + tx, + &document.action_id, + document.proposal_id, + None, + proposal_messages::DOCUMENT_ITEMS, + &reader, + ) + .await? + .into_iter() + .map(|(_, item)| item) + .collect(), + ); + member["links"] = self + .proposal_message_links(tx, action, document, authority) + .await?; + Ok(Some(member)) + } + + /// The thread alone, for a caller answered without a Proposal document + /// while no review context is readable; `None` when one is. + pub(crate) async fn proposal_thread_view( + &self, + tx: &Transaction<'_>, + action: &CompiledAction, + document: &ProposalDocument, + authority: &ProposalAuthority, + ) -> Result, MutationError> { + if review_context_readable(tx, action, document).await? { + return Ok(None); + } + self.proposal_messages_member(tx, action, document, authority, true) + .await + } + + /// The thread's message, mark-read and list links for this caller, with + /// the write's condition and availability. + pub(crate) async fn proposal_message_links( + &self, + tx: &Transaction<'_>, + action: &CompiledAction, + document: &ProposalDocument, + authority: &ProposalAuthority, + ) -> Result { + let thread = thread_of(action).ok_or(MutationError::PreconditionFailed)?; + let side = Side::of(authority.party); + let refusal = match document.header.state.as_str() { + "applied" => Some(LinkRefusal::AlreadyApplied), + "rejected" => Some(LinkRefusal::ReviewRejected), + "cancelled" => Some(LinkRefusal::WrongState), + _ if !proposal_messages::opened(tx, &document.action_id, document.proposal_id) + .await? => + { + Some(LinkRefusal::WrongState) + } + _ if proposal_messages::count(tx, &document.action_id, document.proposal_id, side) + .await? + >= i64::from(thread.maximum_count) => + { + Some(LinkRefusal::LimitReached) + } + _ => None, + }; + let revision = document.header.workflow_revision as u64; + let path = format!("/v1/proposals/{}/messages", document.proposal_id); + let profile = authority.common.access_profile(); + Ok(json!({ + "message":{"method":"POST","path":path,"accessProfile":profile,"operation":"message", + "ifMatch":self.proposal_etag(document, authority)?, + "availability":ProposalAvailability::new(revision, refusal)}, + "markRead":{"method":"POST","path":format!("{path}/read"),"accessProfile":profile,"operation":"message", + "availability":ProposalAvailability::new(revision, None)}, + "list":{"method":"GET","path":path,"accessProfile":profile,"operation":"message", + "availability":ProposalAvailability::new(revision, None)}, + })) + } + + /// The `messages` member of a Proposal document, when the caller's + /// profile holds `message` on it. + pub(super) async fn public_messages( + &self, + tx: &Transaction<'_>, + registry: &CompiledRegistry, + action: &CompiledAction, + document: &ProposalDocument, + claims: &crate::api::VerifiedRequestClaims, + current: &ProposalAuthority, + ) -> Result, MutationError> { + let Some(authority) = self + .public_message_authority(tx, registry, action, document, claims, current) + .await? + else { + return Ok(None); + }; + let items = + current.operation != ProposalAuthorityOperation::Lifecycle(ProposalOperation::List); + let value = self + .proposal_messages_member(tx, action, document, &authority, items) + .await?; + Ok(value.map(|value| (value, Side::of(authority.party)))) + } + + async fn public_message_authority( + &self, + tx: &Transaction<'_>, + registry: &CompiledRegistry, + action: &CompiledAction, + document: &ProposalDocument, + claims: &crate::api::VerifiedRequestClaims, + current: &ProposalAuthority, + ) -> Result, MutationError> { + if thread_of(action).is_none() { + return Ok(None); + } + let Some(authority) = crate::api::proposals::authorize( + registry, + action, + claims, + Some(current.common.access_profile()), + ProposalAuthorityOperation::Lifecycle(ProposalOperation::Message), + Some(document.proposal_id), + self.party_selection(document, current), + ) else { + return Ok(None); + }; + if !link_readable( + self.check_proposal_document(tx, registry, document, &authority, false) + .await, + )? { + return Ok(None); + } + Ok(Some(authority)) + } +} + +fn check_receipt_side(original: Option, current: Side) -> Result<(), MutationError> { + if original == Some(current) { + Ok(()) + } else { + Err(MutationError::IdempotencyConflict) + } +} + +pub(super) fn hold_proposal_response( + status: u16, + mut value: Value, + headers: BTreeMap>, + thread_side: Option, +) -> Result<(HeldResponse, ProposalReadDisclosure), MutationError> { + if let Some(path) = receipt_thread_items_path(&value) { + if thread_side.is_none() || !value.pointer(path).is_some_and(Value::is_array) { + return Err(MutationError::Unavailable); + } + } else if thread_side.is_some() { + return Err(MutationError::Unavailable); + } + let receipt = if message_receipt_shape(&value) == Some(MessageReceiptShape::Review) { + if let Some(full) = HeldResponse::from_json_if_fits(status, &value, headers.clone())? { + full + } else { + // A reviewer can fetch the review context independently. The + // write's existing thread-only outcome fits the receipt limit. + value = value + .pointer_mut("/context/messages") + .filter(|thread| message_receipt_shape(thread) == Some(MessageReceiptShape::Thread)) + .ok_or(MutationError::Unavailable)? + .take(); + HeldResponse::from_json(status, &value, headers)? + } + } else { + HeldResponse::from_json(status, &value, headers)? + }; + Ok((receipt, ProposalReadDisclosure::for_value(&value))) +} + +/// The thread an Action declares, if any. +pub(crate) fn thread_of(action: &CompiledAction) -> Option { + match &action.execution { + CompiledActionExecution::Proposal { proposal } => proposal.messages, + CompiledActionExecution::Immediate => None, + } +} + +/// Whether a review context can be read for this Proposal now: it has a +/// frozen submission, and the Action has not changed since it was written. +pub(crate) async fn review_context_readable( + tx: &Transaction<'_>, + action: &CompiledAction, + document: &ProposalDocument, +) -> Result { + if action.definition_revision != document.action_revision { + return Ok(false); + } + let workflow = + proposal_store::load(tx, &document.action_id, document.proposal_id, false).await?; + Ok(workflow.current_proposal().is_some()) +} + +#[derive(Clone, Copy, Eq, PartialEq)] +enum MessageReceiptShape { + Proposal, + Review, + Thread, +} + +fn receipt_thread_items_path(value: &Value) -> Option<&'static str> { + if value.get("messages").is_some() { + Some("/messages/items") + } else if value.pointer("/context/messages").is_some() { + Some("/context/messages/items") + } else if message_receipt_shape(value) == Some(MessageReceiptShape::Thread) { + Some("/items") + } else { + None + } +} + +fn message_receipt_shape(value: &Value) -> Option { + if let Some(context) = value.get("context") { + context.is_object().then_some(MessageReceiptShape::Review) + } else if value.get("id").is_some() && value.get("state").is_some() { + Some(MessageReceiptShape::Proposal) + } else if value.get("count").and_then(Value::as_u64).is_some() + && value.get("items").is_some_and(Value::is_array) + { + Some(MessageReceiptShape::Thread) + } else { + None + } +} + +fn message_receipt_projection_allows( + held: &Value, + current: &Value, + context_fields: Option<&BTreeMap>, +) -> bool { + let Some(shape) = message_receipt_shape(held) else { + return false; + }; + if message_receipt_shape(current) != Some(shape) { + return false; + } + match shape { + MessageReceiptShape::Review => { + // The context contract includes each mapped form's compiled + // digest. The review envelope binds the frozen submission and + // the live fields have already checked current disclosure. + held.as_object().is_some_and(|held| { + held.iter().all(|(name, value)| match name.as_str() { + "revision" | "reviewable" => true, + "context" => value.as_object().is_some_and(|context| { + context.iter().all(|(name, value)| { + let live = ¤t["context"][name]; + match name.as_str() { + "messages" => live.is_object(), + "additionalForms" => projection_contains(value, live), + "fields" => context_fields.is_some_and(|sources| { + review_fields_visible(value, live, sources) + }), + _ => current["context"] + .get(name) + .is_some_and(|live| held_json_matches(value, live)), + } + }) + }), + _ => current + .get(name) + .is_some_and(|live| held_json_matches(value, live)), + }) + }) + } + MessageReceiptShape::Proposal => held.as_object().is_some_and(|held| { + held.iter().all(|(name, value)| match name.as_str() { + // Lifecycle observations and link conditions are part of + // the original response. Using any link requires fresh admission. + "actionRevision" | "submissionVersion" | "revision" | "state" | "effectDigest" + | "applicationStatus" | "blockedReason" | "status" | "turn" | "links" => true, + "messages" => current[name].is_object(), + "asks" => current.get(name).is_some_and(|live| { + public_asks_visible(value, live) + && held + .get("submissionVersion") + .zip(current.get("submissionVersion")) + .is_some_and(|(version, live)| held_json_matches(version, live)) + }), + "additionalForms" | "attachments" | "additions" => current + .get(name) + .is_some_and(|live| public_member_contains(name, value, live)), + _ => current + .get(name) + .is_some_and(|live| held_json_matches(value, live)), + }) + }), + // The current Message grant covers the whole thread. The caller + // checks the items independently of the current page and counters. + MessageReceiptShape::Thread => true, + } +} + +fn public_asks_visible(held: &Value, current: &Value) -> bool { + let (Some(held), Some(current)) = (held.as_array(), current.as_array()) else { + return false; + }; + held.iter().all(|ask| { + let Some(id) = ask.get("id").and_then(Value::as_str) else { + return false; + }; + let mut matches = current + .iter() + .filter(|live| live.get("id").and_then(Value::as_str) == Some(id)); + let Some(live) = matches.next() else { + return false; + }; + matches.next().is_none() + && ask.as_object().is_some_and(|fields| { + fields.iter().all(|(name, value)| { + matches!(name.as_str(), "state" | "links") + || live + .get(name) + .is_some_and(|live| held_json_matches(value, live)) + }) + }) + }) +} + +fn public_member_contains(name: &str, held: &Value, current: &Value) -> bool { + let mut held = held.clone(); + let mut current = current.clone(); + for member in [&mut held, &mut current] { + if let Some(descriptors) = member.as_object_mut() { + for descriptor in descriptors.values_mut() { + match name { + "attachments" => { + remove_file_observations(descriptor); + if let Some(value) = descriptor.get_mut("value") { + remove_file_observations(value); + } + } + "additions" => { + remove_file_observations(descriptor); + if let Some(items) = + descriptor.get_mut("items").and_then(Value::as_array_mut) + { + for item in items { + remove_file_observations(item); + } + } + } + _ => remove_link_conditions(descriptor), + } + } + } + } + projection_contains(&held, ¤t) +} + +fn remove_file_observations(descriptor: &mut Value) { + // Metadata must still be visible. A held verification observation or + // promoted link grants no access to the file when used later. + if let Some(descriptor) = descriptor.as_object_mut() { + descriptor.remove("verificationStatus"); + descriptor.remove("links"); + } +} + +fn remove_link_conditions(descriptor: &mut Value) { + // Visit only API link containers. Authored input can also use these keys. + if let Some(links) = descriptor.get_mut("links").and_then(Value::as_object_mut) { + for link in links.values_mut().filter_map(Value::as_object_mut) { + link.remove("ifMatch"); + link.remove("availability"); + } + } +} + +fn review_fields_visible( + held: &Value, + current: &Value, + sources: &BTreeMap, +) -> bool { + held.as_object().is_some_and(|fields| { + fields.iter().all(|(name, value)| { + let Some(live) = current.get(name) else { + return false; + }; + match sources.get(name) { + Some( + ProposalContextValueSource::AdditionalForm { .. } + | ProposalContextValueSource::Additions { .. }, + ) => projection_contains(value, live), + Some(_) => held_json_matches(value, live), + None => false, + } + }) + }) +} + +fn projection_contains(held: &Value, current: &Value) -> bool { + match (held, current) { + (Value::Object(held), Value::Object(current)) => held.iter().all(|(key, value)| { + current + .get(key) + .is_some_and(|live| projection_contains(value, live)) + }), + (Value::Array(held), Value::Array(current)) => { + // A response can contain rows to which the live projection has + // since appended. Every retained row must still appear in full. + let mut current = current.iter(); + held.iter() + .all(|entry| current.any(|live| held_json_matches(entry, live))) + } + _ => held_json_matches(held, current), + } +} + +fn held_json_matches(held: &Value, current: &Value) -> bool { + match (held, current) { + (Value::Object(held), Value::Object(current)) => { + held.len() == current.len() + && held.iter().all(|(name, value)| { + current + .get(name) + .is_some_and(|live| held_json_matches(value, live)) + }) + } + (Value::Array(held), Value::Array(current)) => { + held.len() == current.len() + && held + .iter() + .zip(current) + .all(|(value, live)| held_json_matches(value, live)) + } + (Value::Number(_), Value::Number(_)) => { + // HeldResponse stores canonical JSON. Compare numbers in the same + // representation as the parsed receipt, including integral floats. + canonicalize_json(current) + .ok() + .and_then(|bytes| serde_json::from_slice::(&bytes).ok()) + .is_some_and(|normalized| normalized == *held) + } + _ => held == current, + } +} + +#[cfg(test)] +mod receipt_tests { + use super::*; + + #[test] + fn message_receipt_requires_the_retained_review_projection() { + let sources = BTreeMap::from([ + ( + "record".to_owned(), + ProposalContextValueSource::Record { + input: "record".to_owned(), + field: "name".to_owned(), + }, + ), + ( + "form".to_owned(), + ProposalContextValueSource::AdditionalForm { + form: "example".to_owned(), + }, + ), + ]); + let held = json!({ + "id":"proposal", "actionId":"review", "actionRevision":"a1", + "submissionVersion":1, "effectDigest":"effect-1", "revision":4, + "reviewable":true, "subject":{"id":"proposal","version":"1"}, + "context":{ + "reference":"round-1", "contract":{"schemaDigest":"contract-1"}, + "fields":{"record":"visible", "form":[{"id":"entry", "input":{"value":7}}]}, + "messages":{"count":1,"unread":1,"items":[]} + } + }); + let mut current = held.clone(); + current["revision"] = json!(5); + current["reviewable"] = json!(false); + current["context"]["messages"]["unread"] = json!(0); + current["context"]["fields"]["form"] + .as_array_mut() + .unwrap() + .push(json!({"id":"next-entry","input":{"value":8}})); + assert!(message_receipt_projection_allows( + &held, + ¤t, + Some(&sources) + )); + + assert!(!message_receipt_projection_allows( + &held, + &json!({"count":1,"unread":0,"items":[]}), + Some(&sources), + )); + for path in [ + "/submissionVersion", + "/subject/version", + "/effectDigest", + "/context/fields/form", + "/context/fields/record", + "/context/messages", + ] { + let mut narrower = current.clone(); + *narrower.pointer_mut(path).unwrap() = Value::Null; + assert!( + !message_receipt_projection_allows(&held, &narrower, Some(&sources)), + "{path}" + ); + } + let mut successor = current.clone(); + successor["context"]["contract"]["schemaDigest"] = json!("contract-2"); + assert!(!message_receipt_projection_allows( + &held, + &successor, + Some(&sources) + )); + current["context"]["fields"]["form"] = json!([]); + assert!(!message_receipt_projection_allows( + &held, + ¤t, + Some(&sources) + )); + } + + #[test] + fn message_receipt_rechecks_the_proposal_disclosure_and_keeps_thread_observations() { + let held = json!({ + "id": "proposal", + "state": "submitted", + "revision": 4, + "input": {"value": 7}, + "messages": {"count": 1, "unread": 1, "items": []} + }); + let mut current = held.clone(); + current["revision"] = json!(5); + current["messages"]["unread"] = json!(0); + assert!(message_receipt_projection_allows(&held, ¤t, None)); + current.as_object_mut().unwrap().remove("input"); + assert!(!message_receipt_projection_allows(&held, ¤t, None)); + assert!(message_receipt_projection_allows( + &held["messages"], + ¤t["messages"], + None, + )); + } + + #[test] + fn message_receipt_accepts_new_link_conditions_with_the_same_projection() { + let link = |condition, revision| { + json!({ + "method": "POST", "operation": "add", "path": "/forms/example", + "accessProfile": "owner", "ifMatch": condition, + "availability": ProposalAvailability::new(revision, None) + }) + }; + let held = json!({ + "id": "proposal", + "state": "submitted", + "additionalForms": { + "example": { + "items": [{"id": "entry", "input": {"links": {"ifMatch": "data"}}}], + "links": {"add": link("old", 4)}, + } + }, + "messages": {"items": []} + }); + let mut current = held.clone(); + current["additionalForms"]["example"]["links"]["add"] = link("current", 5); + assert!(message_receipt_projection_allows(&held, ¤t, None)); + + let mut changed_path = current.clone(); + changed_path["additionalForms"]["example"]["links"]["add"]["path"] = json!("/forms/other"); + assert!(!message_receipt_projection_allows( + &held, + &changed_path, + None + )); + current["additionalForms"]["example"]["items"][0]["input"]["links"]["ifMatch"] = + json!("different data"); + assert!(!message_receipt_projection_allows(&held, ¤t, None)); + } + + #[test] + fn message_replay_requires_proof_of_the_original_thread_side() { + for side in [Side::Party, Side::Official] { + assert!(check_receipt_side(Some(side), side).is_ok()); + assert!(check_receipt_side(None, side).is_err()); + } + assert!(check_receipt_side(Some(Side::Official), Side::Party).is_err()); + assert!(check_receipt_side(Some(Side::Party), Side::Official).is_err()); + + let thread = json!({"count": 0, "unread": 0, "items": []}); + for value in [ + json!({"id": "proposal", "state": "draft", "messages": thread}), + json!({"context": {"messages": thread}}), + thread, + ] { + assert!(hold_proposal_response(200, value.clone(), BTreeMap::new(), None).is_err()); + assert!(hold_proposal_response(200, value, BTreeMap::new(), Some(Side::Party)).is_ok()); + } + } + + #[test] + fn message_receipt_matches_ask_identity_and_retained_values_through_answer_progress() { + let question = json!({ + "id": "ask-one", "text": "Explain the date", "wants": ["answer"], + "askedAt": "2026-01-05T00:00:00Z", "state": "open", "links": {} + }); + let mut held = json!({ + "id": "proposal", "state": "submitted", "submissionVersion": 1, + "asks": [question], "messages": {"items": []} + }); + let mut current = held.clone(); + let questions = current["asks"].as_array_mut().unwrap(); + questions[0]["state"] = json!("answered"); + questions[0]["answer"] = json!({"text": "Observed date", "additions": ["file-one"], + "formEntries": ["entry-one"], "answeredAt": "2026-01-05T00:01:00Z"}); + questions[0].as_object_mut().unwrap().remove("links"); + questions.insert(0, json!({"id": "ask-two", "text": "Confirm the address"})); + assert!(message_receipt_projection_allows(&held, ¤t, None)); + + let mut next_submission = current.clone(); + next_submission["submissionVersion"] = json!(2); + assert!(!message_receipt_projection_allows( + &held, + &next_submission, + None + )); + + let mut duplicate = current.clone(); + duplicate["asks"] + .as_array_mut() + .unwrap() + .push(current["asks"][1].clone()); + assert!(!message_receipt_projection_allows(&held, &duplicate, None)); + + held["asks"][0]["answer"] = current["asks"][1]["answer"].clone(); + assert!(message_receipt_projection_allows(&held, ¤t, None)); + for (path, replacement) in [ + ("/asks/1/id", json!("ask-three")), + ("/asks/1/text", json!("Explain the time")), + ("/asks/1/wants", json!(["document"])), + ("/asks/1/answer/text", json!("Different date")), + ("/asks/1/answer/additions", json!(["file-two"])), + ("/asks/1/answer/formEntries", json!(["entry-two"])), + ("/asks", json!([])), + ] { + let mut narrower = current.clone(); + *narrower.pointer_mut(path).unwrap() = replacement; + assert!( + !message_receipt_projection_allows(&held, &narrower, None), + "{path}" + ); + } + } + + #[test] + fn message_receipt_retains_file_observations_only_while_metadata_is_visible() { + let held = json!({ + "id": "proposal", "state": "submitted", + "attachments": {"proof": {"id": "proof", "value": { + "submissionVersion": 1, "sha256": "digest", "verificationStatus": "pending" + }, "links": {"upload": {"method": "PATCH"}}}}, + "additions": {"support": {"id": "support", "items": [{ + "id": "file-one", "submissionVersion": 1, "sha256": "another-digest", + "verificationStatus": "pending", "links": {} + }], "links": {}}}, + "messages": {"items": []} + }); + let mut current = held.clone(); + current["attachments"]["proof"]["value"]["verificationStatus"] = json!("verified"); + current["attachments"]["proof"]["links"] = json!({"download": {"method": "GET"}}); + current["additions"]["support"]["items"][0]["verificationStatus"] = json!("verified"); + current["additions"]["support"]["items"][0]["links"] = + json!({"download": {"method": "GET"}}); + assert!(message_receipt_projection_allows(&held, ¤t, None)); + + let mut erased = current.clone(); + erased["attachments"]["proof"] + .as_object_mut() + .unwrap() + .remove("value"); + assert!(!message_receipt_projection_allows(&held, &erased, None)); + let mut replaced = current.clone(); + replaced["additions"]["support"]["items"][0]["sha256"] = json!("replacement-digest"); + assert!(!message_receipt_projection_allows(&held, &replaced, None)); + current["additions"]["support"]["items"] = json!([]); + assert!(!message_receipt_projection_allows(&held, ¤t, None)); + } + + #[test] + fn reviewer_message_receipt_bounds_the_complete_canonical_envelope() { + let thread = json!({"count": 1, "unread": 0, "items": [], "links": {}}); + let mut review = json!({"context": { + "fields": {"summary": "Résumé", "note": "\\n"}, + "messages": thread, + }}); + let framing = canonicalize_json(&review).unwrap().len(); + let remaining = crate::idempotency::MAX_HELD_BODY_BYTES - framing; + review["context"]["fields"]["note"] = json!(format!("\\n{}", "a".repeat(remaining))); + let (held, _) = + hold_proposal_response(200, review.clone(), BTreeMap::new(), Some(Side::Official)) + .unwrap(); + assert_eq!(held.body().len(), crate::idempotency::MAX_HELD_BODY_BYTES); + assert_eq!(held.body(), canonicalize_json(&review).unwrap()); + + review["context"]["fields"]["note"] = json!(format!("\\n{}", "a".repeat(remaining + 1))); + let (held, _) = + hold_proposal_response(200, review, BTreeMap::new(), Some(Side::Official)).unwrap(); + assert_eq!(held.body(), canonicalize_json(&thread).unwrap()); + } + + #[test] + fn message_receipt_compares_numbers_as_they_appear_in_held_json() { + let current = json!({ + "id": "proposal", "state": "submitted", + "input": {"value": 7.0}, "messages": {"items": []} + }); + let held = HeldResponse::from_json(200, ¤t, BTreeMap::new()).unwrap(); + let held: Value = serde_json::from_slice(held.body()).unwrap(); + assert!(held["input"]["value"].is_u64()); + assert!(message_receipt_projection_allows(&held, ¤t, None)); + + let mut changed = current; + changed["input"]["value"] = json!(7.5); + assert!(!message_receipt_projection_allows(&held, &changed, None)); + } +} diff --git a/crates/registry-breg/src/mutation/reference_reach.rs b/crates/registry-breg/src/mutation/reference_reach.rs new file mode 100644 index 0000000000..63bed4aacc --- /dev/null +++ b/crates/registry-breg/src/mutation/reference_reach.rs @@ -0,0 +1,103 @@ +// SPDX-License-Identifier: Apache-2.0 + +//! A direct write that sets a reference field must name a record the caller +//! can read now, as an Action's reference targets must. The check reads the +//! referenced row under the caller's own row security for that Record type, +//! inside the write transaction. A record the caller cannot read answers as a +//! missing one does. + +use super::*; +use crate::contract::FieldTypeSource; +use crate::generated_ddl::REFERENCE_PROBE_ENTITY_SETTING; + +/// The references a body sets: every non-null reference value of a create, +/// and each reference a patch adds or replaces. Unchanged stored references +/// are not rechecked. +pub(super) fn set_references( + entity: &CompiledEntity, + body: &MutationBody, +) -> Result, MutationError> { + let target = |field: &str| match entity.fields.get(field).map(|field| &field.field_type) { + Some(FieldTypeSource::Reference { target, .. }) => Some(target.clone()), + _ => None, + }; + let key = |value: &Value| value.as_str().and_then(|value| Uuid::parse_str(value).ok()); + let mut references = Vec::new(); + match body { + MutationBody::Create(data) => { + for (field, value) in data { + if let (Some(target), Some(id)) = (target(field), key(value)) { + references.push((target, id)); + } + } + } + MutationBody::Patch(operations) => { + for operation in operations { + if let PatchOperation::Add { path, value } + | PatchOperation::Replace { path, value } = operation + { + if let (Some(target), Some(id)) = (target(&patch_field(path)?), key(value)) { + references.push((target, id)); + } + } + } + } + MutationBody::Tombstone => {} + } + Ok(references) +} + +/// Refuse a write naming a record the caller cannot read now. The answer is +/// the one a missing or tombstoned record gets from the reference's foreign +/// key, so the three cannot be told apart. Deduplicate within this item only. +/// Later items must check against the transaction state at their own write. +pub(super) async fn require_readable_references( + transaction: &Transaction<'_>, + plan: &MutationPlan, + claims: &ClaimContext, + references: &[(String, Uuid)], +) -> Result<(), MutationError> { + let mut by_target = BTreeMap::<&str, BTreeSet>::new(); + for (target, id) in references { + by_target.entry(target).or_default().insert(*id); + } + for (target, ids) in by_target { + let table = plan + .reference_tables + .get(target) + .ok_or(MutationError::Unavailable)?; + let Some(boundaries) = claims.reference_row_boundaries(target) else { + return Err(MutationError::Conflict); + }; + let install_context = format!( + "SELECT set_config('registry.row_boundaries', $1, true), + set_config('{REFERENCE_PROBE_ENTITY_SETTING}', $2, true)" + ); + transaction + .execute(&install_context, &[&boundaries, &target]) + .await + .map_err(map_database_error)?; + let ids = ids.into_iter().collect::>(); + let readable = transaction + .query_one( + &format!( + "SELECT count(*) FROM registry_data.{} WHERE record_id = ANY($1)", + quote_identifier(table) + ), + &[&ids], + ) + .await + .map_err(map_database_error)?; + // Close the probe and restore the written Record type's boundaries + // before any further work. A SQL failure aborts the transaction. + transaction + .execute(&install_context, &[&claims.canonical_row_boundaries(), &""]) + .await + .map_err(map_database_error)?; + let readable = readable.try_get::<_, i64>(0).map_err(map_database_error)?; + if usize::try_from(readable).ok() != Some(ids.len()) { + return Err(MutationError::Conflict); + } + } + Ok(()) +} diff --git a/crates/registry-breg/src/odrl_export.rs b/crates/registry-breg/src/odrl_export.rs index cd537817bd..3ab54752e8 100644 --- a/crates/registry-breg/src/odrl_export.rs +++ b/crates/registry-breg/src/odrl_export.rs @@ -389,6 +389,7 @@ fn operation_name(operation: Operation) -> &'static str { Operation::Invoke => "invoke", Operation::Start => "start", Operation::Import => "import", + Operation::Reference => "reference", } } diff --git a/crates/registry-breg/src/package.rs b/crates/registry-breg/src/package.rs index 3de0ad7e37..036b5c9d75 100644 --- a/crates/registry-breg/src/package.rs +++ b/crates/registry-breg/src/package.rs @@ -19,8 +19,10 @@ use std::io::{Read, Write}; use std::path::{Component, Path, PathBuf}; use registry_platform_canonical_json::{canonicalize_json, parse_json_strict}; +#[cfg(all(test, feature = "tooling"))] +use registry_platform_config::package::write_sum_file; use registry_platform_config::package::{ - plan_package, write_sum_file, PackageLimits as SharedPackageLimits, + plan_package, write_sum_file_with_mode, PackageLimits as SharedPackageLimits, VerifiedPackage as SharedVerifiedPackage, REVISION_FILE, SUM_FILE, }; use serde::{Deserialize, Serialize}; @@ -29,10 +31,14 @@ use sha2::{Digest, Sha256}; use thiserror::Error; use crate::artifacts::REGISTRY_METADATA_ARTIFACT_PATH; +#[cfg(feature = "tooling")] +use crate::compiler::module_source_digest; use crate::compiler::{compile_project_with_assets, CompileProfile}; use crate::contract::{ - parse_module_yaml, parse_project_yaml, parse_sealed_module_yaml, parse_sealed_project_yaml, - FieldTypeSource, ModuleAssetSource, RegistryModule, RegistryProject, + parse_module_yaml, parse_predecessor_module_yaml, parse_predecessor_project_yaml, + parse_project_yaml, parse_sealed_module_yaml, parse_sealed_project_yaml, FieldTypeSource, + MembershipBoundarySource, ModuleAssetSource, PredecessorMemberships, RegistryModule, + RegistryProject, }; use crate::derived_sql::MAX_DERIVED_SQL_BYTES; use crate::generated_ddl::{ @@ -795,7 +801,7 @@ pub enum PackageError { Binding, #[error("the package compiler derivation failed")] Derivation, - #[error("the sealed sources use historical Action Plan spelling or the generated artifacts differ from this release's compiler output")] + #[error("the sealed sources use historical Action Plan or Proposal grant spelling, or the generated artifacts differ from this release's compiler output")] GeneratedArtifactsMismatch, /// A package whose generated files name a Record type `entityId`, as /// releases up to v0.41.0 wrote them. @@ -964,12 +970,32 @@ impl PreparedPackage { } /// Publish inside the shared Registry Stack package envelope, optionally - /// with a `REVISION` file. A package carries no environment, so every - /// directory and file is written owner-only. + /// with a `REVISION` file. The deployment package is readable by a + /// separate runtime user. pub fn publish_to_directory_with_revision( &self, destination: &Path, revision: Option<&str>, + ) -> Result { + self.publish(destination, revision, 0o755, 0o644) + } + + /// Publish a local package with owner-only Unix permissions. Package + /// bytes and digest are independent of the permissions used to write it. + pub fn publish_private_to_directory_with_revision( + &self, + destination: &Path, + revision: Option<&str>, + ) -> Result { + self.publish(destination, revision, 0o700, 0o600) + } + + fn publish( + &self, + destination: &Path, + revision: Option<&str>, + directory_mode: u32, + file_mode: u32, ) -> Result { let manifest_bytes = self.manifest_bytes()?; reject_symlink_components(destination)?; @@ -981,30 +1007,46 @@ impl PreparedPackage { if !parent.is_dir() { return Err(PackageError::UnsafePath); } - fs::create_dir(destination).map_err(|_| PackageError::Closure)?; - set_safe_directory_permissions(destination)?; + let directories = &mut fs::DirBuilder::new(); + #[cfg(unix)] + { + use std::os::unix::fs::DirBuilderExt as _; + + directories.mode(0o700); + } + directories + .create(destination) + .map_err(|_| PackageError::Closure)?; let publish = (|| { + // Keep the root private until even a package for a separate + // runtime user has a complete, verified envelope. + set_directory_permissions(destination, 0o700)?; + let mut created_directories = BTreeSet::new(); for (path, bytes) in &self.files { let relative = Path::new(path); - let full = destination.join(relative); - if let Some(parent) = full.parent() { - fs::create_dir_all(parent).map_err(|_| PackageError::Closure)?; - set_safe_directory_permissions(parent)?; + let parent = relative.parent().ok_or(PackageError::UnsafePath)?; + let mut directory = destination.to_path_buf(); + for component in parent.components() { + directory.push(component.as_os_str()); + if created_directories.insert(directory.clone()) { + directories + .create(&directory) + .map_err(|_| PackageError::Closure)?; + set_directory_permissions(&directory, directory_mode)?; + } } - write_new_file(&full, bytes)?; + write_new_file(&destination.join(relative), bytes, file_mode)?; } - write_new_file(&destination.join(MANIFEST_PATH), &manifest_bytes)?; - let package = write_sum_file( + write_new_file(&destination.join(MANIFEST_PATH), &manifest_bytes, file_mode)?; + let package = write_sum_file_with_mode( destination, revision, &shared_package_limits(), "bregctl package", + file_mode, ) .map_err(|_| PackageError::Closure)?; - set_safe_file_permissions(&destination.join(SUM_FILE))?; - if revision.is_some() { - set_safe_file_permissions(&destination.join(REVISION_FILE))?; - } + set_directory_permissions(destination, directory_mode)?; Ok(package) })(); if publish.is_err() { @@ -2349,7 +2391,9 @@ fn additive_migration_plan( .map(|statement| (statement.id.as_str(), statement)) .collect::>(); for (id, statement) in &candidate_probe_functions { - if previous_probe_functions.get(id) != Some(statement) { + if previous_probe_functions.get(id) != Some(statement) + || (refresh_compiler_owned_ddl && id.starts_with("registry_context.membership_")) + { new_statement_ids.insert((*id).to_owned()); if previous_probe_functions.contains_key(id) { replacement_statement_ids.insert((*id).to_owned()); @@ -2769,6 +2813,26 @@ fn additive_migration_plan( new_statement_ids.insert(id.clone()); } } + let previous_index = crate::membership::index_statement(previous_entity); + let candidate_index = crate::membership::index_statement(candidate_entity); + // A baseline compiled without the index still projects it when + // regenerated here. Refresh it on compiler drift even if the model + // declares the same membership columns. + if refresh_compiler_owned_ddl || previous_index != candidate_index { + if let Some((id, name, _)) = previous_index { + removed_dependency_statements.push(DdlStatement { + id: format!("{id}.drop"), + kind: DdlStatementKind::Index, + sql: format!( + "DROP INDEX IF EXISTS registry_data.{}", + quote_identifier(&name) + ), + }); + } + if let Some((id, _, _)) = candidate_index { + new_statement_ids.insert(id); + } + } } let mut statements = removed_dependency_statements; @@ -4082,41 +4146,42 @@ fn validate_build_bindings( Ok(()) } -fn write_new_file(path: &Path, bytes: &[u8]) -> Result<()> { +fn write_new_file( + path: &Path, + bytes: &[u8], + #[cfg_attr(not(unix), allow(unused_variables))] mode: u32, +) -> Result<()> { reject_symlink_components(path)?; - let mut file = OpenOptions::new() - .write(true) - .create_new(true) - .open(path) - .map_err(|_| PackageError::Closure)?; - file.write_all(bytes).map_err(|_| PackageError::Read)?; - file.sync_all().map_err(|_| PackageError::Read)?; - set_safe_file_permissions(path) -} - -#[cfg(unix)] -fn set_safe_directory_permissions(path: &Path) -> Result<()> { - use std::os::unix::fs::PermissionsExt; + let mut options = OpenOptions::new(); + options.write(true).create_new(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt as _; - fs::set_permissions(path, fs::Permissions::from_mode(0o755)) - .map_err(|_| PackageError::Permissions) -} + options.mode(0o600); + } + let mut file = options.open(path).map_err(|_| PackageError::Closure)?; + file.write_all(bytes).map_err(|_| PackageError::Read)?; + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt as _; -#[cfg(not(unix))] -fn set_safe_directory_permissions(_path: &Path) -> Result<()> { - Ok(()) + file.set_permissions(fs::Permissions::from_mode(mode)) + .map_err(|_| PackageError::Permissions)?; + } + file.sync_all().map_err(|_| PackageError::Read) } #[cfg(unix)] -fn set_safe_file_permissions(path: &Path) -> Result<()> { +fn set_directory_permissions(path: &Path, mode: u32) -> Result<()> { use std::os::unix::fs::PermissionsExt; - fs::set_permissions(path, fs::Permissions::from_mode(0o644)) + fs::set_permissions(path, fs::Permissions::from_mode(mode)) .map_err(|_| PackageError::Permissions) } #[cfg(not(unix))] -fn set_safe_file_permissions(_path: &Path) -> Result<()> { +fn set_directory_permissions(_path: &Path, _mode: u32) -> Result<()> { Ok(()) } @@ -4328,11 +4393,10 @@ pub fn load_predecessor_package_with_verified_envelope( } /// Verify a predecessor package exactly as [`load_predecessor_package`] does, -/// then compile its packaged sources with the current compiler so a successor -/// can be rehearsed over the predecessor's schema. The historical generated -/// artifacts are still not compared: the rehearsal instead holds the installed -/// schema to the packaged predecessor fingerprint, and refuses when the -/// current compiler cannot reproduce it. +/// then prepare its schema for successor rehearsal. Historical membership +/// packages use the archived governed model and inventories. The rehearsal +/// compares the installed baseline fingerprint with the archived fingerprint +/// and requires the final catalog to match the candidate fingerprint. #[cfg(feature = "tooling")] pub fn load_predecessor_rehearsal_baseline( root: &Path, @@ -4349,8 +4413,8 @@ pub fn load_predecessor_rehearsal_baseline_with_verified_envelope( shared: &SharedVerifiedPackage, ) -> Result<(VerifiedPredecessorPackage, CompiledRegistry)> { let (package, loaded) = load_predecessor_closure(root, context, shared)?; - let (registry, _) = - compile_package_sources(&package.manifest, &loaded, PackageSourceMode::Predecessor)?; + let registry = + project_rehearsal_baseline(&package.manifest, &loaded, package.migration_baseline())?; Ok((package, registry)) } @@ -4363,7 +4427,7 @@ fn load_predecessor_closure( let (manifest, loaded) = load_verified_closure(root, shared, production)?; validate_engine_features(&manifest)?; validate_source_inventory(&manifest)?; - parse_package_sources(&manifest, &loaded, PackageSourceMode::Predecessor)?; + let sources = parse_package_sources(&manifest, &loaded, PackageSourceMode::Predecessor)?; let governed = package_predecessor_governed_model(&manifest, &loaded)?; validate_predecessor_registry_bindings(&manifest, &governed)?; let package_digest = shared.digest().to_owned(); @@ -4381,6 +4445,9 @@ fn load_predecessor_closure( generated_ddl_sha256, ); validate_migration_baseline(&migration_baseline)?; + if sources.has_historical_membership() { + validate_predecessor_membership_inventory(&sources, &migration_baseline)?; + } let history_schema_descriptor = governed.history_schema_descriptor(&package_digest)?; Ok(( @@ -4847,16 +4914,19 @@ fn load_closure( /// The refusal for stored sources that do not parse. A package closure holds /// sources an earlier release may have written, so the refusal carries the /// reader's diagnostics for the operator to act on. No release seals a file -/// that mixes or doubles the Action Plan spellings, so such a file is a -/// modified package rather than an earlier release's sources. +/// that mixes Action Plan or membership spellings on a grant or doubles an +/// Action Plan, Proposal grant or membership key. fn source_refusal(failure: &CompileFailure) -> PackageError { const SHOWN: usize = 3; let diagnostics = failure.diagnostics(); if diagnostics.iter().any(|diagnostic| { diagnostic.code == "breg.action-plan.mixed-spelling" + || diagnostic.code == "breg.membership.mixed-spelling" || (diagnostic.code == "yaml.duplicate-key" && (diagnostic.path.ends_with(".functions") - || diagnostic.path.ends_with(".function"))) + || diagnostic.path.ends_with(".function") + || diagnostic.path.ends_with(".ownership") + || diagnostic.path.ends_with(".membershipBoundaries"))) }) { return PackageError::Integrity; } @@ -4886,20 +4956,51 @@ impl PackageSourceMode { } Ok(source) } + + fn project(self, bytes: &[u8]) -> Result<(RegistryProject, PredecessorMemberships)> { + match self { + Self::Strict => Ok(( + self.accept(parse_sealed_project_yaml(bytes))?, + PredecessorMemberships::default(), + )), + Self::Predecessor => { + parse_predecessor_project_yaml(bytes).map_err(|failure| source_refusal(&failure)) + } + } + } + + fn module(self, bytes: &[u8]) -> Result<(RegistryModule, PredecessorMemberships)> { + match self { + Self::Strict => Ok(( + self.accept(parse_sealed_module_yaml(bytes))?, + PredecessorMemberships::default(), + )), + Self::Predecessor => { + parse_predecessor_module_yaml(bytes).map_err(|failure| source_refusal(&failure)) + } + } + } +} + +struct ParsedPackageSources { + project: RegistryProject, + modules: Vec, + project_memberships: PredecessorMemberships, + module_memberships: Vec, } /// Parse verified source bytes. Only predecessor planning and rehearsal can -/// use translated historical Action Plan keys. +/// use translated historical Action Plan, Proposal grant or membership keys. fn parse_package_sources( manifest: &PackageManifest, loaded: &BTreeMap>, mode: PackageSourceMode, -) -> Result<(RegistryProject, Vec)> { +) -> Result { let project_bytes = loaded .get(&manifest.sources.project) .ok_or(PackageError::Derivation)?; - let project = mode.accept(parse_sealed_project_yaml(project_bytes))?; - let modules = manifest + let (project, project_memberships) = mode.project(project_bytes)?; + let (modules, module_memberships) = manifest .sources .modules .iter() @@ -4907,19 +5008,420 @@ fn parse_package_sources( loaded .get(&source.path) .ok_or(PackageError::Derivation) - .and_then(|bytes| mode.accept(parse_sealed_module_yaml(bytes))) + .and_then(|bytes| mode.module(bytes)) }) - .collect::>>()?; - Ok((project, modules)) + .collect::>>()? + .into_iter() + .unzip(); + let sources = ParsedPackageSources { + project, + modules, + project_memberships, + module_memberships, + }; + if sources.has_historical_membership() + && sources + .memberships() + .any(|source| source.current_site.is_some()) + { + return Err(PackageError::Integrity); + } + Ok(sources) } -/// Compile the sources of one verified package closure. The caller -/// decides whether generated artifacts must also match byte for byte. -fn compile_package_sources( +impl ParsedPackageSources { + fn memberships(&self) -> impl Iterator { + std::iter::once(&self.project_memberships).chain(&self.module_memberships) + } + + fn has_historical_membership(&self) -> bool { + self.memberships() + .any(|source| !source.historical.is_empty()) + } +} + +#[cfg(feature = "tooling")] +fn project_rehearsal_baseline( + manifest: &PackageManifest, + loaded: &BTreeMap>, + baseline: &CompiledRegistryMigrationBaseline, +) -> Result { + let (sources, assets) = + capture_compiler_inputs(manifest, loaded, PackageSourceMode::Predecessor)?; + if !sources.has_historical_membership() { + return crate::compiler::compile_verified_predecessor_for_rehearsal( + &sources.project, + &sources.modules, + &assets, + ) + .map_err(|_| PackageError::Derivation); + } + + validate_predecessor_module_locks(&sources, &assets)?; + project_archived_registry(manifest, loaded, &sources.project, baseline) +} + +fn validate_predecessor_membership_inventory( + sources: &ParsedPackageSources, + baseline: &CompiledRegistryMigrationBaseline, +) -> Result<()> { + if sources.project.project.version != baseline.registry_version + || baseline + .entities + .values() + .any(|entity| entity.membership.is_some()) + || baseline.actions.actions.iter().any(|action| { + let target_membership = action + .permissions + .iter() + .flat_map(|grant| &grant.targets) + .any(|target| !target.membership_boundaries.is_empty()); + let proposal_targets = match &action.execution { + crate::model::CompiledActionExecution::Proposal { proposal } => { + proposal.permissions.as_slice() + } + crate::model::CompiledActionExecution::Immediate => &[], + }; + target_membership + || proposal_targets + .iter() + .flat_map(|grant| &grant.targets) + .any(|target| !target.membership_boundaries.is_empty()) + }) + { + return Err(PackageError::Derivation); + } + + // Historical read paths never inherited the direct target's membership. + // Unused declarations on other Records cannot disclose a protected row. + let granted_read_path_targets = baseline + .entities + .values() + .flat_map(|entity| { + entity + .access_profiles + .values() + .flat_map(|profile| &profile.read_paths) + .filter_map(|grant| entity.read_paths.get(&grant.path)) + }) + .flat_map(|path| [path.through.as_str(), path.to.as_str()]) + .collect::>(); + + let project = serde_json::to_value(&sources.project).map_err(|_| PackageError::Derivation)?; + let mut seen = BTreeSet::new(); + let mut compare_grants = |source: &Value, memberships: &PredecessorMemberships| { + for (site, boundaries) in &memberships.historical { + if boundaries.is_empty() { + continue; + } + let grant = source + .pointer( + site.strip_suffix("/membershipBoundaries") + .ok_or(PackageError::Derivation)?, + ) + .ok_or(PackageError::Derivation)?; + let parts = site.split('/').collect::>(); + let (id, profile_id) = match parts.as_slice() { + ["", "accessProfiles", profile, "permissions", "records", _, _] => { + (required_str(grant, "recordType")?, *profile) + } + ["", "recordTypes" | "extendRecordTypes", id, "accessProfiles", profile, _] => { + (*id, *profile) + } + _ => return Err(PackageError::Derivation), + }; + let entity = baseline.entities.get(id).ok_or(PackageError::Derivation)?; + let profile = entity + .access_profiles + .get(profile_id) + .ok_or(PackageError::Derivation)?; + let physical = entity + .membership_boundaries + .get(profile_id) + .ok_or(PackageError::Derivation)?; + let rows = grant + .get("rowBoundaries") + .and_then(Value::as_array) + .ok_or(PackageError::Derivation)?; + let claim_count = rows + .len() + .checked_sub(boundaries.len()) + .ok_or(PackageError::Derivation)?; + let claims = &rows[..claim_count]; + let archived_claims = serde_json::to_value(&profile.row_boundaries) + .map_err(|_| PackageError::Derivation)?; + let archived_operations = + serde_json::to_value(&profile.operations).map_err(|_| PackageError::Derivation)?; + let expected_memberships = boundaries + .iter() + .cloned() + .map(MembershipBoundarySource::Expanded); + if entity.id != id + || profile.id != profile_id + || granted_read_path_targets.contains(id) + || !seen.insert((id.to_owned(), profile_id.to_owned())) + || !profile.writable_fields.is_empty() + || profile.spatial_queries.is_some() + || grant.get("operations") != Some(&archived_operations) + || archived_claims.as_array().map(Vec::as_slice) != Some(claims) + || !profile + .membership_boundaries + .iter() + .cloned() + .eq(expected_memberships) + || physical.len() != boundaries.len() + { + return Err(PackageError::Derivation); + } + for (logical, physical) in boundaries.iter().zip(physical) { + verify_predecessor_membership_columns( + baseline, entity, profile, logical, physical, + )?; + } + } + Ok(()) + }; + compare_grants(&project, &sources.project_memberships)?; + for (module, memberships) in sources.modules.iter().zip(&sources.module_memberships) { + let module = serde_json::to_value(module).map_err(|_| PackageError::Derivation)?; + compare_grants(&module, memberships)?; + } + let logical_count = baseline + .entities + .values() + .flat_map(|entity| entity.access_profiles.values()) + .filter(|profile| !profile.membership_boundaries.is_empty()) + .count(); + let physical_count: usize = baseline + .entities + .values() + .map(|entity| entity.membership_boundaries.len()) + .sum(); + // Each matched grant already has equal, ordered logical and physical + // tuples. Both inventories must contain exactly those matched grants. + if seen.len() != logical_count || seen.len() != physical_count { + return Err(PackageError::Derivation); + } + Ok(()) +} + +fn verify_predecessor_membership_columns( + baseline: &CompiledRegistryMigrationBaseline, + protected: &CompiledEntity, + profile: &crate::contract::AccessProfileSource, + logical: &crate::contract::ExpandedMembershipBoundarySource, + physical: &crate::model::CompiledMembershipBoundary, +) -> Result<()> { + let source = baseline + .entities + .get(&logical.membership_entity) + .ok_or(PackageError::Derivation)?; + let names = baseline + .physical_names + .entities + .get(&source.id) + .ok_or(PackageError::Derivation)?; + let field = |id: &str| { + source + .fields + .get(id) + .filter(|field| field.id == id) + .ok_or(PackageError::Derivation) + }; + let root = protected + .fields + .get(&logical.field) + .ok_or(PackageError::Derivation)?; + let protected_names = baseline + .physical_names + .entities + .get(&protected.id) + .ok_or(PackageError::Derivation)?; + let key = field(&logical.membership_key_field)?; + let principal = field(&logical.principal_field)?; + let active = field(&logical.active_field)?; + if physical.field != logical.field + || root.id != logical.field + || protected_names.fields.get(&root.id) != Some(&root.physical_name) + || source.id != logical.membership_entity + || physical.membership_entity != source.id + || physical.membership_table != names.table + || physical.membership_table != source.physical_table + || !source.membership_boundaries.is_empty() + || source.id == protected.id + || baseline.entities.values().any(|entity| { + entity + .read_paths + .values() + .any(|path| path.through == source.id || path.to == source.id) + }) + || !matches!((&root.field_type, &key.field_type), + (FieldTypeSource::Reference { target: root, .. }, FieldTypeSource::Reference { target: key, .. }) if root == key) + || !matches!( + principal.field_type, + FieldTypeSource::String { .. } | FieldTypeSource::Text { .. } + ) + || principal.encryption.is_some() + || active.field_type != FieldTypeSource::Boolean + { + return Err(PackageError::Derivation); + } + if let Some(requirements) = &source.access_requirements { + let mut errors = Vec::new(); + crate::access::check_profile_authority( + requirements, + &profile.required_scopes, + &profile.required_purposes, + "baselinePackage", + &mut errors, + ); + if !requirements.row_boundaries.is_empty() || !errors.is_empty() { + return Err(PackageError::Derivation); + } + } + for (field, column) in [ + (key, &physical.membership_key_column), + (principal, &physical.principal_column), + (active, &physical.active_column), + ] { + if &field.physical_name != column || names.fields.get(&field.id) != Some(column) { + return Err(PackageError::Derivation); + } + } + Ok(()) +} + +/// Rebuild the rehearsal view over the same retained inventories that +/// successor planning uses. As in the migration baseline schema projection, +/// generate DDL from the historical entities, names and Actions. +#[cfg(feature = "tooling")] +fn project_archived_registry( + manifest: &PackageManifest, + loaded: &BTreeMap>, + project: &RegistryProject, + baseline: &CompiledRegistryMigrationBaseline, +) -> Result { + fn member Deserialize<'de>>(model: &mut Value, key: &str) -> Result { + let value = model.get_mut(key).map_or(Value::Null, Value::take); + serde_json::from_value(value).map_err(|error| generated_member_refusal(&error)) + } + + let mut model = packaged_manifest_value(manifest, loaded, PackageFileRole::GovernedModel)?; + let module_closure: Vec = + member(&mut model, "moduleClosure")?; + let archived_locks = module_closure + .iter() + .map(|module| (module.id.as_str(), (&module.version, &module.digest))) + .collect::>(); + if module_closure.len() != project.modules.len() + || archived_locks.len() != module_closure.len() + || project.modules.iter().any(|lock| { + archived_locks.get(lock.id.as_str()) != Some(&(&lock.version, &lock.digest)) + }) + { + return Err(PackageError::Derivation); + } + let ddl = generate_ddl_with_actions( + &baseline.entities, + &baseline.physical_names, + &baseline.actions, + ); + Ok(CompiledRegistry::new( + baseline.registry_id.clone(), + baseline.registry_version.clone(), + member(&mut model, "defaultLanguage")?, + member::>(&mut model, "display")?.unwrap_or_default(), + member(&mut model, "timezone")?, + member::>(&mut model, "reviewAuthorities")?.unwrap_or_default(), + member(&mut model, "datasets")?, + member(&mut model, "accessProfiles")?, + project.package.clone(), + member(&mut model, "manifestProjection")?, + member(&mut model, "moduleOrder")?, + module_closure, + baseline.entities.clone(), + baseline.statistical_datasets.clone(), + baseline.external_views.clone(), + baseline.physical_names.clone(), + baseline.actions.clone(), + baseline.routes.clone(), + baseline.access.clone(), + member(&mut model, "metadataInventory")?, + baseline.queries.clone(), + member(&mut model, "eventDeliveryInventory")?, + baseline.recipients.clone(), + ddl, + // Rehearsal installs the projected schema without publishing artifacts. + serde_json::from_value(Value::Object(Default::default())) + .map_err(|_| PackageError::Derivation)?, + Vec::new(), + baseline.registry_revision.clone(), + )) +} + +/// Reconstruct the historical normalized module value for its exact lock. +/// The legacy grant appended its membership entries after any claim entries. +#[cfg(feature = "tooling")] +fn predecessor_module_digest( + module: &RegistryModule, + memberships: &PredecessorMemberships, + assets: &[ModuleAssetSource], +) -> Result { + let mut value = serde_json::to_value(module).map_err(|_| PackageError::Derivation)?; + for (site, boundaries) in &memberships.historical { + if boundaries.is_empty() { + continue; + } + let (path, _) = site.rsplit_once('/').ok_or(PackageError::Derivation)?; + let grant = value + .pointer_mut(path) + .and_then(Value::as_object_mut) + .ok_or(PackageError::Derivation)?; + let rows = grant + .get_mut("rowBoundaries") + .ok_or(PackageError::Derivation)?; + let entries = rows.as_array_mut().ok_or(PackageError::Derivation)?; + let claim_count = entries + .len() + .checked_sub(boundaries.len()) + .ok_or(PackageError::Derivation)?; + entries.truncate(claim_count); + if entries.is_empty() { + *rows = Value::String("unrestricted".to_owned()); + } + grant.insert( + "membershipBoundaries".to_owned(), + serde_json::to_value(boundaries).map_err(|_| PackageError::Derivation)?, + ); + } + Ok(module_source_digest(&module.id, value, assets)) +} + +#[cfg(feature = "tooling")] +fn validate_predecessor_module_locks( + sources: &ParsedPackageSources, + assets: &[ModuleAssetSource], +) -> Result<()> { + for (module, memberships) in sources.modules.iter().zip(&sources.module_memberships) { + let lock = sources + .project + .modules + .iter() + .find(|lock| lock.id == module.id) + .ok_or(PackageError::Derivation)?; + let original_digest = predecessor_module_digest(module, memberships, assets)?; + if lock.version != module.version || lock.digest.as_ref() != Some(&original_digest) { + return Err(PackageError::Derivation); + } + } + Ok(()) +} + +fn capture_compiler_inputs( manifest: &PackageManifest, loaded: &BTreeMap>, mode: PackageSourceMode, -) -> Result<(CompiledRegistry, bool)> { +) -> Result<(ParsedPackageSources, Vec)> { validate_source_inventory(manifest)?; let fixture_journeys = loaded .get(&manifest.sources.fixture_journeys) @@ -4928,7 +5430,7 @@ fn compile_package_sources( { return Err(PackageError::Derivation); } - let (project, modules) = parse_package_sources(manifest, loaded, mode)?; + let sources = parse_package_sources(manifest, loaded, mode)?; let module_assets = captured_compiler_assets(manifest, loaded)?; let project_assets = module_assets .iter() @@ -4956,12 +5458,31 @@ fn compile_package_sources( .collect(), }) .collect::>(); - validate_declared_package_assets(&project, &modules, &project_assets, &module_sources)?; - validate_captured_bindings(manifest, &project, &modules)?; + validate_declared_package_assets( + &sources.project, + &sources.modules, + &project_assets, + &module_sources, + )?; + validate_captured_bindings(manifest, &sources.project, &sources.modules)?; + Ok((sources, module_assets)) +} + +/// Compile the sources of one verified package closure. The caller +/// decides whether generated artifacts must also match byte for byte. +fn compile_package_sources( + manifest: &PackageManifest, + loaded: &BTreeMap>, + mode: PackageSourceMode, +) -> Result<(CompiledRegistry, bool)> { + let (sources, assets) = capture_compiler_inputs(manifest, loaded, mode)?; + if sources.has_historical_membership() { + return Err(PackageError::Derivation); + } let compiled = compile_project_with_assets( - &project, - &modules, - &module_assets, + &sources.project, + &sources.modules, + &assets, CompileProfile::Production, ) .map_err(|_| PackageError::Derivation)?; @@ -4970,7 +5491,7 @@ fn compile_package_sources( } Ok(( compiled, - crate::compiler::has_placeholder_identity(&project), + crate::compiler::has_placeholder_identity(&sources.project), )) } diff --git a/crates/registry-breg/src/package/tests/immediate_actions.rs b/crates/registry-breg/src/package/tests/immediate_actions.rs index 789155762b..9a477042c6 100644 --- a/crates/registry-breg/src/package/tests/immediate_actions.rs +++ b/crates/registry-breg/src/package/tests/immediate_actions.rs @@ -151,7 +151,7 @@ fn ordinary_policy_source(auditor_operations: Option<&[&str]>) -> Value { {"id":"person-code", "type":"string", "maximumLength":40, "required":true, "classification":"internal"}, {"id":"sensitive-note", "type":"string", "maximumLength":120, "classification":"internal"} ]}}, - "accessProfiles":{"operator": { "default":true, "principalClaim":"principal","requiredScopes":"unrestricted", + "accessProfiles":{"operator": { "default":true, "principalClaim":"principal","requiredScopes":["records:write"], "permissions":{"records":[{"recordType":"person", "operations":["create","get","list"], "readableFields":["person-code","sensitive-note"], "writableFields":["person-code","sensitive-note"], "rowBoundaries":"unrestricted"}]}}} @@ -599,7 +599,7 @@ fn reviewed_successor_does_not_duplicate_action_policies_for_new_entity() { candidate["accessProfiles"] = json!({"task-operator": { "default":true, "principalClaim":"principal", - "requiredScopes":"unrestricted", + "requiredScopes":["records:write"], "permissions":{"actions":[{"action":"create-task", "operations":["invoke"], "targets":[{"recordType":"task", "rowBoundaries":"unrestricted"}], "results":["task"]}]} }}); let after = compile(&candidate); diff --git a/crates/registry-breg/src/package/tests/predecessor_sources.rs b/crates/registry-breg/src/package/tests/predecessor_sources.rs index 910b6c94b6..fe7d2f890e 100644 --- a/crates/registry-breg/src/package/tests/predecessor_sources.rs +++ b/crates/registry-breg/src/package/tests/predecessor_sources.rs @@ -5,9 +5,777 @@ #![cfg(feature = "tooling")] use super::*; +use serde_json::json; use std::fs; use std::path::Path; +const MEMBER_GRANT: &str = "/accessProfiles/member/permissions/records/0"; + +fn membership_source() -> Value { + serde_json::from_slice(include_bytes!(concat!( + env!("CARGO_MANIFEST_DIR"), + "/../../products/breg/fixtures/organization-membership-access/registry.yaml" + ))) + .expect("the maintained membership fixture parses") +} + +fn historical_member_grant(source: &mut Value) { + source["recordTypes"]["membership"] + .as_object_mut() + .unwrap() + .remove("membership"); + let grant = source.pointer_mut(MEMBER_GRANT).unwrap(); + grant["rowBoundaries"] = json!([{"field":"label","claim":"label","operator":"equals"}]); + grant["membershipBoundaries"] = json!([{ + "field": "organization", + "membershipRecordType": "membership", + "membershipKeyField": "organization", + "principalField": "principal", + "activeField": "active" + }]); +} + +#[test] +fn predecessor_sources_refuse_current_membership_elsewhere_in_a_historical_file() { + let mut previous = membership_source(); + historical_member_grant(&mut previous); + let mut different_declaration = + membership_source()["recordTypes"]["membership"]["membership"].clone(); + different_declaration["principal"] = json!("private-note"); + for (pointer, key, value) in [ + ( + "/recordTypes/membership", + "membership", + membership_source()["recordTypes"]["membership"]["membership"].clone(), + ), + ( + "/recordTypes/membership", + "membership", + different_declaration, + ), + ( + "/accessProfiles/steward/permissions/records/2", + "rowBoundaries", + json!([{"field":"organization","membership":"membership"}]), + ), + ( + "/accessProfiles/steward/permissions", + "actions", + json!([{"action":"review","operations":["invoke"],"targets":[{ + "recordType":"facility", + "rowBoundaries":[{"field":"organization","membership":"membership"}] + }]}]), + ), + ( + "/accessProfiles/steward/permissions", + "proposals", + json!([{"action":"review","operations":["apply"],"targets":[{ + "recordType":"facility", + "rowBoundaries":[{"field":"organization","membership":"membership"}] + }]}]), + ), + ( + "", + "rowBoundarySets", + json!({"unused":[{"field":"organization","membership":"membership"}]}), + ), + ] { + let mut mixed = previous.clone(); + mixed.pointer_mut(pointer).unwrap()[key] = value; + let bytes = serde_json::to_vec(&mixed).unwrap(); + let error = parse_predecessor_project_yaml(&bytes).unwrap_err(); + assert_eq!( + error.diagnostics()[0].code, + "breg.membership.mixed-spelling" + ); + assert_eq!( + PackageSourceMode::Predecessor.project(&bytes).err(), + Some(PackageError::Integrity) + ); + assert!(PackageSourceMode::Strict.project(&bytes).is_err()); + } + + previous["rowBoundarySets"] = json!({ + "same-organization":[{"field":"organization","membership":"membership"}] + }); + previous["accessProfiles"]["steward"]["permissions"]["records"][2]["rowBoundaries"] = + json!({"rowBoundarySet":"same-organization"}); + let error = + parse_predecessor_project_yaml(&serde_json::to_vec(&previous).unwrap()).unwrap_err(); + assert_eq!( + error.diagnostics()[0].code, + "breg.membership.mixed-spelling" + ); +} + +#[test] +fn predecessor_sources_refuse_mixed_membership_across_project_and_module() { + let mut project = membership_source(); + historical_member_grant(&mut project); + let historical_grant = project.pointer(MEMBER_GRANT).unwrap()["membershipBoundaries"].clone(); + let mut module = json!({ + "apiVersion": crate::contract::MODULE_API_VERSION, + "kind": crate::contract::MODULE_KIND, + "id": "member-grants", + "version": "1", + "extendRecordTypes": {"facility":{"accessProfiles":{"observer":{ + "principalClaim":"principal", "requiredScopes":["membership:use"], + "operations":["get"], "readableFields":["label"], + "rowBoundaries":"unrestricted" + }}}} + }); + let prepared = prepare_membership_candidate(&membership_source()); + let mut manifest = prepared.manifest; + let mut files = prepared.files; + let module_path = "source/modules/member-grants/module.yaml".to_owned(); + manifest.sources.modules.push(CapturedModule { + id: "member-grants".to_owned(), + path: module_path.clone(), + assets: Vec::new(), + }); + files.insert( + manifest.sources.project.clone(), + serde_json::to_vec(&project).unwrap(), + ); + for (key, declaration) in [ + ( + "recordTypes", + json!({"membership": membership_source()["recordTypes"]["membership"].clone()}), + ), + ( + "rowBoundarySets", + json!({"unused":[{"field":"organization","membership":"membership"}]}), + ), + ] { + module[key] = declaration; + files.insert(module_path.clone(), serde_json::to_vec(&module).unwrap()); + assert_eq!( + parse_package_sources(&manifest, &files, PackageSourceMode::Predecessor).err(), + Some(PackageError::Integrity), + "{key}" + ); + module.as_object_mut().unwrap().remove(key); + } + + module["extendRecordTypes"]["facility"]["accessProfiles"]["observer"]["membershipBoundaries"] = + historical_grant; + files.insert( + manifest.sources.project.clone(), + serde_json::to_vec(&membership_source()).unwrap(), + ); + files.insert(module_path, serde_json::to_vec(&module).unwrap()); + assert_eq!( + parse_package_sources(&manifest, &files, PackageSourceMode::Predecessor).err(), + Some(PackageError::Integrity) + ); +} + +#[test] +fn predecessor_sources_rehearse_a_historically_maintained_membership_source() { + let mut current = membership_source(); + current.pointer_mut(MEMBER_GRANT).unwrap()["rowBoundaries"] + .as_array_mut() + .unwrap() + .insert( + 0, + json!({"field":"label","claim":"label","operator":"equals"}), + ); + let mut prepared = prepare_membership_candidate(¤t); + let source_path = prepared.manifest.sources.project.clone(); + let mut historical: Value = serde_json::from_slice(&prepared.files[&source_path]).unwrap(); + let writer_path = "/accessProfiles/steward/permissions/records/1"; + let maintenance_boundary = + json!([{"field":"principal","claim":"principal","operator":"equals"}]); + current.pointer_mut(writer_path).unwrap()["rowBoundaries"] = maintenance_boundary.clone(); + let edited = parse_project_yaml(&serde_json::to_vec(¤t).unwrap()).unwrap(); + for profile in [CompileProfile::Authoring, CompileProfile::Production] { + let error = compile_project_with_assets(&edited, &[], &[], profile).unwrap_err(); + assert!(error + .diagnostics() + .iter() + .any(|diagnostic| { diagnostic.code == "breg.access.membership-source-key-write" })); + } + + historical_member_grant(&mut historical); + historical.pointer_mut(writer_path).unwrap()["rowBoundaries"] = maintenance_boundary.clone(); + let entry = unique_manifest_file(&prepared.manifest, PackageFileRole::GovernedModel).unwrap(); + let mut model: Value = serde_json::from_slice(&prepared.files[&entry.path]).unwrap(); + let source = &mut model["recordTypes"]["membership"]; + source.as_object_mut().unwrap().remove("membership"); + source["accessProfiles"]["steward"]["rowBoundaries"] = maintenance_boundary; + prepared + .files + .insert(entry.path.clone(), canonicalize_json(&model).unwrap()); + let bytes = serde_json::to_vec(&historical).unwrap(); + assert_eq!( + parse_project_yaml(&bytes).unwrap_err().diagnostics()[0].code, + "config.removed-key" + ); + prepared.files.insert(source_path, bytes); + assert!(matches!( + rederive(&prepared.manifest, &prepared.files), + Err(PackageError::PreviousReleaseSources(_)) + )); + + let governed = package_predecessor_governed_model(&prepared.manifest, &prepared.files).unwrap(); + let baseline = governed.migration_baseline( + "sha256:1111111111111111111111111111111111111111111111111111111111111111", + current_engine_features(), + None, + ); + let registry = project_rehearsal_baseline(&prepared.manifest, &prepared.files, &baseline) + .expect("the historical baseline preserves the archived read and maintenance grants"); + assert_eq!(registry.entities(), &baseline.entities); + assert_eq!(registry.physical_names(), &baseline.physical_names); + assert_eq!(registry.access(), &baseline.access); + assert_eq!( + registry.ddl(), + prepared + .registry + .with_migration_baseline_schema(&baseline) + .ddl() + ); + let previous_writer = edited + .access_profiles + .iter() + .find(|profile| profile.id == "steward") + .unwrap() + .permissions + .entities + .iter() + .find(|grant| grant.entity == "membership") + .unwrap(); + assert_eq!( + registry.entities()["membership"].access_profiles["steward"].row_boundaries, + previous_writer.row_boundaries + ); + assert!(registry.ddl().functions.iter().any(|function| { + function.name == crate::membership::function_name("facility", "member", 0) + })); + assert!(!registry + .ddl() + .statements + .iter() + .any(|statement| { statement.id == "entity.membership.membership.key-index" })); + let maintenance = current.pointer_mut(writer_path).unwrap(); + maintenance["operations"] = json!(["get", "patch"]); + maintenance["writableFields"] = json!(["private-note"]); + let successor = prepare_membership_candidate(¤t); + assert!(successor + .registry + .ddl() + .statements + .iter() + .any(|statement| { statement.id == "entity.membership.membership.key-index" })); + let changes = compiled_registry_change_set_from_baseline( + &baseline, + &successor.registry, + &baseline.package_digest, + ); + assert_eq!(changes.from_package_digest, baseline.package_digest); + assert!(changes.changes.iter().any(|change| { + change.code == CompiledRegistryChangeCode::AccessProfileChanged + && change.target.record_type_id.as_deref() == Some("membership") + })); +} + +fn prepare_membership_candidate(source: &Value) -> PreparedPackage { + let mut source = source.clone(); + source["package"] = json!({ + "sourceRevision":"0123456789abcdef0123456789abcdef01234567" + }); + prepare_package(PackageBuildRequest { + from_package_digest: None, + compiler_source_revision: "0123456789abcdef0123456789abcdef01234567".to_owned(), + schema_fingerprint: + "sha256:1111111111111111111111111111111111111111111111111111111111111111".to_owned(), + project: PackageSourceFile { + path: "source/project.yaml".to_owned(), + bytes: serde_json::to_vec(&source).unwrap(), + }, + modules: Vec::new(), + fixture_journeys: PackageSourceFile { + path: FIXTURE_JOURNEYS_PATH.to_owned(), + bytes: b"journeys: []".to_vec(), + }, + migration_plan: PackageMigrationPlanInput::InitialCompiledDdl, + }) + .expect("the maintained membership source compiles for a candidate") +} + +#[test] +fn predecessor_sources_preserve_a_historical_membership_and_claim_conjunction() { + let mut previous = membership_source(); + historical_member_grant(&mut previous); + let mut current = membership_source(); + current.pointer_mut(MEMBER_GRANT).unwrap()["rowBoundaries"] + .as_array_mut() + .unwrap() + .insert( + 0, + previous.pointer(MEMBER_GRANT).unwrap()["rowBoundaries"][0].clone(), + ); + + let bytes = serde_json::to_vec(&previous).unwrap(); + assert_eq!( + parse_project_yaml(&bytes).unwrap_err().diagnostics()[0].code, + "config.removed-key" + ); + assert!(PackageSourceMode::Strict.project(&bytes).is_err()); + let (project, legacy) = PackageSourceMode::Predecessor.project(&bytes).unwrap(); + assert_eq!(legacy.historical.len(), 1); + let prepared = prepare_membership_candidate(¤t); + let archive_profile = &prepared.registry.entities()["facility"].access_profiles["member"]; + let historical_permission = &project + .access_profiles + .iter() + .find(|profile| profile.id == "member") + .unwrap() + .permissions + .entities[0]; + assert_eq!( + historical_permission.row_boundaries, + archive_profile.row_boundaries + ); + assert_eq!( + archive_profile.membership_boundaries, + vec![MembershipBoundarySource::Expanded( + legacy.historical.values().next().unwrap()[0].clone() + )] + ); +} + +#[test] +fn predecessor_sources_refuse_malformed_or_mixed_historical_membership() { + let mut previous = membership_source(); + historical_member_grant(&mut previous); + let cases: [(&str, Value, &str); 8] = [ + ("membershipBoundaries", Value::Null, "config.null-value"), + ( + "membershipBoundaries/0/principalField", + json!(false), + "config.expected-string", + ), + ( + "membershipBoundaries/0/unknownField", + json!("extra"), + "config.unknown-key", + ), + ( + "membershipBoundaries/0/field", + json!("id"), + "breg.access.membership-key-type", + ), + ("membershipBoundaries/1", json!(null), "config.null-value"), + ( + "rowBoundaries/0", + json!({"field":"organization","membership":"membership"}), + "breg.membership.mixed-spelling", + ), + ( + "operations", + json!(["patch"]), + "breg.access.membership-read-only", + ), + ( + "writableFields", + json!(["label"]), + "breg.access.membership-read-only", + ), + ]; + for (path, value, code) in cases { + let mut source = previous.clone(); + let grant = source.pointer_mut(MEMBER_GRANT).unwrap(); + if path == "membershipBoundaries/1" { + grant["membershipBoundaries"] + .as_array_mut() + .unwrap() + .push(value); + } else { + let pointer = format!("/{path}"); + if let Some(target) = grant.pointer_mut(&pointer) { + *target = value; + } else if let Some((parent, key)) = pointer.rsplit_once('/') { + grant.pointer_mut(parent).unwrap()[key] = value; + } + } + let bytes = serde_json::to_vec(&source).unwrap(); + let error = parse_predecessor_project_yaml(&bytes).unwrap_err(); + assert_eq!(error.diagnostics()[0].code, code, "{path}: {error:?}"); + assert!(PackageSourceMode::Strict.project(&bytes).is_err()); + } + + let bytes = serde_json::to_string(&previous).unwrap().replace( + "\"membershipBoundaries\":", + "\"membershipBoundaries\":[],\"membershipBoundaries\":", + ); + for mode in [PackageSourceMode::Strict, PackageSourceMode::Predecessor] { + assert_eq!( + mode.project(bytes.as_bytes()).err(), + Some(PackageError::Integrity) + ); + } + + let grant = previous.pointer_mut(MEMBER_GRANT).unwrap(); + let duplicate = grant["membershipBoundaries"][0].clone(); + grant["membershipBoundaries"] + .as_array_mut() + .unwrap() + .push(duplicate); + let error = + parse_predecessor_project_yaml(&serde_json::to_vec(&previous).unwrap()).unwrap_err(); + assert_eq!( + error.diagnostics()[0].code, + "breg.access.membership-duplicate" + ); +} + +#[test] +fn predecessor_sources_still_refuse_an_unrelated_retired_key() { + let mut previous = membership_source(); + historical_member_grant(&mut previous); + previous["recordTypes"]["facility"]["changeControl"] = json!({}); + let error = + parse_predecessor_project_yaml(&serde_json::to_vec(&previous).unwrap()).unwrap_err(); + assert_eq!(error.diagnostics()[0].code, "config.removed-key"); + assert!(error.diagnostics()[0].path.ends_with(".changeControl")); +} + +#[test] +fn predecessor_sources_keep_the_module_lock_bound_to_the_exact_membership_fields() { + let mut previous = membership_source(); + historical_member_grant(&mut previous); + let boundaries = previous.pointer(MEMBER_GRANT).unwrap()["membershipBoundaries"].clone(); + previous["accessProfiles"] + .as_object_mut() + .unwrap() + .remove("member"); + let mut module = json!({ + "apiVersion": crate::contract::MODULE_API_VERSION, + "kind": crate::contract::MODULE_KIND, + "id": "member-grants", + "version": "1", + "extendRecordTypes": { + "facility": {"accessProfiles": { + "member": { + "principalClaim": "principal", + "requiredScopes": ["records:read", "membership:use"], + "operations": ["get"], + "readableFields": ["label"], + "rowBoundaries": "unrestricted", + "membershipBoundaries": boundaries + } + }} + } + }); + let bytes = serde_json::to_vec(&module).unwrap(); + assert!(parse_module_yaml(&bytes).is_err()); + assert!(PackageSourceMode::Strict.module(&bytes).is_err()); + let (original, original_memberships) = PackageSourceMode::Predecessor.module(&bytes).unwrap(); + let assets = [ModuleAssetSource { + module: Some("member-grants".to_owned()), + path: "plans/check.rhai".to_owned(), + bytes: b"fn plan(ctx) { #{effects: []} }".to_vec(), + }]; + let original_digest = + predecessor_module_digest(&original, &original_memberships, &assets).unwrap(); + assert_ne!( + original_digest, + crate::compiler::module_digest_with_assets(&original, &assets) + ); + + let other = parse_module_yaml( + &serde_json::to_vec(&json!({ + "apiVersion": crate::contract::MODULE_API_VERSION, + "kind": crate::contract::MODULE_KIND, + "id": "other", + "version": "2" + })) + .unwrap(), + ) + .unwrap(); + let other_digest = crate::compiler::module_digest_with_assets(&other, &assets); + + previous["modules"] = json!({ + "member-grants": {"version":"1", "digest": original_digest}, + "other": {"version":"2", "digest":other_digest} + }); + let project = parse_project_yaml(&serde_json::to_vec(&previous).unwrap()).unwrap(); + module["extendRecordTypes"]["facility"]["accessProfiles"]["member"]["membershipBoundaries"] + [0]["principalField"] = json!("private-note"); + let (changed, changed_memberships) = PackageSourceMode::Predecessor + .module(&serde_json::to_vec(&module).unwrap()) + .unwrap(); + assert_eq!(changed, original); + let changed_sources = ParsedPackageSources { + project: project.clone(), + modules: vec![other.clone(), changed], + project_memberships: PredecessorMemberships::default(), + module_memberships: vec![PredecessorMemberships::default(), changed_memberships], + }; + assert_eq!( + validate_predecessor_module_locks(&changed_sources, &assets), + Err(PackageError::Derivation) + ); + + let original_sources = ParsedPackageSources { + project, + modules: vec![other, original], + project_memberships: PredecessorMemberships::default(), + module_memberships: vec![PredecessorMemberships::default(), original_memberships], + }; + validate_predecessor_module_locks(&original_sources, &assets).unwrap(); + assert_eq!( + validate_predecessor_module_locks(&original_sources, &[]), + Err(PackageError::Derivation) + ); + assert_eq!( + original_sources.project.modules[0].digest.as_deref(), + Some(original_digest.as_str()) + ); +} + +fn historical_membership_package() -> PreparedPackage { + let mut current = membership_source(); + current.pointer_mut(MEMBER_GRANT).unwrap()["rowBoundaries"] + .as_array_mut() + .unwrap() + .insert( + 0, + json!({"field":"label","claim":"label","operator":"equals"}), + ); + let mut package = prepare_membership_candidate(¤t); + let path = package.manifest.sources.project.clone(); + let mut source: Value = serde_json::from_slice(&package.files[&path]).unwrap(); + historical_member_grant(&mut source); + package + .files + .insert(path, serde_json::to_vec(&source).unwrap()); + edit_governed_model(&mut package, |model| { + model["recordTypes"]["membership"] + .as_object_mut() + .unwrap() + .remove("membership"); + }); + package +} + +fn edit_governed_model(package: &mut PreparedPackage, edit: impl FnOnce(&mut Value)) { + let entry = unique_manifest_file(&package.manifest, PackageFileRole::GovernedModel).unwrap(); + let mut model = serde_json::from_slice(&package.files[&entry.path]).unwrap(); + edit(&mut model); + package + .files + .insert(entry.path.clone(), canonicalize_json(&model).unwrap()); +} + +fn historical_membership_baseline(package: &PreparedPackage) -> CompiledRegistryMigrationBaseline { + let governed = package_predecessor_governed_model(&package.manifest, &package.files).unwrap(); + governed.migration_baseline( + "sha256:1111111111111111111111111111111111111111111111111111111111111111", + current_engine_features(), + None, + ) +} + +#[test] +fn predecessor_sources_rehearse_distinct_membership_tuples_on_one_source() { + let mut package = historical_membership_package(); + let path = package.manifest.sources.project.clone(); + let mut source: Value = serde_json::from_slice(&package.files[&path]).unwrap(); + let stored_bounds = source.pointer_mut(MEMBER_GRANT).unwrap()["membershipBoundaries"] + .as_array_mut() + .unwrap(); + let mut alternate = stored_bounds[0].clone(); + alternate["principalField"] = json!("private-note"); + stored_bounds.push(alternate.clone()); + package + .files + .insert(path, serde_json::to_vec(&source).unwrap()); + + let alternate_column = package.registry.entities()["membership"].fields["private-note"] + .physical_name + .clone(); + edit_governed_model(&mut package, |model| { + let entity = &mut model["recordTypes"]["facility"]; + entity["accessProfiles"]["member"]["membershipBoundaries"] + .as_array_mut() + .unwrap() + .push(alternate); + let compiled = entity["membershipBoundaries"]["member"] + .as_array_mut() + .unwrap(); + let mut alternate = compiled[0].clone(); + alternate["principalColumn"] = json!(alternate_column); + compiled.push(alternate); + }); + let baseline = historical_membership_baseline(&package); + let sources = parse_package_sources( + &package.manifest, + &package.files, + PackageSourceMode::Predecessor, + ) + .unwrap(); + validate_predecessor_membership_inventory(&sources, &baseline).unwrap(); + let registry = project_rehearsal_baseline(&package.manifest, &package.files, &baseline) + .expect("rehearsal preserves each archived tuple"); + let boundaries = ®istry.entities()["facility"].membership_boundaries["member"]; + assert_eq!(boundaries.len(), 2); + assert_ne!( + boundaries[0].principal_column, + boundaries[1].principal_column + ); + for (ordinal, boundary) in boundaries.iter().enumerate() { + let probe = crate::membership::function_name("facility", "member", ordinal); + let statement = registry + .ddl() + .statements + .iter() + .find(|statement| statement.id == format!("registry_context.{probe}")) + .expect("one read probe per historical tuple"); + assert!(statement + .sql + .contains(&format!("membership.\"{}\"", boundary.principal_column))); + } +} + +#[test] +fn predecessor_membership_inventory_refuses_unmatched_members() { + let package = historical_membership_package(); + let sources = parse_package_sources( + &package.manifest, + &package.files, + PackageSourceMode::Predecessor, + ) + .unwrap(); + let baseline = historical_membership_baseline(&package); + validate_predecessor_membership_inventory(&sources, &baseline).unwrap(); + let mut logical_only = baseline.clone(); + let facility = logical_only.entities.get_mut("facility").unwrap(); + facility + .access_profiles + .get_mut("steward") + .unwrap() + .membership_boundaries = baseline.entities["facility"].access_profiles["member"] + .membership_boundaries + .clone(); + assert_eq!( + validate_predecessor_membership_inventory(&sources, &logical_only), + Err(PackageError::Derivation) + ); + + let mut mismatched = baseline.clone(); + mismatched + .entities + .get_mut("facility") + .unwrap() + .membership_boundaries + .get_mut("member") + .unwrap()[0] + .principal_column = baseline.entities["membership"].fields["private-note"] + .physical_name + .clone(); + assert_eq!( + validate_predecessor_membership_inventory(&sources, &mismatched), + Err(PackageError::Derivation) + ); +} + +#[test] +fn predecessor_membership_inventory_refuses_granted_read_paths_to_protected_records() { + let package = historical_membership_package(); + let sources = parse_package_sources( + &package.manifest, + &package.files, + PackageSourceMode::Predecessor, + ) + .unwrap(); + let baseline = historical_membership_baseline(&package); + for (through, to) in [("facility", "organization"), ("organization", "facility")] { + let mut archive = baseline.clone(); + let entity = archive.entities.get_mut("organization").unwrap(); + let path = crate::model::CompiledReadPath { + id: "related".to_owned(), + route: "related".to_owned(), + through: through.to_owned(), + to: to.to_owned(), + source_ref: "organization".to_owned(), + target_ref: "organization".to_owned(), + }; + entity.read_paths.insert(path.id.clone(), path); + validate_predecessor_membership_inventory(&sources, &archive).unwrap(); + + archive + .entities + .get_mut("organization") + .unwrap() + .access_profiles + .get_mut("steward") + .unwrap() + .read_paths + .push(serde_json::from_value(json!({"path":"related"})).unwrap()); + assert_eq!( + validate_predecessor_membership_inventory(&sources, &archive), + Err(PackageError::Derivation) + ); + } +} + +#[test] +fn predecessor_membership_inventory_refuses_current_action_and_proposal_targets() { + let package = historical_membership_package(); + let sources = parse_package_sources( + &package.manifest, + &package.files, + PackageSourceMode::Predecessor, + ) + .unwrap(); + let mut baseline = historical_membership_baseline(&package); + baseline.actions = serde_json::from_slice(include_bytes!(concat!( + env!("CARGO_MANIFEST_DIR"), + "/../../products/breg/generated/facility/compiled/actions.json" + ))) + .unwrap(); + validate_predecessor_membership_inventory(&sources, &baseline).unwrap(); + let boundary = &baseline.entities["facility"].membership_boundaries["member"][0]; + let mut immediate = baseline.clone(); + let action = immediate + .actions + .actions + .iter_mut() + .find(|action| !action.execution.is_proposal()) + .unwrap(); + action.permissions[0].targets[0] + .membership_boundaries + .push(boundary.clone()); + assert_eq!( + validate_predecessor_membership_inventory(&sources, &immediate), + Err(PackageError::Derivation) + ); + + let mut proposal = baseline.clone(); + let policy = proposal + .actions + .actions + .iter_mut() + .find_map(|action| match &mut action.execution { + crate::model::CompiledActionExecution::Proposal { proposal } => Some(proposal), + crate::model::CompiledActionExecution::Immediate => None, + }) + .unwrap(); + let target = policy + .permissions + .iter_mut() + .flat_map(|grant| &mut grant.targets) + .next() + .unwrap(); + target.membership_boundaries.push(boundary.clone()); + assert_eq!( + validate_predecessor_membership_inventory(&sources, &proposal), + Err(PackageError::Derivation) + ); +} + /// An exact historical package built before access profiles were keyed by id, /// so its stored sources list them. fn list_form_package() -> PathBuf { diff --git a/crates/registry-breg/src/postgres/cancellation.rs b/crates/registry-breg/src/postgres/cancellation.rs index d60add4206..d78d7cdfe7 100644 --- a/crates/registry-breg/src/postgres/cancellation.rs +++ b/crates/registry-breg/src/postgres/cancellation.rs @@ -19,6 +19,10 @@ use std::time::Duration; +use deadpool_postgres::ClientWrapper; +use tokio::sync::OwnedSemaphorePermit; +use tokio_postgres::{CancelToken, Client}; + use super::RuntimePool; /// How long a guard waits for the cancel request and then for the cancelled @@ -123,11 +127,179 @@ impl Drop for Discarded { /// travels on its own connection and may land on whatever the session runs /// next, so a cancelled session is never reused. async fn stop_and_discard(session: Discarded, token: tokio_postgres::CancelToken) { - let _ = tokio::time::timeout(QUERY_CANCEL_TIMEOUT, session.pool.cancel_query(token)).await; if let Some(client) = &session.client { - // The empty query is answered only after every request queued before - // it, including the cancelled statement and the rollback its dropped - // transaction queued, so its answer means the backend is idle. - let _ = tokio::time::timeout(QUERY_CANCEL_TIMEOUT, client.simple_query("")).await; + cancel_and_drain(&session.pool, token, client).await; + } +} + +async fn cancel_and_drain(pool: &RuntimePool, token: CancelToken, client: &Client) { + let _ = tokio::time::timeout(QUERY_CANCEL_TIMEOUT, pool.cancel_query(token)).await; + // The empty query is answered only after every request queued before + // it, including the cancelled statement and the rollback its dropped + // transaction queued, so its answer means the backend is idle. + let _ = tokio::time::timeout(QUERY_CANCEL_TIMEOUT, client.simple_query("")).await; +} + +/// The dedicated staging session retains its permit while cancellation drains it. +pub(crate) struct AttachmentStagingGuard { + pool: RuntimePool, + session: Option<(ClientWrapper, OwnedSemaphorePermit)>, +} + +impl AttachmentStagingGuard { + pub(super) fn new( + pool: RuntimePool, + client: ClientWrapper, + permit: OwnedSemaphorePermit, + ) -> Self { + Self { + pool, + session: Some((client, permit)), + } + } + + pub(crate) fn client(&mut self) -> &mut ClientWrapper { + &mut self + .session + .as_mut() + .expect("the staging session is guarded") + .0 + } + + pub(crate) fn disarm(mut self) { + drop(self.session.take()); + } +} + +impl Drop for AttachmentStagingGuard { + fn drop(&mut self) { + if let Some((client, permit)) = self.session.take() { + let Ok(runtime) = tokio::runtime::Handle::try_current() else { + return; + }; + let pool = self.pool.clone(); + runtime.spawn(async move { + cancel_and_drain(&pool, client.cancel_token(), &client).await; + drop(client); + drop(permit); + }); + } + } +} + +#[cfg(all(test, feature = "postgres-tls-test"))] +mod tests { + use std::{env, fs, future::poll_fn, pin::pin}; + + use futures_core::Stream; + use tokio::time::{sleep, timeout}; + use tokio_postgres::{error::SqlState, SimpleQueryMessage}; + + use super::*; + use crate::postgres::{ConnectionConfig, PoolBounds}; + + const STATEMENT: &str = "SELECT 1 FROM pg_catalog.pg_sleep(30)"; + + async fn tls_backend_pid(client: &Client) -> i32 { + let row = client + .query_one( + "SELECT pid, ssl FROM pg_catalog.pg_stat_ssl WHERE pid = pg_backend_pid()", + &[], + ) + .await + .unwrap_or_else(|_| panic!("read TLS state for this backend")); + assert!(row.get::<_, bool>(1), "the staging backend must use TLS"); + row.get(0) + } + + #[tokio::test] + async fn verified_tls_attachment_staging_cancels_on_drop() { + let url = env::var("BREG_TEST_TLS_DATABASE_URL").expect("TLS fixture URL is required"); + let ca_path = env::var("BREG_TEST_TLS_CA_DER_PATH").expect("TLS fixture CA is required"); + let ca = fs::read(ca_path).unwrap_or_else(|_| panic!("read the TLS fixture CA")); + let connection_bound = Duration::from_secs(3); + let bounds = PoolBounds::new(1, connection_bound, connection_bound, connection_bound) + .expect("valid fixture connection bounds"); + let pool = ConnectionConfig::require_tls_with_custom_ca(&url, &ca, bounds) + .expect("configure verified TLS with the fixture CA") + .build_pool() + .expect("build the fixture pool"); + + timeout(Duration::from_secs(10), async { + let observer = pool + .get() + .await + .unwrap_or_else(|_| panic!("open the observer session")); + let mut staging = pool + .attachment_staging_connection() + .await + .unwrap_or_else(|_| panic!("open staging while the pool is full")); + tls_backend_pid(staging.client()).await; + staging.disarm(); + + let mut staging = pool + .attachment_staging_connection() + .await + .unwrap_or_else(|_| panic!("reacquire staging after disarm")); + let staging_pid = tls_backend_pid(staging.client()).await; + staging + .client() + .batch_execute("SET statement_timeout = 0") + .await + .unwrap_or_else(|_| panic!("disable the fixture's statement timeout")); + // Queue the statement without waiting for a server response. Keep + // its stream to read the result after dropping the guard. + let mut rows = pin!(staging + .client() + .simple_query_raw(STATEMENT) + .await + .unwrap_or_else(|_| panic!("start the test-owned statement"))); + timeout(connection_bound, async { + loop { + let waiting = observer + .query_one( + "SELECT EXISTS (SELECT 1 FROM pg_catalog.pg_stat_activity + WHERE pid = $1 AND state = 'active' AND query = $2 + AND wait_event_type = 'Timeout' AND wait_event = 'PgSleep')", + &[&staging_pid, &STATEMENT], + ) + .await + .unwrap_or_else(|_| panic!("observe the test-owned statement")) + .get::<_, bool>(0); + if waiting { + break; + } + sleep(Duration::from_millis(20)).await; + } + }) + .await + .expect("the test-owned statement must reach its wait before cancellation"); + drop(staging); + let result = match poll_fn(|cx| rows.as_mut().poll_next(cx)).await { + Some(Ok(SimpleQueryMessage::RowDescription(_))) => { + poll_fn(|cx| rows.as_mut().poll_next(cx)).await + } + result => result, + }; + let Some(Err(error)) = result else { + panic!("the test-owned statement must report cancellation"); + }; + assert!( + error.code() == Some(&SqlState::QUERY_CANCELED), + "the server must report SQLSTATE 57014 for the cancelled statement" + ); + + let mut replacement = pool + .attachment_staging_connection() + .await + .unwrap_or_else(|_| panic!("reacquire staging after discard")); + assert!( + tls_backend_pid(replacement.client()).await != staging_pid, + "reacquired staging must use a fresh backend" + ); + replacement.disarm(); + }) + .await + .expect("the staging TLS proof must finish within ten seconds"); } } diff --git a/crates/registry-breg/src/postgres/catalog.rs b/crates/registry-breg/src/postgres/catalog.rs index f66111969c..6147b08510 100644 --- a/crates/registry-breg/src/postgres/catalog.rs +++ b/crates/registry-breg/src/postgres/catalog.rs @@ -143,6 +143,7 @@ const MANAGED_INTERNAL_INDEXES: &[&str] = &[ "registry_internal.registry_ingestion_run_chunk_records_erased_record", "registry_internal.registry_migrations_one_open_activation_per_digest", "registry_internal.registry_proposal_evidence_uses_expiry", + "registry_internal.registry_proposal_form_entries_form", "registry_internal.registry_proposal_idempotency_by_request", "registry_internal.registry_proposal_pending_targets", "registry_internal.registry_proposal_queue", @@ -154,6 +155,7 @@ const MANAGED_INTERNAL_INDEXES: &[&str] = &[ "registry_internal.registry_proposal_review_completion_reconcile", "registry_internal.registry_proposal_review_submission_jobs", "registry_internal.registry_proposal_review_submissions_request", + "registry_internal.registry_proposal_subject", "registry_internal.registry_record_attachment_live_references", super::timer::TIMER_BINDINGS_OPEN_INDEX, super::timer::TIMER_DUE_INDEX, @@ -1574,6 +1576,15 @@ async fn verify_closed_ambient_catalog( projection_definers.push(*security_definer); } } + let membership_identities: Vec<_> = expected_catalog + .objects + .iter() + .filter(|object| { + object.kind == ManagedObjectKind::Function + && object.name.starts_with("registry_context.membership_") + }) + .map(|object| object.name.as_str()) + .collect(); let row = client .query_one( "SELECT @@ -1617,12 +1628,17 @@ async fn verify_closed_ambient_catalog( AND p.proisstrict AND p.provolatile = 'i' AND p.proconfig = ARRAY['search_path=pg_catalog']) - OR (p.proname ~ '^membership_[0-9a-f]{24}$' + OR (p.proname ~ '^membership_(target_|lock_)?[0-9a-f]{24}$' + AND ('registry_context.' || p.proname || '(uuid)') = ANY($6::text[]) AND pg_catalog.pg_get_function_identity_arguments(p.oid) = 'uuid' AND p.prorettype = 'boolean'::regtype AND NOT p.proretset AND NOT p.prosecdef - AND p.provolatile = 's') + AND p.provolatile::text = CASE WHEN p.proname ~ '^membership_lock_' THEN 'v' ELSE 's' END + AND p.prokind = 'f' + AND p.proisstrict AND NOT p.proleakproof + AND p.prolang = (SELECT oid FROM pg_catalog.pg_language WHERE lanname = 'plpgsql') + AND p.proconfig = ARRAY['search_path=pg_catalog']) OR (p.proname ~ '^consent_[0-9a-f]{24}$' AND pg_catalog.pg_get_function_identity_arguments(p.oid) = '' AND p.prorettype = 'uuid'::regtype @@ -1695,7 +1711,7 @@ async fn verify_closed_ambient_catalog( ) OR EXISTS ( SELECT 1 FROM pg_catalog.pg_publication WHERE puballtables )", - &[&MANAGED_SCHEMAS, &projection_identities, &projection_returns, &projection_sets, &projection_definers], + &[&MANAGED_SCHEMAS, &projection_identities, &projection_returns, &projection_sets, &projection_definers, &membership_identities], ) .await?; if (0..5).any(|index| row.get::<_, bool>(index)) { diff --git a/crates/registry-breg/src/postgres/config.rs b/crates/registry-breg/src/postgres/config.rs index 38b0643dfa..a810d7e5ec 100644 --- a/crates/registry-breg/src/postgres/config.rs +++ b/crates/registry-breg/src/postgres/config.rs @@ -1,12 +1,21 @@ // SPDX-License-Identifier: Apache-2.0 -use std::{error::Error as _, fmt, sync::OnceLock, time::Duration}; - -use deadpool_postgres::{Manager, ManagerConfig, Pool, RecyclingMethod, Runtime}; +use std::{ + error::Error as _, + fmt, + sync::{Arc, OnceLock}, + time::Duration, +}; + +use deadpool_postgres::{ + ClientWrapper, ConfigConnectImpl, Connect, Manager, ManagerConfig, Pool, RecyclingMethod, + Runtime, +}; use tokio_postgres::NoTls; use tokio_postgres::{config::SslMode, CancelToken, Config}; use tokio_postgres_rustls::MakeRustlsConnect; +use super::cancellation::AttachmentStagingGuard; use super::{PostgresKernelError, Result}; const MAX_POOL_SIZE: usize = 128; @@ -348,6 +357,8 @@ impl ConnectionConfig { Ok(RuntimePool { pool, transport: self.transport.clone(), + postgres: self.postgres.clone(), + attachment_staging: Arc::new(tokio::sync::Semaphore::new(1)), }) } } @@ -416,6 +427,8 @@ fn connector_from_roots(roots: rustls::RootCertStore) -> Result, } /// Value-free causes that operator tooling may report for a refused database @@ -568,6 +581,43 @@ impl RuntimePool { self.pool.get().await.map_err(|_| PostgresKernelError::Pool) } + /// Durable S3 staging while the caller's primary transaction holds its + /// membership and target locks. One separate session per pool prevents + /// pool exhaustion when every ordinary connection is in use. + pub(crate) async fn attachment_staging_connection(&self) -> Result { + let permit = Arc::clone(&self.attachment_staging) + .acquire_owned() + .await + .map_err(|_| PostgresKernelError::Pool)?; + let connect = async { + match &self.transport { + Transport::Tls { connector, .. } => { + ConfigConnectImpl { + tls: connector.clone(), + } + .connect(&self.postgres) + .await + } + Transport::Plaintext(_) => { + ConfigConnectImpl { tls: NoTls } + .connect(&self.postgres) + .await + } + } + }; + let (client, task) = match self.pool.timeouts().create { + Some(timeout) => tokio::time::timeout(timeout, connect) + .await + .map_err(|_| PostgresKernelError::Pool)??, + None => connect.await?, + }; + Ok(AttachmentStagingGuard::new( + self.clone(), + ClientWrapper::new(client, task), + permit, + )) + } + pub(crate) async fn get_for_startup( &self, ) -> std::result::Result { diff --git a/crates/registry-breg/src/postgres/context.rs b/crates/registry-breg/src/postgres/context.rs index 1d0334d95e..c10f77ae80 100644 --- a/crates/registry-breg/src/postgres/context.rs +++ b/crates/registry-breg/src/postgres/context.rs @@ -9,6 +9,7 @@ use registry_platform_canonical_json::canonicalize_json; use serde_json::{json, Value}; use time::{format_description::well_known::Rfc3339, OffsetDateTime}; use tokio_postgres::types::Type; +use tokio_postgres::IsolationLevel; use uuid::Uuid; use crate::contract::{BoundaryOperator, Operation}; @@ -56,6 +57,7 @@ pub(crate) struct ActionClaimContext { principal: String, access_profile: String, purpose: Option, + target_memberships: BTreeMap>, result_effects: BTreeSet, audit_context: Option, task_grant: Option, @@ -75,6 +77,7 @@ impl ActionClaimContext { principal, access_profile, purpose, + target_memberships: BTreeMap::new(), result_effects, audit_context: None, task_grant: None, @@ -84,6 +87,35 @@ impl ActionClaimContext { Ok(context) } + pub(crate) fn with_target_memberships( + mut self, + memberships: BTreeMap>, + ) -> Self { + self.target_memberships = memberships; + self + } + + pub(crate) fn locks_membership(&self) -> bool { + !self.target_memberships.is_empty() + } + + pub(crate) fn is_membership_source(&self, entity: &str) -> bool { + self.target_memberships + .values() + .flatten() + .any(|boundary| boundary.membership_entity == entity) + } + + pub(crate) fn target_membership( + &self, + entity: &str, + ) -> &[crate::model::CompiledMembershipBoundary] { + self.target_memberships + .get(entity) + .map(Vec::as_slice) + .unwrap_or_default() + } + /// Name the issuer that verified the caller. Its keys and proposals are /// recorded under it. An issuer in the engine's reserved namespace is /// refused. @@ -319,6 +351,9 @@ pub struct ClaimContext { recipients: BTreeSet, write_attribution: Option, caller_issuer: Option, + /// The caller's canonical row boundaries for each Record type a direct + /// write may reference, resolved from the same verified claims. + reference_row_boundaries: BTreeMap, } #[derive(Clone, Debug, Eq, PartialEq)] @@ -414,6 +449,36 @@ impl ClaimContext { &self.recipients } + /// Add the caller's context for a Record type this write may reference. + /// It must be the same caller: principal, profile and purpose match. + pub fn with_reference_context(mut self, reference: &ClaimContext) -> Result { + if reference.principal != self.principal + || reference.access_profile != self.access_profile + || reference.purpose != self.purpose + { + return Err(invalid_context()); + } + self.reference_row_boundaries.insert( + reference.entity_id.clone(), + reference.canonical_row_boundaries.clone(), + ); + Ok(self) + } + + /// The caller's canonical row boundaries on an explicitly admitted + /// reference target, including when it is the written Record type. + #[must_use] + pub fn reference_row_boundaries(&self, entity_id: &str) -> Option<&str> { + self.reference_row_boundaries + .get(entity_id) + .map(String::as_str) + } + + #[must_use] + pub fn canonical_row_boundaries(&self) -> &str { + &self.canonical_row_boundaries + } + pub(crate) fn with_task_grant( mut self, grant: crate::task_grant::TaskGrantBinding, @@ -508,6 +573,7 @@ impl ClaimContext { recipients: BTreeSet::new(), write_attribution: None, caller_issuer: None, + reference_row_boundaries: BTreeMap::new(), }) } @@ -544,6 +610,7 @@ impl ClaimContext { recipients: BTreeSet::new(), write_attribution: None, caller_issuer: None, + reference_row_boundaries: BTreeMap::new(), }) } @@ -617,6 +684,25 @@ impl ClaimContext { entity: &crate::model::CompiledEntity, row: &serde_json::Map, record_id: Uuid, + ) -> Result { + self.authorizes_record_snapshot_at(entity, row, record_id, false) + } + + pub(crate) fn authorizes_record_snapshot_before_allocation( + &self, + entity: &crate::model::CompiledEntity, + row: &serde_json::Map, + record_id: Uuid, + ) -> Result { + self.authorizes_record_snapshot_at(entity, row, record_id, true) + } + + fn authorizes_record_snapshot_at( + &self, + entity: &crate::model::CompiledEntity, + row: &serde_json::Map, + record_id: Uuid, + before_allocation: bool, ) -> Result { self.validate()?; if entity.id != self.entity_id { @@ -625,13 +711,23 @@ impl ClaimContext { // A state the profile may not see is outside its boundary, as the // restrictive disclosure policies would refuse it. A state that // cannot be evaluated counts as withheld. - if crate::disclosure::plan(entity, &self.access_profile) - .withholds_record(row) - .unwrap_or(true) - { + let disclosure = crate::disclosure::plan(entity, &self.access_profile); + let withheld = if before_allocation { + disclosure.withholds_record_before_allocation(row) + } else { + disclosure.withholds_record(row) + }; + if withheld.unwrap_or(true) { return Ok(false); } - snapshot_matches_boundaries(entity, row, record_id, &self.row_boundaries) + snapshot_matches_selected_boundaries( + entity, + row, + record_id, + self.row_boundaries + .iter() + .filter(|boundary| !before_allocation || !is_allocated_field(entity, boundary)), + ) } } @@ -727,6 +823,7 @@ pub(crate) struct ImmediateActionTargetContext { lock_only: bool, application_id: Option, target_row_boundaries: Vec, + membership_boundaries: Vec, timer: Option, canonical_context: String, } @@ -801,6 +898,10 @@ impl ImmediateActionTargetContext { &target_boundaries, &target_grant.row_boundaries, )?; + let membership_boundaries = action_claims.target_membership(&binding.target_entity_id); + if membership_boundaries != target_grant.membership_boundaries { + return Err(invalid_context()); + } let mut context = Self { action_id: binding.action_id, contract_fingerprint: binding.contract_fingerprint, @@ -817,6 +918,7 @@ impl ImmediateActionTargetContext { lock_only: binding.lock_only, application_id: binding.application_id, target_row_boundaries: target_boundaries, + membership_boundaries: membership_boundaries.to_vec(), timer: None, canonical_context: String::new(), }; @@ -925,6 +1027,7 @@ impl ImmediateActionTargetContext { lock_only: binding.lock_only, application_id: binding.application_id, target_row_boundaries: Vec::new(), + membership_boundaries: Vec::new(), timer: Some(TimerActionTargetAuthority { timer_id: timer.id.clone(), target_input_id: None, @@ -1041,6 +1144,7 @@ impl ImmediateActionTargetContext { lock_only: binding.lock_only, application_id: binding.application_id, target_row_boundaries: Vec::new(), + membership_boundaries: Vec::new(), timer: Some(TimerActionTargetAuthority { timer_id: timer.id.clone(), target_input_id: target_input_id.map(str::to_owned), @@ -1061,11 +1165,41 @@ impl ImmediateActionTargetContext { Ok(context) } + pub(crate) fn membership_boundaries(&self) -> &[crate::model::CompiledMembershipBoundary] { + &self.membership_boundaries + } + #[must_use] pub(crate) fn canonical_context(&self) -> &str { &self.canonical_context } + pub(crate) fn authorize_create_before_allocation( + &self, + entity: &crate::model::CompiledEntity, + row: &serde_json::Map, + record_id: Uuid, + ) -> Result<()> { + self.validate()?; + if self.operation != Operation::Create + || entity.id != self.target_entity_id + || record_id != self.target_record_id + { + return Err(invalid_context()); + } + if !snapshot_matches_selected_boundaries( + entity, + row, + record_id, + self.target_row_boundaries + .iter() + .filter(|boundary| !is_allocated_field(entity, boundary)), + )? { + return Err(invalid_context()); + } + Ok(()) + } + pub(crate) fn authorize_rows( &self, target_entity: &crate::model::CompiledEntity, @@ -1311,6 +1445,7 @@ pub(crate) struct ImmediateActionLinkContext { target_entity_id: String, target_record_id: Uuid, target_row_boundaries: Vec, + membership_boundaries: Vec, canonical_context: String, } @@ -1383,6 +1518,10 @@ impl ImmediateActionLinkContext { &target_boundaries, &target_grant.row_boundaries, )?; + let membership_boundaries = action_claims.target_membership(&binding.target_entity_id); + if membership_boundaries != target_grant.membership_boundaries { + return Err(invalid_context()); + } let mut context = Self { action_id: binding.action_id, contract_fingerprint: binding.contract_fingerprint, @@ -1395,6 +1534,7 @@ impl ImmediateActionLinkContext { target_entity_id: binding.target_entity_id, target_record_id: binding.target_record_id, target_row_boundaries: target_boundaries, + membership_boundaries: membership_boundaries.to_vec(), canonical_context: String::new(), }; context.canonical_context = Self::canonicalize(&context)?; @@ -1402,6 +1542,10 @@ impl ImmediateActionLinkContext { Ok(context) } + pub(crate) fn membership_boundaries(&self) -> &[crate::model::CompiledMembershipBoundary] { + &self.membership_boundaries + } + #[must_use] pub(crate) fn canonical_context(&self) -> &str { &self.canonical_context @@ -1701,6 +1845,25 @@ pub(crate) fn snapshot_matches_boundaries( row: &serde_json::Map, record_id: Uuid, boundaries: &[RowBoundaryContext], +) -> Result { + snapshot_matches_selected_boundaries(entity, row, record_id, boundaries) +} + +fn is_allocated_field( + entity: &crate::model::CompiledEntity, + boundary: &RowBoundaryContext, +) -> bool { + entity + .fields + .get(boundary.field()) + .is_some_and(|field| field.generate.is_some()) +} + +fn snapshot_matches_selected_boundaries<'a>( + entity: &crate::model::CompiledEntity, + row: &serde_json::Map, + record_id: Uuid, + boundaries: impl IntoIterator, ) -> Result { for boundary in boundaries { let (actual, field_type) = if boundary.field() == entity.canonical_id.id { @@ -1922,21 +2085,7 @@ impl GuardedTransaction<'_> { /// outruns the budget fails its read instead of holding the shared /// Registry lock and a pooled connection for an unbounded time. pub(crate) async fn set_statement_budget(&self, budget: Duration) -> Result<()> { - if budget.is_zero() || budget > Duration::from_secs(30) { - return Err(PostgresKernelError::Configuration( - "statement budget must be between 1 millisecond and 30 seconds", - )); - } - let budget_millis = i32::try_from(budget.as_millis()).map_err(|_| { - PostgresKernelError::Configuration("statement budget is outside PostgreSQL bounds") - })?; - self.transaction - .execute( - "SELECT set_config('statement_timeout', $1::text, true)", - &[&format!("{budget_millis}ms")], - ) - .await?; - Ok(()) + set_transaction_statement_budget(&self.transaction, budget).await } pub async fn commit(self) -> Result<()> { @@ -1982,6 +2131,27 @@ impl GuardedTransaction<'_> { } } +pub(crate) async fn set_transaction_statement_budget( + transaction: &Transaction<'_>, + budget: Duration, +) -> Result<()> { + if budget.is_zero() || budget > Duration::from_secs(30) { + return Err(PostgresKernelError::Configuration( + "statement budget must be between 1 millisecond and 30 seconds", + )); + } + let budget_millis = i32::try_from(budget.as_millis()).map_err(|_| { + PostgresKernelError::Configuration("statement budget is outside PostgreSQL bounds") + })?; + transaction + .execute( + "SELECT set_config('statement_timeout', $1::text, true)", + &[&format!("{budget_millis}ms")], + ) + .await?; + Ok(()) +} + #[derive(Debug)] pub(crate) enum RegistryLockFailure { Timeout, @@ -2014,7 +2184,17 @@ pub(crate) async fn begin_registry_transaction<'a>( lock_timeout: Duration, expected: &ExpectedRegistryIdentity, ) -> Result> { - begin_registry_transaction_with_reason(client, lock_key, lock_timeout, expected) + begin_registry_transaction_at_isolation(client, lock_key, lock_timeout, expected, None).await +} + +async fn begin_registry_transaction_at_isolation<'a>( + client: &'a mut Client, + lock_key: RegistryLockKey, + lock_timeout: Duration, + expected: &ExpectedRegistryIdentity, + isolation: Option, +) -> Result> { + begin_registry_transaction_inner(client, lock_key, lock_timeout, expected, false, isolation) .await .map_err(|error| match error { RegistryTransactionError::Kernel(error) => error, @@ -2035,7 +2215,7 @@ pub(crate) async fn begin_registry_transaction_with_reason<'a>( lock_timeout: Duration, expected: &ExpectedRegistryIdentity, ) -> std::result::Result, RegistryTransactionError> { - begin_registry_transaction_inner(client, lock_key, lock_timeout, expected, false).await + begin_registry_transaction_inner(client, lock_key, lock_timeout, expected, false, None).await } pub(crate) async fn begin_registry_read_transaction_with_reason<'a>( @@ -2044,7 +2224,7 @@ pub(crate) async fn begin_registry_read_transaction_with_reason<'a>( lock_timeout: Duration, expected: &ExpectedRegistryIdentity, ) -> std::result::Result, RegistryTransactionError> { - begin_registry_transaction_inner(client, lock_key, lock_timeout, expected, true).await + begin_registry_transaction_inner(client, lock_key, lock_timeout, expected, true, None).await } async fn begin_registry_transaction_inner<'a>( @@ -2053,6 +2233,7 @@ async fn begin_registry_transaction_inner<'a>( lock_timeout: Duration, expected: &ExpectedRegistryIdentity, read_only: bool, + isolation: Option, ) -> std::result::Result, RegistryTransactionError> { expected.validate()?; if lock_timeout.is_zero() || lock_timeout > Duration::from_secs(30) { @@ -2061,7 +2242,16 @@ async fn begin_registry_transaction_inner<'a>( ) .into()); } - let transaction = client.transaction().await?; + let transaction = match isolation { + Some(level) => { + client + .build_transaction() + .isolation_level(level) + .start() + .await? + } + None => client.transaction().await?, + }; if read_only { transaction .batch_execute("SET TRANSACTION READ ONLY") @@ -2098,6 +2288,15 @@ async fn begin_registry_transaction_inner<'a>( _ => RegistryLockFailure::Database, }) })?; + verify_registry_transaction_identity(&transaction, lock_key, expected).await?; + Ok(GuardedTransaction { transaction }) +} + +pub(crate) async fn verify_registry_transaction_identity( + transaction: &tokio_postgres::Transaction<'_>, + lock_key: RegistryLockKey, + expected: &ExpectedRegistryIdentity, +) -> std::result::Result<(), RegistryTransactionError> { let state = transaction .query_typed_opt( "SELECT package_id, database_id, active_package_digest, @@ -2119,11 +2318,11 @@ async fn begin_registry_transaction_inner<'a>( if !ready { return Err(PostgresKernelError::RegistryUnavailable.into()); } - let timer_protocol = super::timer::read_timer_protocol(&*transaction).await?; + let timer_protocol = super::timer::read_timer_protocol(transaction).await?; if timer_protocol.protocol_version != super::timer::SUPPORTED_TIMER_PROTOCOL_VERSION { return Err(RegistryTransactionError::TimerProtocolUnsupported); } - Ok(GuardedTransaction { transaction }) + Ok(()) } /// Starts a record transaction and installs authority only after the shared @@ -2134,9 +2333,29 @@ pub async fn begin_record_transaction<'a>( lock_timeout: Duration, expected: &ExpectedRegistryIdentity, claims: &ClaimContext, +) -> Result> { + begin_record_transaction_for_write(client, lock_key, lock_timeout, expected, claims, false) + .await +} + +pub(crate) async fn begin_record_transaction_for_write<'a>( + client: &'a mut Client, + lock_key: RegistryLockKey, + lock_timeout: Duration, + expected: &ExpectedRegistryIdentity, + claims: &ClaimContext, + locks_membership: bool, ) -> Result> { claims.validate()?; - let guarded = begin_registry_transaction(client, lock_key, lock_timeout, expected).await?; + let isolation = locks_membership.then_some(IsolationLevel::ReadCommitted); + let guarded = begin_registry_transaction_at_isolation( + client, + lock_key, + lock_timeout, + expected, + isolation, + ) + .await?; let transaction = guarded.transaction(); // A JSON array of strings; `[]` for a client no organization lists. let recipients = serde_json::to_string(&claims.recipients).map_err(|_| invalid_context())?; @@ -2170,9 +2389,29 @@ pub async fn begin_action_transaction<'a>( lock_timeout: Duration, expected: &ExpectedRegistryIdentity, claims: &ActionClaimContext, +) -> Result> { + begin_action_transaction_for_write(client, lock_key, lock_timeout, expected, claims, false) + .await +} + +pub(crate) async fn begin_action_transaction_for_write<'a>( + client: &'a mut Client, + lock_key: RegistryLockKey, + lock_timeout: Duration, + expected: &ExpectedRegistryIdentity, + claims: &ActionClaimContext, + locks_membership: bool, ) -> Result> { claims.validate()?; - let guarded = begin_registry_transaction(client, lock_key, lock_timeout, expected).await?; + let isolation = locks_membership.then_some(IsolationLevel::ReadCommitted); + let guarded = begin_registry_transaction_at_isolation( + client, + lock_key, + lock_timeout, + expected, + isolation, + ) + .await?; let transaction = guarded.transaction(); transaction .execute( @@ -2691,10 +2930,10 @@ mod tests { "disclosureConditions":{"hide": {"when":[{"type":"field-equals","field":"level","value":"secret"}], "withhold":"record","exemptProfiles":["officer"]}}}}, "accessProfiles":{ - "clerk": {"default":true,"principalClaim":"registry_principal","requiredScopes":"unrestricted", + "clerk": {"default":true,"principalClaim":"registry_principal","requiredScopes":["records:write"], "permissions":{"records":[{"recordType":"entry","operations":["get","create"], "rowBoundaries":"unrestricted","readableFields":["level"],"writableFields":["level"]}]}}, - "officer": {"principalClaim":"registry_principal","requiredScopes":"unrestricted", + "officer": {"principalClaim":"registry_principal","requiredScopes":["records:write"], "permissions":{"records":[{"recordType":"entry","operations":["get","create"], "rowBoundaries":"unrestricted","readableFields":["level"],"writableFields":["level"]}]}}}}); let project = crate::contract::parse_project_json(&serde_json::to_vec(&source).unwrap()) @@ -3175,7 +3414,7 @@ mod tests { "accessProfiles":{"contact-registrar": { "default":true, "principalClaim":"registry_principal", - "requiredScopes":"unrestricted", + "requiredScopes":["records:write"], "requiredPurposes":["contact-registration"], "permissions":{"actions":[{ "action":"rename-household-local", 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/postgres/interlock.rs b/crates/registry-breg/src/postgres/interlock.rs index 23a1a5c55d..b6ca9b2fc1 100644 --- a/crates/registry-breg/src/postgres/interlock.rs +++ b/crates/registry-breg/src/postgres/interlock.rs @@ -109,6 +109,7 @@ pub(crate) struct PackageDdlStatement<'a> { pub checksum: &'a str, pub kind: DdlStatementKind, pub pattern_field: Option<(&'a str, &'a str)>, + pub membership_source: Option<&'a str>, pub ordinal: i32, } @@ -445,6 +446,7 @@ impl DedicatedApplyConnection { statement.sql, statement.kind, statement.pattern_field, + statement.membership_source, runtime_role, ) .await @@ -898,6 +900,7 @@ impl DedicatedApplyConnection { statement.sql, statement.kind, statement.pattern_field, + statement.membership_source, runtime_role, ) .await?; @@ -3070,6 +3073,7 @@ async fn execute_initial_package_ddl_in( statement.sql, statement.kind, statement.pattern_field, + statement.membership_source, runtime_role, ) .await?; @@ -3080,6 +3084,7 @@ async fn execute_initial_package_ddl_in( statement.sql, statement.kind, statement.pattern_field, + statement.membership_source, runtime_role, ) .await?; @@ -5086,6 +5091,7 @@ mod tests { checksum: "", kind, pattern_field: None, + membership_source: None, ordinal: 0, }; assert!(compiler_statement_runs_after_reviewed_steps(&statement( @@ -5171,7 +5177,7 @@ mod tests { "accessProfiles": {"caseworker": { "default": true, "principalClaim": "principal", - "requiredScopes": "unrestricted", + "requiredScopes": ["records:write"], "permissions": {"records": [{ "recordType": "case", "rowBoundaries": "unrestricted", diff --git a/crates/registry-breg/src/postgres/mod.rs b/crates/registry-breg/src/postgres/mod.rs index b861eadbed..a163c8f926 100644 --- a/crates/registry-breg/src/postgres/mod.rs +++ b/crates/registry-breg/src/postgres/mod.rs @@ -56,7 +56,8 @@ pub use config::{ TlsPolicy, }; pub(crate) use context::{ - begin_action_transaction, begin_timer_action_transaction, + begin_action_transaction, begin_action_transaction_for_write, + begin_record_transaction_for_write, begin_timer_action_transaction, create_row_matches_request_boundaries, snapshot_matches_boundaries, validate_invoke_target_boundaries, ActionClaimContext, ImmediateActionLinkBinding, ImmediateActionLinkContext, ImmediateActionTargetBinding, ImmediateActionTargetContext, @@ -70,7 +71,8 @@ pub use context::{ }; pub(crate) use context::{ begin_registry_read_transaction_with_reason, begin_registry_transaction, - begin_registry_transaction_with_reason, RegistryLockFailure, RegistryTransactionError, + begin_registry_transaction_with_reason, set_transaction_statement_budget, + verify_registry_transaction_identity, RegistryLockFailure, RegistryTransactionError, }; pub(crate) use context::{install_spatial_bbox_context, validate_field_value, SpatialBboxContext}; pub use failure::PostgresFailure; @@ -103,7 +105,7 @@ pub(crate) use migration_ledger::{ MigrationLedgerEntry, MigrationLedgerStep, MigrationLedgerStepKind, }; pub use migration_ledger::{ActivationPlanKind, RoleMode}; -pub(crate) use mutation::api_boundary; +pub(crate) use mutation::{api_boundary, ActionTargetMembershipObservation}; pub use mutation::{ IngestionChunkSubmitInput, IngestionRunCreateInput, IngestionRunListQuery, IngestionServiceError, PostgresRecordMutationService, @@ -231,7 +233,6 @@ pub use roles::{ spatial_bbox_role, verify_btree_gist, verify_migration_role, verify_postgis, RuntimeWriteAuthority, SqlIdentifier, MIN_POSTGIS_MAJOR, MIN_POSTGIS_MINOR, }; -pub(crate) use schema::compiled_pattern_field; pub use schema::install_compiled_schema; #[cfg(feature = "postgres-test")] #[doc(hidden)] @@ -239,6 +240,7 @@ pub use schema::reconcile_compiled_runtime_acl_for_test; pub(crate) use schema::verify_postgres_17_or_newer; #[cfg(all(feature = "runtime", feature = "tooling"))] pub(crate) use schema::PreparedSchemaTestCatalogVerifier; +pub(crate) use schema::{compiled_membership_source, compiled_pattern_field}; #[cfg(all(feature = "runtime", feature = "tooling"))] pub use schema::{ prepare_schema_test_database_with_connections, PreparedSchemaTestDatabase, SchemaMeasurement, @@ -407,6 +409,10 @@ pub enum PostgresKernelError { FieldPatternSyntax { entity_id: String, field_id: String }, #[error("existing rows do not conform to a persisted field pattern")] FieldPatternExistingRows { entity_id: String, field_id: String }, + /// Authored identifiers only; key and principal values never cross this + /// boundary. + #[error("existing active membership rows repeat a key and principal")] + MembershipDuplicateLiveRows { entity_id: String }, /// Authored record identifiers only; field values never cross this boundary. #[error("field-encryption backfill would collide blind indexes of existing records")] FieldEncryptionBlindCollision { diff --git a/crates/registry-breg/src/postgres/mutation.rs b/crates/registry-breg/src/postgres/mutation.rs index 5c7e99c70a..255742087c 100644 --- a/crates/registry-breg/src/postgres/mutation.rs +++ b/crates/registry-breg/src/postgres/mutation.rs @@ -37,6 +37,13 @@ use super::{ pub(super) const REQUEST_ACTION_TIMEOUT: Duration = Duration::from_secs(30); +pub(crate) enum ActionTargetMembershipObservation { + Authorized, + OutsideBoundary, + Withheld, + Missing, +} + fn action_timeout_for_http_deadline(http_request_timeout: Duration) -> Duration { REQUEST_ACTION_TIMEOUT.min(http_request_timeout) } @@ -65,6 +72,8 @@ pub struct PostgresRecordMutationService { proposal_read_barrier_for_test: Option, #[cfg(feature = "postgres-test")] task_context_barrier_for_test: Option, + #[cfg(feature = "postgres-test")] + automatic_apply_barrier_for_test: Option, evidence_timeout: Duration, evidence_evaluator: Option>, review_result_source: Option>, @@ -434,6 +443,7 @@ impl PostgresRecordMutationService { deadline, self.coordinator.execute_immediate_action( guard.client(), + &self.pool, &self.registry, input, &claims, @@ -562,6 +572,96 @@ impl PostgresRecordMutationService { result } + pub(crate) async fn observe_action_target_membership( + &self, + context: &AuthorizedRequestContext, + entity: &crate::model::CompiledEntity, + record: uuid::Uuid, + revision: i64, + memberships: &[crate::model::CompiledMembershipBoundary], + disclosed_fields: &std::collections::BTreeSet, + ) -> Result { + let claims = strict_claim_context(&self.registry, context, &entity.id)?; + let client = self + .pool + .get() + .await + .map_err(|_| MutationError::Unavailable)?; + let mut guard = QueryCancellationGuard::new(self.pool.clone(), client); + let guarded = super::begin_record_transaction( + guard.client(), + self.lock_key, + self.lock_timeout, + &self.expected, + &claims, + ) + .await + .map_err(|_| MutationError::Unavailable)?; + let predicates = memberships + .iter() + .map(|boundary| { + let probe = crate::membership::RowProbe { + function: crate::membership::target_function_name( + claims.access_profile(), + &boundary.membership_entity, + ), + field: boundary.field.clone(), + form: crate::membership::RowProbeForm::PerKey, + }; + if probe.field == entity.canonical_id.id { + probe.sql("record_id") + } else { + probe.sql(&format!( + "\"{}\"", + entity.fields[&probe.field].physical_name + )) + } + }) + .collect::>() + .join(" AND "); + let disclosure = crate::disclosure::plan(entity, claims.access_profile()); + let mut withholds = disclosure + .conditions() + .iter() + .filter_map(|condition| { + let crate::model::DisclosureWithhold::Fields(fields) = &condition.withhold else { + return None; + }; + (!fields.is_disjoint(disclosed_fields)).then(|| { + crate::disclosure::when_sql(entity, &condition.when, &|field| { + format!("\"{}\"", entity.fields[field].physical_name) + }) + }) + }) + .collect::>(); + withholds.push("false".into()); + let withheld = withholds.join(" OR "); + // Check the Action's boundary on the same revision as the ordinary + // GET. Evaluate field withholding only for an admitted target. + let sql = format!( + "SELECT CASE WHEN ({predicates}) IS NOT TRUE THEN false + WHEN ({withheld}) IS TRUE THEN NULL + ELSE true END + FROM registry_data.\"{}\" WHERE record_id=$1 AND record_revision=$2 AND record_lifecycle='active'", + entity.physical_table, + ); + let row = guarded + .transaction() + .query_opt(&sql, &[&record, &revision]) + .await + .map_err(|_| MutationError::Unavailable)?; + drop(guarded); + guard.disarm(); + let Some(row) = row else { + return Ok(ActionTargetMembershipObservation::Missing); + }; + match row.try_get(0).map_err(|_| MutationError::Unavailable)? { + Some(true) => Ok(ActionTargetMembershipObservation::Authorized), + Some(false) => Ok(ActionTargetMembershipObservation::OutsideBoundary), + None => Ok(ActionTargetMembershipObservation::Withheld), + } + } + pub async fn action_target_conditions( &self, input: ActionTargetConditionsInput<'_>, @@ -660,6 +760,8 @@ impl PostgresRecordMutationService { proposal_read_barrier_for_test: None, #[cfg(feature = "postgres-test")] task_context_barrier_for_test: None, + #[cfg(feature = "postgres-test")] + automatic_apply_barrier_for_test: None, evidence_timeout: REQUEST_ACTION_TIMEOUT, evidence_evaluator: None, review_result_source: None, @@ -706,6 +808,20 @@ impl PostgresRecordMutationService { self } + /// Pause the automatic worker after it has read the Proposal and before + /// it applies it, so a test can land another write in between. + #[cfg(feature = "postgres-test")] + #[must_use] + #[doc(hidden)] + pub fn with_automatic_apply_barrier_for_test( + mut self, + loaded: Arc, + resume: Arc, + ) -> Self { + self.automatic_apply_barrier_for_test = Some(ProposalReadBarrier { loaded, resume }); + self + } + #[cfg(feature = "postgres-test")] #[must_use] #[doc(hidden)] @@ -1905,6 +2021,7 @@ impl PostgresRecordMutationService { return self .finish_ingestion_submission( context, + correlation, &input, self.coordinator .execute_batch_with_fault(&mut writer, request, fault) @@ -1914,6 +2031,7 @@ impl PostgresRecordMutationService { } self.finish_ingestion_submission( context, + correlation, &input, self.coordinator.execute_batch(&mut writer, request).await, ) @@ -2011,6 +2129,7 @@ impl PostgresRecordMutationService { async fn finish_ingestion_submission( &self, context: &AuthorizedRequestContext, + correlation: &RequestCorrelation, input: &IngestionChunkSubmitInput, outcome: Result, ) -> Result { @@ -2055,6 +2174,13 @@ impl PostgresRecordMutationService { IngestionAttemptOutcome::InvalidItem, Some(IngestionServiceError::RequestInvalid), ), + MutationError::MembershipPreconditionFailed + | MutationError::MembershipWriteOutsideBoundary => { + crate::correlation::record_refusal_check( + registry_platform_authcommon::FailedCheck::Membership, correlation, + ); + (IngestionAttemptOutcome::Refused, Some(IngestionServiceError::PreconditionFailed)) + } MutationError::PreconditionFailed | MutationError::ProposalTargetChanged | MutationError::FieldGuardFailed { .. } @@ -2063,6 +2189,9 @@ impl PostgresRecordMutationService { | MutationError::Conflict | MutationError::ProposalUniqueConflict | MutationError::ProposalRejected + | MutationError::ProposalSubjectNotCaller + | MutationError::ProposalSubjectChanged + | MutationError::ProposalMessageLimitReached | MutationError::AuthorizationRefused(_) // Ingestion consumes the batch mutation outcome through // its run protocol. Its item refusal remains the generic @@ -2077,6 +2206,7 @@ impl PostgresRecordMutationService { | MutationError::IdempotencyExpired | MutationError::Unavailable | MutationError::RetryableConflict + | MutationError::MembershipKeyDrift | MutationError::CommitUnresolved | MutationError::MigrationLockHeld | MutationError::PostureMismatch { .. } @@ -2091,6 +2221,8 @@ impl PostgresRecordMutationService { | MutationError::AttachmentSlotWriteOnce | MutationError::AttachmentTooLarge | MutationError::AttachmentLimitReached + | MutationError::FormUndeclared + | MutationError::FormLimitReached | MutationError::AttachmentRequired { .. } | MutationError::AttachmentVerificationPending { .. } | MutationError::AttachmentVerificationRejected { .. } @@ -2419,6 +2551,20 @@ fn strict_claim_context( None => Ok(claims), }) .map_err(|_| MutationError::InvalidRequest) + .and_then(|claims| { + context + .reference_contexts() + // A target claim that fails this type's compiled boundary makes + // that type unavailable. Only a reference to it is refused. + .filter_map(|(target, reference)| { + strict_claim_context(registry, reference, target).ok() + }) + .try_fold(claims, |claims, reference| { + claims + .with_reference_context(&reference) + .map_err(|_| MutationError::InvalidRequest) + }) + }) } /// The claim context of a direct Create, Patch, Batch or Tombstone, which @@ -2448,7 +2594,11 @@ fn strict_action_context( context.purpose().map(str::to_owned), context.result_effects().clone(), ) - .map(|claims| claims.with_audit_context(context.audit_context().cloned())) + .map(|claims| { + claims + .with_target_memberships(context.target_memberships().clone()) + .with_audit_context(context.audit_context().cloned()) + }) .and_then(|claims| claims.with_verified_issuer(context.caller_issuer())) .and_then(|claims| match context.task_grant() { Some(binding) => claims.with_task_grant(binding.clone()), @@ -2606,6 +2756,101 @@ mod ingestion_context_tests { .expect("the fixture context is exact") } + #[test] + fn a_same_type_probe_requires_an_admitted_target_context() { + use crate::subject_access_log::ACCESS_REASON_HEADER; + use axum::http::{HeaderMap, HeaderValue}; + + let project = parse_project_json(CONTEXT_FIXTURE.as_bytes()).unwrap(); + let registry = compile_project(&project, &[], CompileProfile::Authoring).unwrap(); + let context = AuthorizedRequestContext::new( + Some("agent".to_owned()), + Some("review".to_owned()), + "operator".to_owned(), + vec![VerifiedRowBoundary::equals_for_test("tenant", "tenant-a")], + ) + .with_access_reason_requirement(true); + let mut write = context + .clone() + .with_reference_context("entry", context.clone()); + let check = |context: &AuthorizedRequestContext, expected| { + let claims = strict_claim_context(®istry, context, "entry").unwrap(); + assert!(!claims.row_boundaries().is_empty()); + assert_eq!(claims.reference_row_boundaries("entry"), expected); + }; + + let mut headers = HeaderMap::new(); + assert!(write.bind_access_reason(&headers).is_err()); + check(&write, None); + + headers.insert(ACCESS_REASON_HEADER, HeaderValue::from_static("!")); + assert!(write.bind_access_reason(&headers).is_err()); + check(&write, None); + + headers.insert(ACCESS_REASON_HEADER, HeaderValue::from_static("cmV2aWV3")); + let mut absent_target = context; + absent_target.bind_access_reason(&headers).unwrap(); + check(&absent_target, None); + + write.bind_access_reason(&headers).unwrap(); + let boundaries = fixture_claims(); + check(&write, Some(boundaries.canonical_row_boundaries())); + } + + #[test] + fn an_invalid_target_context_does_not_invalidate_other_record_types() { + let mut project: Value = serde_json::from_str(CONTEXT_FIXTURE).unwrap(); + project["recordTypes"]["source"] = json!({ + "primaryDataset":"test-dataset","route":"sources","mutationMode":"mutable", + "classification":"internal","fields":[ + {"id":"entry","type":"reference","target":"entry","classification":"internal"}, + {"id":"related","type":"reference","target":"related","classification":"internal"} + ] + }); + project["recordTypes"]["related"] = project["recordTypes"]["entry"].clone(); + project["recordTypes"]["related"]["route"] = json!("related"); + project["recordTypes"]["entry"]["fields"][0]["maximumLength"] = json!(4); + project["accessProfiles"]["operator"]["requiredScopes"] = json!(["records:write"]); + project["accessProfiles"]["operator"]["permissions"]["records"] + .as_array_mut() + .unwrap() + .extend([ + json!({"recordType":"source","operations":["create"], + "writableFields":["entry","related"],"rowBoundaries":"unrestricted"}), + json!({"recordType":"related","operations":["reference"], + "rowBoundaries":"unrestricted"}), + ]); + let project = parse_project_json(&serde_json::to_vec(&project).unwrap()).unwrap(); + let registry = compile_project(&project, &[], CompileProfile::Authoring) + .expect("the reference project compiles"); + let context = |row_boundaries| { + AuthorizedRequestContext::new( + Some("agent".to_owned()), + Some("review".to_owned()), + "operator".to_owned(), + row_boundaries, + ) + }; + let entry = |tenant| context(vec![VerifiedRowBoundary::equals_for_test("tenant", tenant)]); + + // The claim has the expected cardinality, but exceeds this type's + // field bound. Validation of the written type must still be strict. + assert!(strict_claim_context(®istry, &entry("area"), "entry").is_ok()); + assert!(matches!( + strict_claim_context(®istry, &entry("tenant-a"), "entry"), + Err(MutationError::InvalidRequest) + )); + + let write = context(Vec::new()) + .with_reference_context("entry", entry("tenant-a")) + .with_reference_context("related", context(Vec::new())); + let claims = strict_claim_context(®istry, &write, "source") + .expect("an unavailable target is local to references to that type"); + assert_eq!(claims.reference_row_boundaries("entry"), None); + assert_eq!(claims.reference_row_boundaries("related"), Some("[]")); + assert_eq!(claims.canonical_row_boundaries(), "[]"); + } + fn grant(id: &str) -> TaskGrantBinding { serde_json::from_value(json!({ "grantId": id, diff --git a/crates/registry-breg/src/postgres/proposal.rs b/crates/registry-breg/src/postgres/proposal.rs index 2d658246c1..86d8156c22 100644 --- a/crates/registry-breg/src/postgres/proposal.rs +++ b/crates/registry-breg/src/postgres/proposal.rs @@ -6,12 +6,15 @@ use super::*; use crate::api::proposals::ReviewDocumentSource; use crate::api::proposals::{ProposalListQuery, ProposalMutationInput}; use crate::api::VerifiedRequestClaims; -use crate::model::{ProposalOperation, ProposalOwnership}; +use crate::model::{ProposalOperation, ProposalParty}; use crate::mutation::{link_readable, CheckedProposalTaskAuthority, ProposalApplyPreflight}; use crate::postgres::{begin_proposal_transaction, ProposalAuthority, ProposalAuthorityOperation}; use crate::proposal_store; use std::collections::{BTreeMap, BTreeSet}; +#[path = "proposal_messages.rs"] +mod messages; + const REVIEW_PROGRESS_LOOKUP_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(1); const REVIEW_PROGRESS_FINAL_READ_RESERVE: std::time::Duration = std::time::Duration::from_millis(250); @@ -24,19 +27,22 @@ struct ProposalReviewSnapshot { } // Keep status selection in the single candidate query before its scan bound. -// Caller ownership is exact here, so another holder's Proposal never reaches a -// per-candidate read; `$4` pairs each `$1` Action with the caller's owner -// reference, or NULL when that authority is not ownership-scoped. `$5` and `$6` +// Party binding is exact here, so another holder's Proposal never reaches a +// per-candidate read; `$4` and `$7` pair each `$1` Action with the caller's +// owner or subject reference, both NULL when that authority is bound to no +// party. `$5` and `$6` // are the caller's optional `action` and `state` filters: they only narrow rows // the collection authority already lists, so applying them here spends the scan // budget on candidates that can match without revealing anything further. -const PROPOSAL_LIST_CANDIDATES: &str = "SELECT p.proposal_id,p.action_id,p.workflow_revision,({open_ask}) AS ask_open FROM registry_internal.registry_proposal_state p +const PROPOSAL_LIST_CANDIDATES: &str = "SELECT p.proposal_id,p.action_id,p.workflow_revision,({open_ask}) AS ask_open,p.owner_reference,p.subject_reference FROM registry_internal.registry_proposal_state p WHERE p.action_id=ANY($1) AND ($2::uuid IS NULL OR p.proposal_id>$2) AND ($5::text IS NULL OR p.action_id=$5) AND ($6::text IS NULL OR p.state=$6) - AND EXISTS (SELECT 1 FROM unnest($1::text[],$4::text[]) AS a(action_id,owner_reference) + AND EXISTS (SELECT 1 FROM unnest($1::text[],$4::text[],$7::text[]) AS a(action_id,owner_reference,subject_reference) WHERE a.action_id=p.action_id - AND (a.owner_reference IS NULL OR a.owner_reference=p.owner_reference)) + AND ((a.owner_reference IS NULL AND a.subject_reference IS NULL) + OR a.owner_reference=p.owner_reference + OR a.subject_reference=p.subject_reference)) AND (NOT $3 OR (p.state='submitted' AND p.blocked_reason IS NULL AND EXISTS ( SELECT 1 FROM registry_internal.registry_proposal_submissions s LEFT JOIN registry_internal.registry_proposal_review_submissions review @@ -79,6 +85,7 @@ impl PostgresRecordMutationService { &vec![None::; actions.len()], &Option::::None, &Option::::None, + &vec![None::; actions.len()], ], ) .await @@ -244,7 +251,7 @@ impl PostgresRecordMutationService { return Ok(false); }; let result = async { - let (authority, etag) = { + let authority = { let mut client = tokio::time::timeout_at(deadline, self.pool.get()) .await .map_err(|_| MutationError::Unavailable)? @@ -273,19 +280,17 @@ impl PostgresRecordMutationService { ) .await .map_err(|_| MutationError::PreconditionFailed)?; - let document = proposal_store::load_document( - guarded.transaction(), - id, - proposal_store::DocumentLock::None, - ) - .await?; - let etag = self.coordinator.proposal_etag(&document, &authority)?; guarded .commit() .await .map_err(|_| MutationError::Unavailable)?; - (authority, etag) + authority }; + #[cfg(feature = "postgres-test")] + if let Some(barrier) = &self.automatic_apply_barrier_for_test { + barrier.loaded.notify_one(); + barrier.resume.notified().await; + } let correlation = crate::correlation::RequestCorrelation::breg_created(); let key = format!("breg-proposal-automatic-{job_id}"); self.proposal_mutation_with_deadline( @@ -295,7 +300,12 @@ impl PostgresRecordMutationService { operation: ProposalAuthorityOperation::Lifecycle(ProposalOperation::Apply), authority: &authority, idempotency_key: &key, - expected_etag: Some(&etag), + // The claimed lease, the submission version and the + // frozen effect digest fence this Apply inside its own + // transaction. A Proposal ETag read earlier would also + // fence on thread activity, which never changes what is + // applied. + expected_etag: None, input: None, submission_version: Some(frozen.version().get()), effect_digest: Some(frozen.effect_digest().as_str()), @@ -306,7 +316,9 @@ impl PostgresRecordMutationService { }), rebase_start_authority: None, attachment: None, + form: None, answer: None, + message: None, correlation: &correlation, human_identity: None, claims: None, @@ -413,6 +425,26 @@ impl PostgresRecordMutationService { authority, ) .await?; + // The admitting entry, party included, must still read this + // slot: the route chose it before the document was locked. + let readable = self + .registry + .actions() + .actions + .iter() + .find(|action| action.id == document.action_id) + .and_then(|action| match &action.execution { + crate::model::CompiledActionExecution::Proposal { proposal } => { + authority.permission(proposal) + } + crate::model::CompiledActionExecution::Immediate => None, + }) + .is_some_and(|grant| grant.readable_attachments.contains(slot)); + if !readable { + return Err(MutationError::AuthorizationRefused( + registry_platform_authcommon::FailedCheck::Visibility, + )); + } } if document.header.submission_version != i64::from(version) { return Err(MutationError::PreconditionFailed); @@ -603,20 +635,20 @@ impl PostgresRecordMutationService { pub(crate) async fn proposal_route_target( &self, id: Uuid, - ) -> Result, MutationError> { + ) -> Result)>, MutationError> { let deadline = tokio::time::Instant::now() + self.action_timeout; let client = tokio::time::timeout_at(deadline, self.pool.get()) .await .map_err(|_| MutationError::Unavailable)? .map_err(|_| MutationError::Unavailable)?; let mut guard = QueryCancellationGuard::new(self.pool.clone(), client); - let sql = "SELECT action_id, owner_reference FROM registry_internal.registry_proposal_state WHERE proposal_id=$1"; + let sql = "SELECT action_id, owner_reference, subject_reference FROM registry_internal.registry_proposal_state WHERE proposal_id=$1"; match tokio::time::timeout_at(deadline, guard.client().query_opt(sql, &[&id])).await { Ok(row) => { guard.disarm(); Ok(row .map_err(|_| MutationError::Unavailable)? - .map(|row| (row.get(0), row.get(1)))) + .map(|row| (row.get(0), row.get(1), row.get(2)))) } Err(_) => { guard.cancel_and_discard().await; @@ -625,13 +657,140 @@ impl PostgresRecordMutationService { } } - pub(crate) fn proposal_owner_matches( + /// The party match of the verified caller on one Proposal, from its + /// stored owner and subject references. + pub(crate) fn party_selection( + &self, + claims: &crate::api::VerifiedRequestClaims, + owner_reference: &str, + subject_reference: Option<&str>, + ) -> crate::api::proposals::PartySelection { + let Some(principal) = claims.principal() else { + return crate::api::proposals::PartySelection::Proposal { + owner: false, + subject: false, + }; + }; + crate::api::proposals::PartySelection::Proposal { + owner: self.coordinator.proposal_owner_reference( + self.coordinator.caller_issuer(claims.caller_issuer()), + principal, + ) == owner_reference, + subject: self.coordinator.proposal_subject_matches( + subject_reference, + principal, + crate::api::proposals::acts_for_self(claims), + ), + } + } + + /// The List authority that governs the caller on one candidate: the + /// profile's entry bound to no party, else its owner entry for a + /// Proposal the caller filed, else its subject entry. None when the + /// governing entry does not hold List. + fn governing_list_authority<'a>( + &self, + authorities: &'a [ProposalAuthority], + action_id: &str, + owner_reference: &str, + subject_reference: Option<&str>, + ) -> Option<&'a ProposalAuthority> { + let mut candidates = authorities + .iter() + .filter(|authority| authority.common.action_id() == action_id); + let first = candidates.clone().next()?; + let action = self + .registry + .actions() + .actions + .iter() + .find(|action| action.id == action_id)?; + let crate::model::CompiledActionExecution::Proposal { proposal } = &action.execution else { + return None; + }; + let person = authorities + .iter() + .filter(|authority| authority.common.action_id() == action_id) + .any(|authority| authority.person); + let parties = crate::api::proposals::PartySelection::Proposal { + owner: self.coordinator.proposal_owner_of(&first.common) == owner_reference, + subject: self.coordinator.proposal_subject_matches( + subject_reference, + first.common.principal(), + person, + ), + }; + let grant = crate::api::proposals::select_proposal_grant( + proposal, + first.common.access_profile(), + ProposalOperation::List, + parties, + )?; + candidates.find(|authority| authority.party == grant.party) + } + + /// Whether a `target` filter matches a Proposal for this authority. A + /// subject's filter matches only through the reference inputs its entry + /// reads, so it cannot learn a reference its projection hides. + fn target_filter_matches( + &self, + document: &proposal_store::ProposalDocument, + authority: &ProposalAuthority, + target: Uuid, + ) -> bool { + if authority.party != Some(ProposalParty::Subject) { + return document.input_targets.iter().any(|(_, id)| *id == target); + } + let Some(action) = self + .registry + .actions() + .actions + .iter() + .find(|action| action.id == document.action_id) + else { + return false; + }; + let crate::model::CompiledActionExecution::Proposal { proposal } = &action.execution else { + return false; + }; + let Some(permission) = authority.permission(proposal) else { + return false; + }; + let target = target.to_string(); + action.inputs.iter().any(|input| { + matches!( + input.field_type, + crate::contract::FieldTypeSource::Reference { .. } + ) && permission.readable_inputs.contains(&input.id) + && document + .input + .as_ref() + .and_then(|values| values.get(&input.id)) + .and_then(Value::as_str) + == Some(target.as_str()) + }) + } + + /// Whether the admitting entry's party matches the caller on the + /// Proposal. An entry bound to no party always does; the transaction + /// checks again. + pub(crate) fn proposal_party_matches( &self, authority: &ProposalAuthority, owner_reference: &str, + subject_reference: Option<&str>, ) -> bool { - authority.ownership != Some(ProposalOwnership::Caller) - || self.coordinator.proposal_owner_of(&authority.common) == owner_reference + party_admits( + authority.party, + || self.coordinator.proposal_owner_of(&authority.common) == owner_reference, + || { + self.coordinator.proposal_subject_matches( + subject_reference, + authority.common.principal(), + authority.person, + ) + }, + ) } pub(crate) async fn proposal_visible( @@ -1584,10 +1743,25 @@ impl PostgresRecordMutationService { let owner_references = authorities .iter() .map(|authority| { - (authority.ownership == Some(crate::model::ProposalOwnership::Caller)) + (authority.party == Some(ProposalParty::Owner)) .then(|| self.coordinator.proposal_owner_of(&authority.common)) }) .collect::>(); + // A subject authority lists only for a person acting for themselves; + // any other caller's subject entry matches no Proposal. + let subject_references = authorities + .iter() + .map(|authority| { + (authority.party == Some(ProposalParty::Subject)).then(|| { + if authority.person { + self.coordinator + .proposal_subject_reference(authority.common.principal()) + } else { + String::new() + } + }) + }) + .collect::>(); let mut after = query.after; let mut items = Vec::new(); let mut has_more = false; @@ -1610,6 +1784,7 @@ impl PostgresRecordMutationService { &owner_references, &query.action, &query.state, + &subject_references, ], ) .await @@ -1622,10 +1797,12 @@ impl PostgresRecordMutationService { let id: Uuid = candidate.get(0); let action_id: String = candidate.get(1); after = Some(id); - let Some(authority) = authorities - .iter() - .find(|authority| authority.common.action_id() == action_id) - else { + let Some(authority) = self.governing_list_authority( + authorities, + &action_id, + &candidate.get::<_, String>(4), + candidate.get::<_, Option>(5).as_deref(), + ) else { continue; }; let guarded = begin_proposal_transaction( @@ -1646,27 +1823,21 @@ impl PostgresRecordMutationService { .await?; #[cfg(feature = "postgres-test")] self.pause_proposal_read_for_test().await; - match self - .coordinator - .authorize_proposal_document( - guarded.transaction(), - &self.registry, - &document, - authority, - ) - .await - { - Ok(()) => {} - Err( - MutationError::AuthorizationRefused(_) | MutationError::PreconditionFailed, - ) => { - guarded - .rollback() - .await - .map_err(|_| MutationError::Unavailable)?; - continue; - } - Err(error) => return Err(error), + if !link_readable( + self.coordinator + .authorize_proposal_document( + guarded.transaction(), + &self.registry, + &document, + authority, + ) + .await, + )? { + guarded + .rollback() + .await + .map_err(|_| MutationError::Unavailable)?; + continue; } // Only an authorized UUID may become a continuation. An extra // authorized candidate proves another bounded page is useful. @@ -1693,7 +1864,7 @@ impl PostgresRecordMutationService { || document.header.owner_reference == self.coordinator.proposal_owner_of(&authority.common)) && query.target.is_none_or(|target| { - document.input_targets.iter().any(|(_, id)| *id == target) + self.target_filter_matches(&document, authority, target) }); if matches { let value = self @@ -1790,7 +1961,10 @@ impl PostgresRecordMutationService { items .iter() .filter(|item| { + // Each party's entry counts only the items it governed. item["actionId"].as_str() == Some(authority.common.action_id()) + && item.get("partyRole") + == authority.party.map(|party| json!(party)).as_ref() }) .count() }), @@ -1826,6 +2000,7 @@ mod tests { registry_platform_authcommon::FailedCheck::Ownership, ), MutationError::PreconditionFailed, + MutationError::MembershipPreconditionFailed, ] { assert_eq!(link_readable(Err(refusal)), Ok(false)); } @@ -1843,3 +2018,40 @@ mod tests { } } } + +/// The route-level party decision: an entry bound to no party admits, an +/// owner entry admits only the owner, and a subject entry only the subject. +fn party_admits( + party: Option, + owner: impl FnOnce() -> bool, + subject: impl FnOnce() -> bool, +) -> bool { + match party { + None => true, + Some(ProposalParty::Owner) => owner(), + Some(ProposalParty::Subject) => subject(), + } +} + +#[cfg(test)] +mod party_admission_tests { + use super::*; + + #[test] + fn each_party_entry_admits_only_its_own_party() { + for (party, owner, subject, admitted) in [ + (None, false, false, true), + (Some(ProposalParty::Owner), true, false, true), + (Some(ProposalParty::Owner), false, true, false), + (Some(ProposalParty::Subject), false, true, true), + (Some(ProposalParty::Subject), true, false, false), + (Some(ProposalParty::Subject), false, false, false), + ] { + assert_eq!( + party_admits(party, || owner, || subject), + admitted, + "{party:?} owner={owner} subject={subject}" + ); + } + } +} diff --git a/crates/registry-breg/src/postgres/proposal_context.rs b/crates/registry-breg/src/postgres/proposal_context.rs index 54b88f1d9d..7a1d9dc66b 100644 --- a/crates/registry-breg/src/postgres/proposal_context.rs +++ b/crates/registry-breg/src/postgres/proposal_context.rs @@ -3,7 +3,9 @@ //! Proposal grants are independent from Action start and record CRUD grants. use super::*; -use crate::model::{CompiledActionExecution, ProposalOperation, ProposalOwnership}; +use crate::model::{ + CompiledActionExecution, CompiledMembershipBoundary, ProposalOperation, ProposalParty, +}; #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub(crate) enum ProposalAuthorityOperation { @@ -24,15 +26,28 @@ pub(crate) enum ProposalTargetPhase { pub(crate) struct ProposalAuthority { pub(crate) common: ActionClaimContext, pub(crate) operation: ProposalAuthorityOperation, - pub(crate) ownership: Option, + /// The party the admitting entry is bound to. `None` for an entry bound + /// to no party and for Start. + pub(crate) party: Option, + /// Submit may name someone other than the submitter as the subject. + pub(crate) submits_for_anyone: bool, pub(crate) readable_review_progress: bool, pub(crate) targets: BTreeMap>, + target_memberships: BTreeMap>, pub(crate) task_grant: Option, pub(crate) proposal_scope: Option>, /// Whether this caller may receive applicant answers to review asks and /// download the files they cite. Only Proposal admission of a verified /// human caller sets it; every other authority is built without it. pub(crate) receives_review_answers: bool, + /// The admission's human test alone: a verified person acting for no one + /// else and under no task grant. Only such a caller is matched as a + /// subject. Review reads clear the answers flag, never this one. + pub(crate) person: bool, + pub(crate) receives_form_values: bool, + /// The same caller's `message` admission, set by a review-context read + /// that may serve the thread: `true` serves its text, `false` its counts. + pub(crate) review_messages: Option<(Box, bool)>, system: Option, } @@ -56,6 +71,7 @@ impl ProposalAuthority { operation: ProposalAuthorityOperation, principal: &str, profile: &str, + party: Option, purpose: Option<&str>, targets: BTreeMap>, ) -> Result { @@ -68,7 +84,8 @@ impl ProposalAuthority { let CompiledActionExecution::Proposal { proposal } = &action.execution else { return Err(invalid_context()); }; - let ownership; + let selected_party; + let submits_for_anyone; let readable_review_progress; let expected = match operation { ProposalAuthorityOperation::Start => { @@ -77,26 +94,41 @@ impl ProposalAuthority { .iter() .find(|p| p.profile_id == profile && p.operations.contains(&Operation::Start)) .ok_or_else(invalid_context)?; - ownership = None; + selected_party = None; + submits_for_anyone = false; readable_review_progress = false; permission - .targets - .iter() - .map(|t| (t.entity_id.as_str(), &t.row_boundaries)) + .entity_target_locks() + .map(|t| { + ( + t.entity_id.as_str(), + (&t.row_boundaries, &t.membership_boundaries), + ) + }) .collect::>() } ProposalAuthorityOperation::Lifecycle(operation) => { let permission = proposal .permissions .iter() - .find(|p| p.profile_id == profile && p.operations.contains(&operation)) + .find(|p| { + p.profile_id == profile + && p.party == party + && p.operations.contains(&operation) + }) .ok_or_else(invalid_context)?; - ownership = permission.ownership; + selected_party = permission.party; + submits_for_anyone = permission.submits_for_anyone; readable_review_progress = permission.readable_review_progress; permission .targets .iter() - .map(|t| (t.entity_id.as_str(), &t.row_boundaries)) + .map(|t| { + ( + t.entity_id.as_str(), + (&t.row_boundaries, &t.membership_boundaries), + ) + }) .collect::>() } }; @@ -110,9 +142,15 @@ impl ProposalAuthority { boundaries, expected .get(entity_id.as_str()) - .ok_or_else(invalid_context)?, + .ok_or_else(invalid_context)? + .0, )?; } + let target_memberships = expected + .into_iter() + .filter(|(_, (_, memberships))| !memberships.is_empty()) + .map(|(id, (_, memberships))| (id.to_owned(), memberships.clone())) + .collect(); Ok(Self { common: ActionClaimContext::new( action_id.to_owned(), @@ -122,12 +160,17 @@ impl ProposalAuthority { BTreeSet::new(), )?, operation, - ownership, + party: selected_party, + submits_for_anyone, readable_review_progress, targets, + target_memberships, task_grant: None, proposal_scope: None, receives_review_answers: false, + person: false, + receives_form_values: false, + review_messages: None, system: None, }) } @@ -247,12 +290,17 @@ impl ProposalAuthority { BTreeSet::new(), )?, operation: ProposalAuthorityOperation::Lifecycle(ProposalOperation::Apply), - ownership: None, + party: None, + submits_for_anyone: false, readable_review_progress: false, targets, + target_memberships: BTreeMap::new(), task_grant: None, proposal_scope: Some(BTreeSet::from([proposal_id])), receives_review_answers: false, + person: false, + receives_form_values: false, + review_messages: None, system: Some(SystemApplyAuthority { grant: grant.clone(), proposal_id, @@ -269,6 +317,37 @@ impl ProposalAuthority { }) } + /// The compiled Proposal entry this authority was admitted by. Start + /// authority is admitted by an Action grant, so it names the entry the + /// starter's draft is governed by: the profile's entry bound to no party, + /// or its owner entry. + pub(crate) fn permission<'a>( + &self, + proposal: &'a crate::model::CompiledProposalPolicy, + ) -> Option<&'a crate::model::CompiledProposalPermission> { + let profile = self.common.access_profile(); + proposal.permissions.iter().find(|permission| { + permission.profile_id == profile + && match self.operation { + ProposalAuthorityOperation::Start => { + matches!(permission.party, None | Some(ProposalParty::Owner)) + } + ProposalAuthorityOperation::Lifecycle(_) => permission.party == self.party, + } + }) + } + + pub(crate) fn target_membership(&self, entity_id: &str) -> &[CompiledMembershipBoundary] { + self.target_memberships + .get(entity_id) + .map_or(&[], Vec::as_slice) + } + + pub(crate) fn locks_membership(&self) -> bool { + self.operation == ProposalAuthorityOperation::Lifecycle(ProposalOperation::Apply) + && !self.target_memberships.is_empty() + } + pub(crate) fn is_system(&self) -> bool { self.system.is_some() } @@ -295,6 +374,23 @@ impl ProposalAuthority { snapshot_matches_boundaries(entity, snapshot, id, boundaries) } + pub(crate) fn authorizes_create_before_allocation( + &self, + entity: &crate::model::CompiledEntity, + id: Uuid, + snapshot: &serde_json::Map, + ) -> Result { + let boundaries = self.targets.get(&entity.id).ok_or_else(invalid_context)?; + snapshot_matches_selected_boundaries( + entity, + snapshot, + id, + boundaries + .iter() + .filter(|boundary| !is_allocated_field(entity, boundary)), + ) + } + #[allow(clippy::too_many_arguments)] pub(crate) async fn install_target( &self, @@ -448,11 +544,13 @@ impl ProposalAuthority { ProposalAuthorityOperation::Lifecycle(ProposalOperation::GetReviewContext) => "get-review-context", ProposalAuthorityOperation::Lifecycle(ProposalOperation::GetTaskGrantContext) => "get-task-grant-context", ProposalAuthorityOperation::Lifecycle(ProposalOperation::GetApplicationActor) => "get-application-actor", + ProposalAuthorityOperation::Lifecycle(ProposalOperation::Message) => "message", }, "phase": match phase {ProposalTargetPhase::Preparation=>"preparation",ProposalTargetPhase::Application=>"application",ProposalTargetPhase::Inspection=>"inspection"}, "targetEntityId": target_entity_id, "targetRecordId": target_record_id, "operation": match operation {Operation::Get=>"get",Operation::Create=>"create",Operation::Patch=>"patch",_=>return Err(invalid_context())}, "selectedAccessProfile": self.common.access_profile(), + "party": self.party, "principal": self.common.principal(), "purpose": self.common.purpose(), "rowBoundaries": boundaries.iter().map(|b| json!({"field":b.field(),"operator":b.operator().as_str(),"values":b.values()})).collect::>(), "fields": fields, @@ -477,7 +575,7 @@ impl fmt::Debug for ProposalAuthority { f.debug_struct("ProposalAuthority") .field("common", &self.common) .field("operation", &self.operation) - .field("ownership", &self.ownership) + .field("party", &self.party) .field("target_count", &self.targets.len()) .finish() } @@ -492,5 +590,13 @@ pub(crate) async fn begin_proposal_transaction<'a>( expected: &ExpectedRegistryIdentity, authority: &ProposalAuthority, ) -> Result> { - begin_action_transaction(client, lock_key, lock_timeout, expected, &authority.common).await + begin_action_transaction_for_write( + client, + lock_key, + lock_timeout, + expected, + &authority.common, + authority.locks_membership(), + ) + .await } diff --git a/crates/registry-breg/src/postgres/proposal_messages.rs b/crates/registry-breg/src/postgres/proposal_messages.rs new file mode 100644 index 0000000000..68365d898e --- /dev/null +++ b/crates/registry-breg/src/postgres/proposal_messages.rs @@ -0,0 +1,210 @@ +// SPDX-License-Identifier: Apache-2.0 + +//! Reading a Proposal's message thread page by page, and one side marking +//! it read. A write is an ordinary Proposal command. +use super::*; +use crate::model::CompiledAction; +use crate::proposal_messages; +use crate::proposal_store::ProposalDocument; + +impl PostgresRecordMutationService { + /// One page of the thread, newest first. `before` is the cursor the + /// previous page returned. + pub(crate) async fn proposal_messages_page( + &self, + id: Uuid, + authority: &ProposalAuthority, + before: Option, + limit: i64, + correlation: &crate::correlation::RequestCorrelation, + ) -> Result { + let method = crate::model::HttpMethod::Get; + let _attempt = self + .coordinator + .begin_proposal_read_audit(authority, method, correlation) + .await?; + let deadline = tokio::time::Instant::now() + self.action_timeout; + let client = self + .admitted_proposal_read_client(authority, method, correlation, deadline) + .await?; + let mut guard = QueryCancellationGuard::new(self.pool.clone(), client); + let result = tokio::time::timeout_at(deadline, async { + let guarded = begin_proposal_transaction( + guard.client(), + self.lock_key, + self.lock_timeout, + &self.expected, + authority, + ) + .await + .map_err(|_| MutationError::Unavailable)?; + guarded + .set_statement_budget( + deadline.saturating_duration_since(tokio::time::Instant::now()), + ) + .await + .map_err(|_| MutationError::Unavailable)?; + let tx = guarded.transaction(); + let document = + proposal_store::load_document(tx, id, proposal_store::DocumentLock::Share).await?; + self.coordinator + .authorize_proposal_document(tx, &self.registry, &document, authority) + .await?; + let reader = self.coordinator.proposal_actor_of(&authority.common)?; + let mut page = + proposal_messages::page(tx, &document.action_id, id, before, limit + 1, &reader) + .await?; + let more = page.len() as i64 > limit; + page.truncate(limit as usize); + let mut value = + json!({"items":page.iter().map(|(_, item)| item.clone()).collect::>()}); + // The page carries the thread's links, so a reader with no + // document to start from still has the write's condition. + value["links"] = self + .coordinator + .proposal_message_links(tx, self.thread_action(&document)?, &document, authority) + .await?; + if more { + if let Some((position, _)) = page.last() { + value["nextCursor"] = json!(position.to_string()); + } + } + guarded + .commit() + .await + .map_err(|_| MutationError::Unavailable)?; + self.coordinator + .finish_proposal_read_audit( + authority, + method, + Some(&document), + page.len(), + Some(MESSAGES_REFERENCE), + correlation, + ) + .await?; + Ok(value) + }) + .await; + self.finish_message_request(guard, result, authority, method, correlation) + .await + } + + /// Move the caller's side of the thread forward through `through`. A + /// move advances the Proposal revision and emits no event; repeating it + /// changes nothing. With `thread_view`, a caller answered without a + /// Proposal document receives the thread when no review context is + /// readable. + pub(crate) async fn proposal_mark_messages_read( + &self, + id: Uuid, + authority: &ProposalAuthority, + through: Uuid, + thread_view: bool, + correlation: &crate::correlation::RequestCorrelation, + ) -> Result, MutationError> { + let method = crate::model::HttpMethod::Post; + let _attempt = self + .coordinator + .begin_proposal_read_audit(authority, method, correlation) + .await?; + let deadline = tokio::time::Instant::now() + self.action_timeout; + let client = self + .admitted_proposal_read_client(authority, method, correlation, deadline) + .await?; + let mut guard = QueryCancellationGuard::new(self.pool.clone(), client); + let result = tokio::time::timeout_at(deadline, async { + let guarded = begin_proposal_transaction( + guard.client(), + self.lock_key, + self.lock_timeout, + &self.expected, + authority, + ) + .await + .map_err(|_| MutationError::Unavailable)?; + guarded + .set_statement_budget( + deadline.saturating_duration_since(tokio::time::Instant::now()), + ) + .await + .map_err(|_| MutationError::Unavailable)?; + let tx = guarded.transaction(); + let document = + proposal_store::load_document(tx, id, proposal_store::DocumentLock::Update).await?; + self.coordinator + .authorize_proposal_document(tx, &self.registry, &document, authority) + .await?; + let moved = self + .coordinator + .record_messages_read(tx, &document, authority, through) + .await?; + let view = if thread_view { + let document = + proposal_store::load_document(tx, id, proposal_store::DocumentLock::None) + .await?; + self.coordinator + .proposal_thread_view(tx, self.thread_action(&document)?, &document, authority) + .await? + } else { + None + }; + guarded + .commit() + .await + .map_err(|_| MutationError::Unavailable)?; + self.coordinator + .finish_proposal_read_audit( + authority, + method, + Some(&document), + usize::from(moved), + view.as_ref().map(|_| MESSAGES_REFERENCE), + correlation, + ) + .await?; + Ok(view) + }) + .await; + self.finish_message_request(guard, result, authority, method, correlation) + .await + } + + fn thread_action(&self, document: &ProposalDocument) -> Result<&CompiledAction, MutationError> { + self.registry + .actions() + .actions + .iter() + .find(|action| action.id == document.action_id) + .ok_or(MutationError::PreconditionFailed) + } + + async fn finish_message_request( + &self, + mut guard: QueryCancellationGuard, + result: Result, tokio::time::error::Elapsed>, + authority: &ProposalAuthority, + method: crate::model::HttpMethod, + correlation: &crate::correlation::RequestCorrelation, + ) -> Result { + let result = match result { + Ok(result) => { + guard.disarm(); + result + } + Err(_) => { + guard.cancel_and_discard().await; + Err(MutationError::Unavailable) + } + }; + if result.is_err() { + self.coordinator + .record_proposal_refusal(authority, method, correlation) + .await?; + } + result + } +} + +/// The audit marker of a read that served message text. +const MESSAGES_REFERENCE: &str = "proposal-messages"; diff --git a/crates/registry-breg/src/postgres/read.rs b/crates/registry-breg/src/postgres/read.rs index 69aee6af38..1865f57aef 100644 --- a/crates/registry-breg/src/postgres/read.rs +++ b/crates/registry-breg/src/postgres/read.rs @@ -462,7 +462,15 @@ impl PostgresRecordReadService { .through_entity .as_ref() .ok_or(ReadServiceError::Unavailable)?; - ReadRelations::relationship(&plan.source_entity, through, &plan.entity, path, root_id)? + ReadRelations::relationship( + &plan.source_entity, + through, + &plan.entity, + path, + root_id, + query, + &selected_fields, + )? } else { ReadRelations::collection(&plan.entity, query, &selected_fields)? }; @@ -2072,13 +2080,13 @@ fn parse_rfc3339_utc(value: &str) -> Result( +fn required_derived_relations<'a>( entity: &'a CompiledEntity, query: Option<&crate::api::CompiledReadQuery>, selected_fields: &[String], @@ -2120,6 +2128,38 @@ fn collect_filter_fields<'a>(filter: &'a ReadFilterExpr, fields: &mut BTreeSet<& } } +fn join_derived_relations( + from_sql: &mut String, + entity: &CompiledEntity, + id_expression: &str, + query: Option<&crate::api::CompiledReadQuery>, + selected_fields: &[String], +) -> Result, ReadServiceError> { + let mut derived_aliases = BTreeMap::new(); + let required_relations = required_derived_relations(entity, query, selected_fields); + for (index, relation) in entity + .derived_relations + .values() + .filter(|relation| required_relations.contains(relation.id.as_str())) + .enumerate() + { + let alias = format!("derived_{index}"); + let view_name = + crate::generated_ddl::derived_view_name(&entity.source_relation.sql_name, &relation.id); + if !valid_physical_identifier(&view_name) { + return Err(ReadServiceError::Unavailable); + } + from_sql.push_str(&format!( + " LEFT JOIN registry_derived.{} AS {alias} + ON {alias}.{} = {id_expression}", + quote_identifier(&view_name), + quote_identifier(&entity.canonical_id.sql_name), + )); + derived_aliases.insert(relation.id.clone(), alias); + } + Ok(derived_aliases) +} + pub(crate) struct ReadRelations { pub(crate) base_alias: &'static str, pub(crate) source_alias: &'static str, @@ -2143,7 +2183,6 @@ impl ReadRelations { { return Err(ReadServiceError::Unavailable); } - let mut derived_aliases = BTreeMap::new(); let id_expression = format!( "{source_alias}.{}", quote_identifier(&entity.canonical_id.sql_name) @@ -2166,29 +2205,13 @@ impl ReadRelations { quote_identifier(&candidate_view), )); } - let required_relations = collection_derived_relations(entity, query, selected_fields); - for (index, relation) in entity - .derived_relations - .values() - .filter(|relation| required_relations.contains(relation.id.as_str())) - .enumerate() - { - let alias = format!("derived_{index}"); - let view_name = crate::generated_ddl::derived_view_name( - &entity.source_relation.sql_name, - &relation.id, - ); - if !valid_physical_identifier(&view_name) { - return Err(ReadServiceError::Unavailable); - } - from_sql.push_str(&format!( - " LEFT JOIN registry_derived.{} AS {alias} - ON {alias}.{} = {id_expression}", - quote_identifier(&view_name), - quote_identifier(&entity.canonical_id.sql_name), - )); - derived_aliases.insert(relation.id.clone(), alias); - } + let derived_aliases = join_derived_relations( + &mut from_sql, + entity, + &id_expression, + query, + selected_fields, + )?; Ok(Self { base_alias, source_alias, @@ -2212,6 +2235,8 @@ impl ReadRelations { target: &CompiledEntity, path: &CompiledReadPath, root_id: &str, + query: Option<&crate::api::CompiledReadQuery>, + selected_fields: &[String], ) -> Result { if !valid_canonical_uuid(root_id) { return Err(ReadServiceError::Unavailable); @@ -2252,24 +2277,8 @@ impl ReadRelations { quote_identifier(&target.source_relation.sql_name), quote_identifier(&target.physical_table), ); - let mut derived_aliases = BTreeMap::new(); - for (index, relation) in target.derived_relations.values().enumerate() { - let alias = format!("derived_{index}"); - let view_name = crate::generated_ddl::derived_view_name( - &target.source_relation.sql_name, - &relation.id, - ); - if !valid_physical_identifier(&view_name) { - return Err(ReadServiceError::Unavailable); - } - from_sql.push_str(&format!( - " LEFT JOIN registry_derived.{} AS {alias} - ON {alias}.{} = {target_id}", - quote_identifier(&view_name), - quote_identifier(&target.canonical_id.sql_name), - )); - derived_aliases.insert(relation.id.clone(), alias); - } + let derived_aliases = + join_derived_relations(&mut from_sql, target, &target_id, query, selected_fields)?; Ok(Self { base_alias, source_alias, diff --git a/crates/registry-breg/src/postgres/rehearsal.rs b/crates/registry-breg/src/postgres/rehearsal.rs index 980ff5d7c8..a5b1e147dd 100644 --- a/crates/registry-breg/src/postgres/rehearsal.rs +++ b/crates/registry-breg/src/postgres/rehearsal.rs @@ -33,9 +33,10 @@ use super::{ }, migration_ledger::statement_checksum, schema::{ - compiled_pattern_field, connect_schema_test, execute_compiled_ddl_statement, - install_compiled_schema, is_spatial_candidate_view_sql, pattern_field_for_constraint, - reconcile_compiled_runtime_acl, refuse_existing_managed_objects, + compiled_membership_source, compiled_pattern_field, connect_schema_test, + execute_compiled_ddl_statement, install_compiled_schema, is_spatial_candidate_view_sql, + pattern_field_for_constraint, reconcile_compiled_runtime_acl, + refuse_existing_managed_objects, }, verify_migration_role, ConnectionConfig, SqlIdentifier, }; @@ -193,6 +194,10 @@ pub async fn rehearse_successor_migration( checksum, kind: statement.kind, pattern_field: compiled_pattern_field(candidate.registry(), &statement.id), + membership_source: compiled_membership_source( + candidate.registry(), + &statement.id, + ), ordinal: i32::try_from(ordinal).ok()?, }, }) @@ -396,6 +401,7 @@ async fn rehearse_compiler_statement( statement.ddl.sql, statement.ddl.kind, None, + None, runtime_role, ) .await diff --git a/crates/registry-breg/src/postgres/schema.rs b/crates/registry-breg/src/postgres/schema.rs index 64aa615e90..280bb7f4db 100644 --- a/crates/registry-breg/src/postgres/schema.rs +++ b/crates/registry-breg/src/postgres/schema.rs @@ -86,6 +86,7 @@ pub async fn install_compiled_schema( &statement.sql, statement.kind, compiled_pattern_field(registry, &statement.id), + compiled_membership_source(registry, &statement.id), runtime_role, ) .await?; @@ -96,6 +97,7 @@ pub async fn install_compiled_schema( &statement.sql, statement.kind, None, + None, runtime_role, ) .await?; @@ -376,19 +378,50 @@ pub(crate) async fn execute_compiled_ddl_statement( sql: &str, kind: DdlStatementKind, pattern_field: Option<(&str, &str)>, + membership_source: Option<&str>, runtime_role: &SqlIdentifier, ) -> Result<()> { if kind == DdlStatementKind::View && is_spatial_candidate_view_sql(sql) { execute_spatial_candidate_view_ddl(client, sql, runtime_role).await } else { - client - .batch_execute(sql) - .await - .map_err(|error| map_pattern_database_error(error, pattern_field))?; + client.batch_execute(sql).await.map_err(|error| { + map_membership_index_error(&error, membership_source) + .unwrap_or_else(|| map_pattern_database_error(error, pattern_field)) + })?; Ok(()) } } +/// The membership source whose generated live-row index `statement_id` +/// builds. +pub(crate) fn compiled_membership_source<'a>( + registry: &'a CompiledRegistry, + statement_id: &str, +) -> Option<&'a str> { + registry + .entities() + .values() + .filter(|entity| entity.membership.is_some()) + .find(|entity| statement_id == format!("entity.{}.membership.key-index", entity.id)) + .map(|entity| entity.id.as_str()) +} + +/// Existing active rows that repeat a key and principal stop the unique +/// live-row index from building. Name the source, never the values. +fn map_membership_index_error( + error: &tokio_postgres::Error, + membership_source: Option<&str>, +) -> Option { + (error.code() == Some(&tokio_postgres::error::SqlState::UNIQUE_VIOLATION)) + .then_some(membership_source) + .flatten() + .map( + |entity_id| PostgresKernelError::MembershipDuplicateLiveRows { + entity_id: entity_id.to_owned(), + }, + ) +} + pub(crate) fn compiled_pattern_field<'a>( registry: &'a CompiledRegistry, statement_id: &str, diff --git a/crates/registry-breg/src/problem.rs b/crates/registry-breg/src/problem.rs index e823b1d66c..66bbe87cf4 100644 --- a/crates/registry-breg/src/problem.rs +++ b/crates/registry-breg/src/problem.rs @@ -30,6 +30,8 @@ pub enum ProblemCode { AttachmentContentType, AttachmentDigestMismatch, AttachmentLimitReached, + ProposalFormUndeclared, + ProposalFormLimitReached, AttachmentRequired, AttachmentSlotWriteOnce, AttachmentTooLarge, @@ -50,8 +52,11 @@ pub enum ProblemCode { PreconditionFailed, PreconditionRequired, ProfileNotAuthorized, + ProposalMessageLimitReached, ProposalRejected, ProposalReviewResultMismatch, + ProposalSubjectChanged, + ProposalSubjectNotCaller, ProposalSubmissionExpired, QueryCursorInvalid, QueryFilterRequired, @@ -103,8 +108,13 @@ impl ProblemCode { Self::PreconditionFailed, Self::PreconditionRequired, Self::ProfileNotAuthorized, + Self::ProposalFormLimitReached, + Self::ProposalFormUndeclared, + Self::ProposalMessageLimitReached, Self::ProposalRejected, Self::ProposalReviewResultMismatch, + Self::ProposalSubjectChanged, + Self::ProposalSubjectNotCaller, Self::ProposalSubmissionExpired, Self::QueryCursorInvalid, Self::QueryFilterRequired, @@ -159,8 +169,13 @@ impl ProblemCode { Self::PreconditionFailed, Self::PreconditionRequired, Self::ProfileNotAuthorized, + Self::ProposalFormLimitReached, + Self::ProposalFormUndeclared, + Self::ProposalMessageLimitReached, Self::ProposalRejected, Self::ProposalReviewResultMismatch, + Self::ProposalSubjectChanged, + Self::ProposalSubjectNotCaller, Self::ProposalSubmissionExpired, Self::QueryCursorInvalid, Self::QueryFilterRequired, @@ -191,6 +206,8 @@ impl ProblemCode { Self::AttachmentContentType => "attachment.content-type", Self::AttachmentDigestMismatch => "attachment.digest-mismatch", Self::AttachmentLimitReached => "attachment.limit-reached", + Self::ProposalFormUndeclared => "proposal.form-undeclared", + Self::ProposalFormLimitReached => "proposal.form-limit-reached", Self::AttachmentRequired => "attachment.required", Self::AttachmentVerificationPending => "attachment.verification-pending", Self::AttachmentVerificationRejected => "attachment.verification-rejected", @@ -211,8 +228,11 @@ impl ProblemCode { Self::PreconditionFailed => "precondition.failed", Self::PreconditionRequired => "precondition.required", Self::ProfileNotAuthorized => "profile.not-authorized", + Self::ProposalMessageLimitReached => "proposal.message-limit-reached", Self::ProposalRejected => "proposal.rejected", Self::ProposalReviewResultMismatch => "proposal.review-result-mismatch", + Self::ProposalSubjectChanged => "proposal.subject-changed", + Self::ProposalSubjectNotCaller => "proposal.subject-not-caller", Self::ProposalSubmissionExpired => "proposal.submission-expired", Self::QueryCursorInvalid => "query.cursor-invalid", Self::QueryFilterRequired => "query.filter-required", @@ -247,17 +267,21 @@ impl ProblemCode { Self::AuthenticationRefused | Self::DevelopmentTaskAssertion => 401, Self::IngestionProfileMismatch | Self::ProfileNotAuthorized + | Self::ProposalSubjectNotCaller | Self::WriteOutsideBoundary => 403, - Self::LookupUnresolved | Self::ResourceNotFound => 404, + Self::LookupUnresolved | Self::ResourceNotFound | Self::ProposalFormUndeclared => 404, Self::AttachmentSlotWriteOnce | Self::AttachmentLimitReached + | Self::ProposalFormLimitReached | Self::AttachmentVerificationPending | Self::IdempotencyConflict | Self::IngestionChunkMismatch | Self::IngestionRunBlocked | Self::IngestionRunNotOpen | Self::MutationConflict + | Self::ProposalMessageLimitReached | Self::ProposalRejected + | Self::ProposalSubjectChanged | Self::StatisticalDatasetVersionConflict => 409, Self::IdempotencyExpired | Self::IngestionReceiptErased @@ -335,6 +359,8 @@ impl ProblemCode { } Self::AttachmentTooLarge => "The file is larger than the attachment slot accepts.", Self::AttachmentLimitReached => "The supporting document slot has reached its file limit.", + Self::ProposalFormUndeclared => "The Action does not declare this additional form.", + Self::ProposalFormLimitReached => "The submission has reached the entry limit for this form.", 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.", @@ -360,6 +386,9 @@ impl ProblemCode { } Self::PreconditionFailed => "The mutation precondition failed.", Self::ProposalReviewResultMismatch => "The current review result does not match the retained approval.", + 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::PreconditionRequired => "The mutation precondition is required.", Self::ProfileNotAuthorized => "No access profile admits this caller for this request.", Self::ProposalRejected => { diff --git a/crates/registry-breg/src/problem_location.rs b/crates/registry-breg/src/problem_location.rs index bb063e5667..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"; @@ -118,6 +117,20 @@ impl RequestLocation { scope: Scope::Input, } } + /// The text of a Proposal message. No submitted value is echoed. + pub fn proposal_message_text() -> Self { + Self { + pointer: "/text".into(), + scope: Scope::Input, + } + } + /// The message a mark-read names. No submitted value is echoed. + pub fn proposal_message_through() -> Self { + Self { + pointer: "/through".into(), + scope: Scope::Input, + } + } pub fn proposal_answer_additions() -> Self { Self { pointer: "/additions".into(), @@ -125,6 +138,13 @@ impl RequestLocation { } } + pub fn proposal_answer_form_entries() -> Self { + Self { + pointer: "/formEntries".into(), + scope: Scope::Input, + } + } + /// The `data` member of a create body. #[must_use] pub fn data() -> Self { @@ -161,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`. @@ -168,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, @@ -402,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 8aaec7be4e..54b0482fb4 100644 --- a/crates/registry-breg/src/proposal_artifacts.rs +++ b/crates/registry-breg/src/proposal_artifacts.rs @@ -1,6 +1,7 @@ // SPDX-License-Identifier: Apache-2.0 //! First-class Proposal operations derived from the compiled Action policies. use super::*; +use crate::contract::MAX_PROPOSAL_MESSAGE_COUNT; use crate::model::{CompiledActionExecution, ProposalOperation}; use crate::problem::ProblemCode; @@ -14,6 +15,12 @@ pub(crate) fn append_proposal_openapi( matches!(&action.execution, CompiledActionExecution::Proposal { proposal } if proposal.additions.is_some()) }); + let forms_enabled = actions.actions.iter().any(|action| { + matches!(&action.execution, CompiledActionExecution::Proposal { proposal } if !proposal.additional_forms.is_empty()) + }); + let mut form_profiles = BTreeSet::new(); + let mut form_inputs = Vec::new(); + let mut message_profiles = BTreeSet::new(); let mut permissions: BTreeMap, Vec)> = BTreeMap::new(); // A manual application writes as the applier, so the apply operation may @@ -44,6 +51,7 @@ pub(crate) fn append_proposal_openapi( ProposalOperation::GetApplicationActor | ProposalOperation::Add | ProposalOperation::Answer + | ProposalOperation::Message ) { continue; } @@ -231,6 +239,20 @@ pub(crate) fn append_proposal_openapi( merge_operation(paths, path.clone(), method, operation)?; } } + if permitted(ProposalOperation::Message) { + message_profiles.insert(grant.profile_id.clone()); + } + if permitted(ProposalOperation::Add) { + for id in &grant.writable_forms { + let form = &proposal.additional_forms[id]; + let schema = + additional_form_contract(&action.id, id, &form.inputs)["schema"].clone(); + if !form_inputs.contains(&schema) { + form_inputs.push(schema); + } + form_profiles.insert(grant.profile_id.clone()); + } + } if permitted(ProposalOperation::Answer) { let mut document = operation_document( "proposals.answer", @@ -243,9 +265,10 @@ pub(crate) fn append_proposal_openapi( "name":"ask_id","in":"path","required":true,"schema":{"type":"string","format":"uuid"}})); document["requestBody"] = json!({"required":true,"content":{"application/json":{"schema":{ "type":"object","additionalProperties":false, - "anyOf":[{"required":["text"]},{"required":["additions"],"properties":{"additions":{"minItems":1}}}], + "anyOf":[{"required":["text"]},{"required":["additions"],"properties":{"additions":{"minItems":1}}},{"required":["formEntries"],"properties":{"formEntries":{"minItems":1}}}], "properties":{ "text":{"type":"string","minLength":1,"maxLength":2000}, + "formEntries":{"type":"array","maxItems":32,"uniqueItems":true,"items":{"type":"string","format":"uuid"}}, "additions":{"type":"array","maxItems":32,"uniqueItems":true,"items":{"type":"string","format":"uuid"}}}}}}}); merge_operation( paths, @@ -465,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"}}} ]}}}}); @@ -478,9 +501,224 @@ pub(crate) fn append_proposal_openapi( } merge_operation(paths, path, method, document)?; } + if !form_profiles.is_empty() { + let mut add = operation_document( + "proposals.add-form", + "post", + &form_profiles, + false, + additions_enabled, + ); + add["parameters"].as_array_mut().expect("operation parameters").push(json!({ + "name":"form_id","in":"path","required":true,"schema":{"type":"string","pattern":"^[a-z][a-z0-9_-]{0,63}$"} + })); + add["requestBody"] = json!({"required":true,"content":{"application/json":{"schema":{ + "type":"object","additionalProperties":false,"required":["input"],"properties":{"input":{"anyOf":form_inputs}} + }}}}); + merge_operation( + paths, + "/v1/proposals/{proposal_id}/additional-forms/{form_id}".to_owned(), + "post", + add, + )?; + } + if !message_profiles.is_empty() { + append_message_openapi(paths, &message_profiles, additions_enabled, forms_enabled)?; + } + if forms_enabled { + for (path, operations) in paths + .iter_mut() + .filter(|(path, _)| path.starts_with("/v1/proposals")) + { + for operation in operations + .as_object_mut() + .expect("path operations") + .values_mut() + { + let Some(schema) = + operation.pointer_mut("/responses/200/content/application~1json/schema") + else { + continue; + }; + if path == "/v1/proposals" { + if let Some(item) = schema.pointer_mut("/properties/items/items") { + append_proposal_forms_schema(item); + } + } else if schema.pointer("/properties/actionRevision").is_some() + && schema.pointer("/properties/links").is_some() + { + append_proposal_forms_schema(schema); + } else if path.ends_with("/review-context") { + if let Some(properties) = schema.pointer_mut("/properties/context/properties") { + properties["additionalForms"] = json!({"type":"object","maxProperties":8,"additionalProperties":{"type":"string"}}); + } + } + } + } + } Ok(()) } +fn append_message_openapi( + paths: &mut Map, + profiles: &BTreeSet, + additions: bool, + forms: bool, +) -> Result<(), Diagnostic> { + 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":"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!({ + "type":"object","additionalProperties":false,"required":["items","links"], + "properties":{"items":{"type":"array","maxItems":50,"items":proposal_message_schema()}, + "nextCursor":{"type":"string","pattern":"^[1-9][0-9]*$"}, + "links":proposal_messages_schema(false)["properties"]["links"].clone()} + }); + merge_operation(paths, path.to_owned(), "get", list)?; + let mut proposal = proposal_schema_with_additions(additions); + if forms { + append_proposal_forms_schema(&mut proposal); + } + proposal["properties"]["messages"] = proposal_messages_schema(false); + let mut review = review_document_schema(true); + review["properties"]["context"]["properties"]["messages"] = proposal_messages_schema(false); + if forms { + review["properties"]["context"]["properties"]["additionalForms"] = + json!({"type":"object","maxProperties":8,"additionalProperties":{"type":"string"}}); + } + for (id, suffix, member, member_schema) in [ + ( + "proposals.message", + "", + "text", + json!({"type":"string","minLength":1,"maxLength":2000,"x-maximum-utf8-bytes":2000}), + ), + ( + "proposals.mark-messages-read", + "/read", + "through", + json!({"type":"string","format":"uuid"}), + ), + ] { + let mut operation = operation_document(id, "post", profiles, false, additions); + if !suffix.is_empty() { + operation["parameters"] + .as_array_mut() + .expect("command parameters") + .retain(|parameter| parameter["in"] != "header"); + let responses = operation["responses"].as_object_mut().expect("responses"); + responses.remove("409"); + responses.remove("412"); + responses.insert( + "204".into(), + json!({"description":"The read position was recorded"}), + ); + } + operation["requestBody"] = json!({"required":true,"content":{"application/json":{"schema":{ + "type":"object","additionalProperties":false,"required":[member],"properties":{(member):member_schema} + }}}}); + // A caller without Get is answered with the review context, or with + // the thread alone while no review context is readable. + operation["responses"]["200"]["content"]["application/json"]["schema"] = + json!({"oneOf":[proposal,review,proposal_messages_schema(false)]}); + merge_operation(paths, format!("{path}{suffix}"), "post", operation)?; + } + for (path, operations) in paths + .iter_mut() + .filter(|(path, _)| path.starts_with("/v1/proposals")) + { + for operation in operations + .as_object_mut() + .expect("path operations") + .values_mut() + { + let Some(schema) = + operation.pointer_mut("/responses/200/content/application~1json/schema") + else { + continue; + }; + if path == "/v1/proposals" { + if let Some(item) = schema.pointer_mut("/properties/items/items") { + item["properties"]["messages"] = proposal_messages_schema(true); + } + } else if schema.pointer("/properties/actionRevision").is_some() + && schema.pointer("/properties/links").is_some() + { + schema["properties"]["messages"] = proposal_messages_schema(false); + } else if path.ends_with("/review-context") { + if let Some(properties) = schema.pointer_mut("/properties/context/properties") { + properties["messages"] = proposal_messages_schema(false); + } + if path == "/v1/proposals/review-context" { + if let Some(properties) = schema.pointer_mut("/properties/items/items/oneOf/0/properties/context/properties/context/properties") { + let mut messages = proposal_messages_schema(true); + messages["properties"]["readerSide"] = json!({ + "enum":["party","official"], + "description":"The reader's side whose read position supplied unread." + }); + properties["messages"] = messages; + } + } else if let Some(parameter) = + operation["parameters"] + .as_array_mut() + .and_then(|parameters| { + parameters + .iter_mut() + .find(|parameter| parameter["name"] == "include") + }) + { + parameter["schema"] = json!({"type":"array","maxItems":2,"uniqueItems":true, + "items":{"enum":["answers","messages"]}}); + parameter["style"] = json!("form"); + parameter["explode"] = json!(true); + } + } + } + } + Ok(()) +} + +fn proposal_message_schema() -> Value { + json!({"type":"object","additionalProperties":false,"required":["id","from","mine","sentAt"], + "properties":{"id":{"type":"string","format":"uuid"},"from":{"enum":["party","official"]}, + "partyRole":{"enum":["owner","subject"]},"mine":{"type":"boolean"}, + "sentAt":{"type":"string","format":"date-time"}, + "text":{"type":"string","maxLength":2000,"description":"Render the text as plain text. Escape it before placing it in HTML."}}, + "if":{"properties":{"from":{"const":"party"}}}, + "then":{"required":["partyRole"]},"else":{"not":{"required":["partyRole"]}} + }) +} + +pub(crate) fn proposal_messages_schema(summary: bool) -> Value { + let mut schema = json!({"type":"object","additionalProperties":false,"required":["count","unread"], + "properties":{"count":{"type":"integer","minimum":0,"maximum":2 * MAX_PROPOSAL_MESSAGE_COUNT}, + "unread":{"type":"integer","minimum":0,"maximum":MAX_PROPOSAL_MESSAGE_COUNT},"lastSentAt":{"type":"string","format":"date-time"}} + }); + if !summary { + schema["properties"]["items"] = + json!({"type":"array","maxItems":20,"items":proposal_message_schema()}); + let links = [("message","POST",true),("markRead","POST",false),("list","GET",false)] + .into_iter().map(|(name,method,keyed)| { + let mut link = json!({"type":"object","additionalProperties":false, + "required":["method","path","accessProfile","operation","availability"], + "properties":{"method":{"const":method},"path":{"type":"string"},"accessProfile":{"type":"string"}, + "operation":{"const":"message"},"availability":availability_schema()} + }); + if keyed { + link["required"].as_array_mut().expect("link required members").push(json!("ifMatch")); + link["properties"]["ifMatch"] = json!({"type":"string"}); + } + (name.to_owned(),link) + }).collect::>(); + schema["properties"]["links"] = + json!({"type":"object","additionalProperties":false,"properties":links}); + } + schema +} + fn task_context_request_schema() -> Value { let digest = json!({"type":"string","pattern":"^sha256:[0-9a-f]{64}$"}); json!({"type":"object","additionalProperties":false, @@ -720,6 +958,16 @@ pub(super) fn append_operation_problems(operation: &mut Value, method: &str) { ProblemCode::SourceUnavailable, ProblemCode::RequestTimeout, ]; + if id == "proposals.message" { + codes.push(ProblemCode::ProposalMessageLimitReached); + } + if id == "proposals.list-messages" { + codes.extend([ + ProblemCode::QueryCursorInvalid, + ProblemCode::QueryInvalid, + ProblemCode::RequestInvalid, + ]); + } if id == "proposals.list" { codes.push(ProblemCode::QueryInvalid); } @@ -729,7 +977,12 @@ pub(super) fn append_operation_problems(operation: &mut Value, method: &str) { ProblemCode::UnsupportedMediaType, ]); } - if mutation { + if id == "proposals.mark-messages-read" { + codes.extend([ + ProblemCode::RequestInvalid, + ProblemCode::UnsupportedMediaType, + ]); + } else if mutation { codes.extend([ ProblemCode::RequestInvalid, ProblemCode::PreconditionFailed, @@ -754,10 +1007,23 @@ pub(super) fn append_operation_problems(operation: &mut Value, method: &str) { if addition { codes.push(ProblemCode::AttachmentLimitReached); } + if id == "proposals.add-form" { + codes.extend([ + ProblemCode::ProposalFormLimitReached, + ProblemCode::ProposalFormUndeclared, + ]); + } } if id == "proposals.get-submission" { codes.push(ProblemCode::ProposalSubmissionExpired); } + // Submit binds the subject of an Action that declares one. + if id == "proposals.submit" { + codes.extend([ + ProblemCode::ProposalSubjectNotCaller, + ProblemCode::ProposalSubjectChanged, + ]); + } append_problem_codes(operation, &codes); } @@ -840,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() @@ -848,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/proposal_ddl.rs b/crates/registry-breg/src/proposal_ddl.rs index 8b70753088..f32fab1684 100644 --- a/crates/registry-breg/src/proposal_ddl.rs +++ b/crates/registry-breg/src/proposal_ddl.rs @@ -28,16 +28,24 @@ pub(super) fn target_policies( else { continue; }; + let first_policy = result.len(); add_read_policies( &mut result, entity, action, &grant.profile_id, + None, &grant.required_purposes, &target.row_boundaries, "preparation", "start", ); + crate::membership::append_target_probes( + entity, + &grant.profile_id, + &target.membership_boundaries, + &mut result[first_policy..], + ); } for grant in &proposal.permissions { let Some(target) = grant @@ -47,6 +55,8 @@ pub(super) fn target_policies( else { continue; }; + let party = party_qualifier(grant, &proposal.permissions); + let first_policy = result.len(); for operation in &grant.operations { let name = match operation { ProposalOperation::Get => "get", @@ -63,6 +73,7 @@ pub(super) fn target_policies( ProposalOperation::GetReviewContext => "get-review-context", ProposalOperation::GetTaskGrantContext => "get-task-grant-context", ProposalOperation::GetReviewStatus => "get-review-status", + ProposalOperation::Message => "message", ProposalOperation::GetApplicationActor => continue, }; add_read_policies( @@ -70,6 +81,7 @@ pub(super) fn target_policies( entity, action, &grant.profile_id, + party, &grant.required_purposes, &target.row_boundaries, "inspection", @@ -84,6 +96,7 @@ pub(super) fn target_policies( entity, action, &grant.profile_id, + party, &grant.required_purposes, &target.row_boundaries, "preparation", @@ -96,11 +109,18 @@ pub(super) fn target_policies( entity, action, &grant.profile_id, + party, &grant.required_purposes, &target.row_boundaries, ); } } + crate::membership::append_target_probes( + entity, + &grant.profile_id, + &target.membership_boundaries, + &mut result[first_policy..], + ); } if let Some(grant) = &proposal.system_apply_grant { add_system_policies(&mut result, entity, action, grant); @@ -109,11 +129,32 @@ pub(super) fn target_policies( result } +/// The party a grant's policies are qualified by. A profile's owner and +/// subject entries may bound the same target differently, so once a profile +/// holds a subject entry each of its party entries gets its own policies, +/// matched against the party the runtime admitted. Every other grant keeps +/// its unqualified policies and names. +fn party_qualifier( + grant: &crate::model::CompiledProposalPermission, + permissions: &[crate::model::CompiledProposalPermission], +) -> Option<&'static str> { + use crate::model::ProposalParty; + let qualified = permissions.iter().any(|entry| { + entry.profile_id == grant.profile_id && entry.party == Some(ProposalParty::Subject) + }); + match grant.party { + Some(ProposalParty::Owner) if qualified => Some("owner"), + Some(ProposalParty::Subject) => Some("subject"), + _ => None, + } +} + #[allow(clippy::too_many_arguments)] fn common( entity: &CompiledEntity, action: &CompiledAction, profile: &str, + party: Option<&str>, purposes: &BTreeSet, boundaries: &[crate::contract::RowBoundarySource], phase: &str, @@ -159,6 +200,9 @@ fn common( format!("record_lifecycle = 'active'"), target_boundary_expression(CONTEXT, "rowBoundaries", entity, boundaries), ]; + if let Some(party) = party { + expressions.push(format!("{CONTEXT} ->> 'party' = {}", quote_literal(party))); + } if !purposes.is_empty() { expressions.push(format!( "NULLIF(current_setting('registry.purpose', true), '') IN ({})", @@ -178,6 +222,7 @@ fn add_read_policies( entity: &CompiledEntity, action: &CompiledAction, profile: &str, + party: Option<&str>, purposes: &BTreeSet, boundaries: &[crate::contract::RowBoundarySource], phase: &str, @@ -189,6 +234,7 @@ fn add_read_policies( entity, action, profile, + party, purposes, boundaries, phase, @@ -201,6 +247,7 @@ fn add_read_policies( action, entity, profile, + party, phase, authority_operation, PolicyCommand::Select, @@ -219,6 +266,7 @@ fn add_read_policies( action, entity, profile, + party, phase, authority_operation, PolicyCommand::Update, @@ -236,6 +284,7 @@ fn add_application_policies( entity: &CompiledEntity, action: &CompiledAction, profile: &str, + party: Option<&str>, purposes: &BTreeSet, boundaries: &[crate::contract::RowBoundarySource], ) { @@ -243,6 +292,7 @@ fn add_application_policies( entity, action, profile, + party, purposes, boundaries, "application", @@ -258,6 +308,7 @@ fn add_application_policies( action, entity, profile, + party, "application", "get", PolicyCommand::Select, @@ -274,6 +325,7 @@ fn add_application_policies( action, entity, profile, + party, "application", "get", PolicyCommand::Update, @@ -327,6 +379,7 @@ fn add_application_policies( action, entity, profile, + party, "application", suffix, PolicyCommand::Select, @@ -344,7 +397,15 @@ fn add_application_policies( }; result.push(DdlPolicy { permissive: true, - name: policy_name(action, entity, profile, "application", suffix, command), + name: policy_name( + action, + entity, + profile, + party, + "application", + suffix, + command, + ), command, access_profile: profile.to_owned(), applies_to: ordinary_policy_role(entity), @@ -508,7 +569,7 @@ fn add_system_policies( for command in [PolicyCommand::Select, PolicyCommand::Update] { result.push(DdlPolicy { permissive: true, - name: policy_name(action, entity, PROFILE, phase, "get", command), + name: policy_name(action, entity, PROFILE, None, phase, "get", command), command, access_profile: PROFILE.to_owned(), applies_to: ordinary_policy_role(entity), @@ -540,6 +601,7 @@ fn add_system_policies( action, entity, PROFILE, + None, "application", operation_name(operation), PolicyCommand::Select, @@ -561,6 +623,7 @@ fn add_system_policies( action, entity, PROFILE, + None, "application", operation_name(operation), command, @@ -582,6 +645,7 @@ fn policy_name( action: &CompiledAction, entity: &CompiledEntity, profile: &str, + party: Option<&str>, phase: &str, operation: &str, command: PolicyCommand, @@ -599,6 +663,11 @@ fn policy_name( hash.update((value.len() as u64).to_be_bytes()); hash.update(value.as_bytes()); } + // A party-qualified policy adds its party; every other name is unchanged. + if let Some(party) = party { + hash.update((party.len() as u64).to_be_bytes()); + hash.update(party.as_bytes()); + } // PostgreSQL truncates identifiers after 63 bytes. Keep the complete // generated name below that boundary so installation and verification // compare exactly the same policy identity. diff --git a/crates/registry-breg/src/proposal_events.rs b/crates/registry-breg/src/proposal_events.rs index cee46b35c5..2f83c2cd9a 100644 --- a/crates/registry-breg/src/proposal_events.rs +++ b/crates/registry-breg/src/proposal_events.rs @@ -23,6 +23,7 @@ pub(crate) struct ProposalLifecycleEvent<'a> { pub from_state: &'a str, pub state: &'a str, pub transition: &'a str, + pub message_from: Option<&'a str>, pub effect_digest: Option<&'a str>, pub authority_kind: &'a str, pub system_grant_revision: Option<&'a str>, @@ -47,6 +48,11 @@ pub(crate) async fn insert_proposal_lifecycle_event( if event.version == 0 || event.revision == 0 || event.action_id.is_empty() + || match (event.transition, event.message_from) { + ("messaged", Some("party" | "official")) => false, + ("messaged", _) | (_, Some(_)) => true, + _ => false, + } || !matches!( event.transition, "started" @@ -62,6 +68,7 @@ pub(crate) async fn insert_proposal_lifecycle_event( | "applied" | "rejected" | "review-returned" + | "messaged" ) { return Err(OutboxError::InvalidProjection); @@ -83,6 +90,14 @@ pub(crate) async fn insert_proposal_lifecycle_event( event_type.clone(), crate::proposal_hooks::PROPOSAL_EVENT_SCHEMA.to_owned(), )]); + let mut data = json!({"actionId":event.action_id,"actionRevision":event.action_revision, + "proposalId":event.proposal_id,"submissionVersion":event.version,"revision":event.revision, + "fromState":event.from_state,"state":event.state,"transition":event.transition, + "effectDigest":event.effect_digest,"authorityKind":event.authority_kind, + "systemApplyGrantRevision":event.system_grant_revision,"turn":event.turn}); + if let Some(side) = event.message_from { + data["messageFrom"] = json!(side); + } let envelope = capture_envelope( &EnvelopeBinding { source: event.source, @@ -97,11 +112,7 @@ pub(crate) async fn insert_proposal_lifecycle_event( event.reference, i64::try_from(event.revision).map_err(|_| OutboxError::Unavailable)?, ), - data: json!({"actionId":event.action_id,"actionRevision":event.action_revision, - "proposalId":event.proposal_id,"submissionVersion":event.version,"revision":event.revision, - "fromState":event.from_state,"state":event.state,"transition":event.transition, - "effectDigest":event.effect_digest,"authorityKind":event.authority_kind, - "systemApplyGrantRevision":event.system_grant_revision,"turn":event.turn}), + data, }, )?; let payload = envelope_payload( diff --git a/crates/registry-breg/src/proposal_hooks.rs b/crates/registry-breg/src/proposal_hooks.rs index ccc015add8..0325cdcc39 100644 --- a/crates/registry-breg/src/proposal_hooks.rs +++ b/crates/registry-breg/src/proposal_hooks.rs @@ -39,10 +39,14 @@ pub fn proposal_event_schema() -> Value { "submissionVersion":{"type":"integer","minimum":1,"maximum":4294967295u64}, "revision":{"type":"integer","minimum":1,"maximum":9007199254740991u64}, "fromState":{"anyOf":[states.clone(),{"const":"none"}]},"state":states, - "transition":{"type":"string","enum":["started","edited","submitted","revised","rebased","retried","cancelled","applied","rejected","review-returned","added","asked","answered"]}, + "transition":{"type":"string","enum":["started","edited","submitted","revised","rebased","retried","cancelled","applied","rejected","review-returned","added","asked","answered","messaged"]}, "effectDigest":nullable_digest.clone(),"authorityKind":{"enum":["caller","system","review"]}, "systemApplyGrantRevision":nullable_digest, - "turn":{"type":"string","enum":["party","official","nobody"]}}}) + "turn":{"type":"string","enum":["party","official","nobody"]}, + "messageFrom":{"enum":["party","official"]}}, + "if":{"properties":{"transition":{"const":"messaged"}}}, + "then":{"required":["messageFrom"]}, + "else":{"not":{"required":["messageFrom"]}}}) } pub fn source_hooks( @@ -263,9 +267,10 @@ fn exact_inventory(expected: &[CompiledEventDelivery], actual: &[&CompiledEventD }) } -#[cfg(all(test, feature = "runtime"))] +#[cfg(test)] #[path = "../tests/support/proposal_hooks_model.rs"] -mod test_model; +#[cfg_attr(not(feature = "runtime"), allow(dead_code))] +pub(crate) mod test_model; #[cfg(all(test, feature = "runtime"))] #[test] @@ -335,6 +340,7 @@ pub fn matching_transitions( ProposalEventTransition::Added, ProposalEventTransition::Asked, ProposalEventTransition::Answered, + ProposalEventTransition::Messaged, ] .into_iter() .filter(|transition| transitions.is_empty() || transitions.contains(transition)) diff --git a/crates/registry-breg/src/proposal_messages.rs b/crates/registry-breg/src/proposal_messages.rs new file mode 100644 index 0000000000..daed6a1ffe --- /dev/null +++ b/crates/registry-breg/src/proposal_messages.rs @@ -0,0 +1,362 @@ +// SPDX-License-Identifier: Apache-2.0 + +//! The message thread on one Proposal: text between its party (the owner or +//! the subject) and the office. The caller's admission decides the side a +//! message is written from; nothing here reads a token. Text leaves this +//! store only in a served document, never in an event, audit entry or log. + +use serde_json::{json, Value}; +use tokio_postgres::Transaction; +use uuid::Uuid; + +use crate::model::ProposalParty; +use crate::mutation::MutationError; + +/// The longest message, in UTF-8 bytes: the limit of answers and Casework notes. +pub(crate) const MAX_TEXT_BYTES: usize = 2000; +/// The newest messages a Proposal document carries. +pub(crate) const DOCUMENT_ITEMS: i64 = 20; +/// The most messages one page of the thread carries. +pub(crate) const MAX_PAGE_ITEMS: i64 = 50; + +/// The side of the thread a message is written from or read by. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub(crate) enum Side { + Party, + Official, +} + +impl Side { + /// A party-bound entry writes and reads as the party; any other grant + /// as the office. The writer does not choose. + pub(crate) fn of(party: Option) -> Self { + if party.is_some() { + Self::Party + } else { + Self::Official + } + } + + pub(crate) const fn as_str(self) -> &'static str { + match self { + Self::Party => "party", + Self::Official => "official", + } + } + + const fn read_position_column(self) -> &'static str { + match self { + Self::Party => "party_read_position", + Self::Official => "official_read_position", + } + } +} + +/// Text a person can read as written: not empty, within the byte limit, and +/// free of control characters other than line breaks and tabs, of the +/// characters that reorder how text displays, and of characters that do not +/// display at all. A carriage return is kept only before a line feed, as a +/// form post sends a line break. +pub(crate) fn valid_text(text: &str) -> bool { + let mut characters = text.chars().peekable(); + while let Some(character) = characters.next() { + let allowed = match character { + '\r' => characters.peek() == Some(&'\n'), + '\n' | '\t' => true, + _ => !character.is_control() && !hidden_or_reordering(character), + }; + if !allowed { + return false; + } + } + !text.trim().is_empty() && text.len() <= MAX_TEXT_BYTES +} + +/// Characters that reorder text, take no visible space, or carry hidden +/// tags, so a reader cannot see what was written. +fn hidden_or_reordering(character: char) -> bool { + matches!( + character, + '\u{061C}' + | '\u{200B}'..='\u{200F}' + | '\u{2028}'..='\u{202E}' + | '\u{2060}'..='\u{2064}' + | '\u{2066}'..='\u{2069}' + | '\u{FEFF}' + | '\u{E0000}'..='\u{E007F}' + ) +} + +/// Whether the thread has opened: it opens at the first Submit. +pub(crate) async fn opened( + tx: &Transaction<'_>, + action_id: &str, + proposal_id: Uuid, +) -> Result { + tx.query_one( + "SELECT EXISTS (SELECT 1 FROM registry_internal.registry_proposal_submissions + WHERE action_id=$1 AND proposal_id=$2)", + &[&action_id, &proposal_id], + ) + .await + .map(|row| row.get(0)) + .map_err(|_| MutationError::Unavailable) +} + +/// The number of messages one side has written. Each side has its own +/// share of the Action's `maximumCount`, so neither can close the thread +/// for the other. +pub(crate) async fn count( + tx: &Transaction<'_>, + action_id: &str, + proposal_id: Uuid, + side: Side, +) -> Result { + tx.query_one( + "SELECT count(*) FROM registry_internal.registry_proposal_messages + WHERE action_id=$1 AND proposal_id=$2 AND side=$3", + &[&action_id, &proposal_id, &side.as_str()], + ) + .await + .map(|row| row.get(0)) + .map_err(|_| MutationError::Unavailable) +} + +/// One message to append. The caller holds the Proposal's state row lock. +pub(crate) struct NewMessage<'a> { + pub action_id: &'a str, + pub proposal_id: Uuid, + pub submission_version: i64, + pub side: Side, + pub party_role: Option, + pub sent_by: &'a str, + pub text: &'a str, + pub maximum_count: u32, +} + +pub(crate) async fn append( + tx: &Transaction<'_>, + message: NewMessage<'_>, +) -> Result { + if !valid_text(message.text) { + return Err(MutationError::InvalidRequestAt( + crate::problem_location::RequestLocation::proposal_message_text(), + )); + } + if count(tx, message.action_id, message.proposal_id, message.side).await? + >= i64::from(message.maximum_count) + { + return Err(MutationError::ProposalMessageLimitReached); + } + let id = Uuid::new_v4(); + let party_role = match (message.side, message.party_role) { + (Side::Party, Some(ProposalParty::Owner)) => Some("owner"), + (Side::Party, Some(ProposalParty::Subject)) => Some("subject"), + (Side::Official, None) => None, + _ => return Err(MutationError::InvalidRequest), + }; + tx.execute( + "INSERT INTO registry_internal.registry_proposal_messages + (action_id,proposal_id,message_id,position,submission_version,side,party_role,sent_by,text) + SELECT $1,$2,$3,COALESCE(max(position),0)+1,$4,$5,$6,$7,$8 + FROM registry_internal.registry_proposal_messages + WHERE action_id=$1 AND proposal_id=$2", + &[ + &message.action_id, + &message.proposal_id, + &id, + &message.submission_version, + &message.side.as_str(), + &party_role, + &message.sent_by, + &message.text, + ], + ) + .await + .map_err(|_| MutationError::Unavailable)?; + Ok(id) +} + +/// What one side sees of the thread without its text. +pub(crate) struct Summary { + pub count: i64, + pub unread: i64, + pub last_sent_at: Option, +} + +impl Summary { + pub(crate) fn to_json(&self) -> Value { + let mut value = json!({"count":self.count,"unread":self.unread}); + if let Some(last) = &self.last_sent_at { + value["lastSentAt"] = json!(last); + } + value + } +} + +/// `unread` counts the other side's messages past the reader's side position. +pub(crate) async fn summary( + tx: &Transaction<'_>, + action_id: &str, + proposal_id: Uuid, + reader: Side, +) -> Result { + let row = tx + .query_one( + &format!( + "SELECT count(m.message_id), + count(m.message_id) FILTER (WHERE m.side<>$3 AND m.position>s.{}), + to_char(max(m.sent_at) AT TIME ZONE 'UTC','YYYY-MM-DD\"T\"HH24:MI:SS.US\"Z\"') + FROM registry_internal.registry_proposal_state s + LEFT JOIN registry_internal.registry_proposal_messages m + ON m.action_id=s.action_id AND m.proposal_id=s.proposal_id + WHERE s.action_id=$1 AND s.proposal_id=$2", + reader.read_position_column() + ), + &[&action_id, &proposal_id, &reader.as_str()], + ) + .await + .map_err(|_| MutationError::Unavailable)?; + Ok(Summary { + count: row.get(0), + unread: row.get(1), + last_sent_at: row.get(2), + }) +} + +/// The newest messages before `before` (a position), newest first. Each +/// item says whether `reader` wrote it; it never names who did. +pub(crate) async fn page( + tx: &Transaction<'_>, + action_id: &str, + proposal_id: Uuid, + before: Option, + limit: i64, + reader: &str, +) -> Result, MutationError> { + let rows = tx + .query( + "SELECT message_id,position,side,party_role,sent_by,text, + to_char(sent_at AT TIME ZONE 'UTC','YYYY-MM-DD\"T\"HH24:MI:SS.US\"Z\"') + FROM registry_internal.registry_proposal_messages + WHERE action_id=$1 AND proposal_id=$2 AND ($3::bigint IS NULL OR position<$3) + ORDER BY position DESC LIMIT $4", + &[&action_id, &proposal_id, &before, &limit], + ) + .await + .map_err(|_| MutationError::Unavailable)?; + Ok(rows + .iter() + .map(|row| (row.get(1), message_item(row, reader))) + .collect()) +} + +/// Check retained items outside the newest-items window of an admitted thread. +pub(crate) async fn receipt_items_match( + tx: &Transaction<'_>, + action_id: &str, + proposal_id: Uuid, + items: &[Value], + reader: &str, +) -> Result { + let Some(ids) = items + .iter() + .map(|item| item.get("id")?.as_str()?.parse::().ok()) + .collect::>>() + else { + return Ok(false); + }; + let rows = tx + .query( + "SELECT message_id,position,side,party_role,sent_by,text, + to_char(sent_at AT TIME ZONE 'UTC','YYYY-MM-DD\"T\"HH24:MI:SS.US\"Z\"') + FROM registry_internal.registry_proposal_messages + WHERE action_id=$1 AND proposal_id=$2 AND message_id=ANY($3) + ORDER BY position DESC", + &[&action_id, &proposal_id, &ids], + ) + .await + .map_err(|_| MutationError::Unavailable)?; + Ok(rows.len() == items.len() + && rows + .iter() + .zip(items) + .all(|(row, item)| message_item(row, reader) == *item)) +} + +fn message_item(row: &tokio_postgres::Row, reader: &str) -> Value { + let mut item = json!({"id":row.get::<_, Uuid>(0),"from":row.get::<_, String>(2), + "mine":row.get::<_, Option>(4).as_deref()==Some(reader),"sentAt":row.get::<_, String>(6)}); + if let Some(role) = row.get::<_, Option>(3) { + item["partyRole"] = json!(role); + } + // An erased message keeps its place and loses its text. + if let Some(text) = row.get::<_, Option>(5) { + item["text"] = json!(text); + } + item +} + +/// Move `reader`'s side forward through the message `through`. Returns +/// whether the position moved; reading again, or backwards, changes nothing. +/// The caller holds the Proposal's state row lock. +pub(crate) async fn mark_read( + tx: &Transaction<'_>, + action_id: &str, + proposal_id: Uuid, + reader: Side, + through: Uuid, +) -> Result { + let position: i64 = tx + .query_opt( + "SELECT position FROM registry_internal.registry_proposal_messages + WHERE action_id=$1 AND proposal_id=$2 AND message_id=$3", + &[&action_id, &proposal_id, &through], + ) + .await + .map_err(|_| MutationError::Unavailable)? + .ok_or_else(|| { + MutationError::InvalidRequestAt( + crate::problem_location::RequestLocation::proposal_message_through(), + ) + })? + .get(0); + let column = reader.read_position_column(); + let changed = tx + .execute( + &format!( + "UPDATE registry_internal.registry_proposal_state SET {column}=$3 + WHERE action_id=$1 AND proposal_id=$2 AND {column}<$3" + ), + &[&action_id, &proposal_id, &position], + ) + .await + .map_err(|_| MutationError::Unavailable)?; + Ok(changed == 1) +} + +/// Correlated with the Proposal row `p`: an office message the party has +/// not read. While the Proposal is open this makes it the party's turn. +pub(crate) const PARTY_UNREAD_SQL: &str = "EXISTS ( + SELECT 1 FROM registry_internal.registry_proposal_messages m + WHERE m.action_id=p.action_id AND m.proposal_id=p.proposal_id + AND m.side='official' AND m.position>p.party_read_position)"; + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn text_is_readable_as_written_and_bounded_in_utf8_bytes() { + assert!(valid_text("Is a scan enough?\nThanks.")); + assert!(valid_text("bold & ")); + assert!(valid_text(&"\u{e9}".repeat(1000))); + assert!(!valid_text(&"\u{e9}".repeat(1001))); + assert!(!valid_text("")); + assert!(!valid_text(" \n ")); + assert!(!valid_text("Bell \u{0007}")); + for reordering in ['\u{202E}', '\u{2066}', '\u{200F}', '\u{061C}'] { + assert!(!valid_text(&format!("Reordered {reordering}text"))); + } + } +} diff --git a/crates/registry-breg/src/proposal_prepare.rs b/crates/registry-breg/src/proposal_prepare.rs index de8392fccb..8b666ed80b 100644 --- a/crates/registry-breg/src/proposal_prepare.rs +++ b/crates/registry-breg/src/proposal_prepare.rs @@ -26,6 +26,8 @@ pub(crate) struct ResolvedProposalTargets { pub records: BTreeMap<(String, Uuid), Operation>, } +pub(crate) type ProposalPatchBases = BTreeMap<(String, Uuid), (i64, Map)>; + type ProposalCreateFields = BTreeMap<(String, Uuid), Map>; #[derive(Clone, Debug)] @@ -226,6 +228,77 @@ pub(crate) fn materialize_create_fields( Ok(creates) } +/// Check candidate boundaries before reserving generated identifiers. +pub(crate) async fn authorize_candidates_before_allocation( + tx: &tokio_postgres::Transaction<'_>, + registry: &CompiledRegistry, + authority: &crate::postgres::ProposalAuthority, + input: &Map, + resolved: &ResolvedProposalTargets, + creates: &ProposalCreateFields, + bases: &ProposalPatchBases, +) -> Result<(), MutationError> { + use crate::mutation::probe_action_memberships; + + let profile = authority.common.access_profile(); + for ((entity, id), snapshot) in creates { + let compiled = ®istry.entities()[entity]; + if !authority + .authorizes_create_before_allocation(compiled, *id, snapshot) + .map_err(|_| MutationError::PreconditionFailed)? + { + return Err(MutationError::PreconditionFailed); + } + probe_action_memberships( + tx, + profile, + authority.target_membership(entity), + Some(*id), + snapshot, + ) + .await?; + } + let mut patches = BTreeMap::new(); + for effect in resolved + .effects + .iter() + .filter(|effect| effect.operation == Operation::Patch) + { + let entity = &effect.target.entity_id; + let key = (entity.clone(), resolved.effect_records[&effect.id]); + let after = patches + .entry(key.clone()) + .or_insert_with(|| bases[&key].1.clone()); + for mutation in &effect.mutations { + match mutation { + CompiledPlanMutation::Set { field, value } => { + after.insert(field.clone(), resolve_plan_value(input, resolved, value)?); + } + CompiledPlanMutation::Clear { field } => { + after.insert(field.clone(), Value::Null); + } + } + } + } + for ((entity, id), snapshot) in patches { + if !authority + .authorizes_snapshot(®istry.entities()[&entity], id, &snapshot) + .map_err(|_| MutationError::PreconditionFailed)? + { + return Err(MutationError::PreconditionFailed); + } + probe_action_memberships( + tx, + profile, + authority.target_membership(&entity), + Some(id), + &snapshot, + ) + .await?; + } + Ok(()) +} + fn resolve_plan_value( input: &Map, resolved: &ResolvedProposalTargets, @@ -269,7 +342,7 @@ pub(crate) fn prepare( input_revision: i64, package_fingerprint: &str, resolved: &ResolvedProposalTargets, - bases: BTreeMap<(String, Uuid), (i64, Map)>, + bases: ProposalPatchBases, guard_bases: BTreeMap)>, ) -> Result { let create_fields = materialize_create_fields(registry, input, resolved)?; @@ -295,7 +368,7 @@ pub(crate) fn prepare_with_reserved_create_fields( package_fingerprint: &str, resolved: &ResolvedProposalTargets, reserved_create_fields: BTreeMap<(String, Uuid), Map>, - bases: BTreeMap<(String, Uuid), (i64, Map)>, + bases: ProposalPatchBases, guard_bases: BTreeMap)>, ) -> Result { let CompiledActionExecution::Proposal { proposal: policy } = &action.execution else { diff --git a/crates/registry-breg/src/proposal_prepare/tests.rs b/crates/registry-breg/src/proposal_prepare/tests.rs index caf57b2641..e429ecf82d 100644 --- a/crates/registry-breg/src/proposal_prepare/tests.rs +++ b/crates/registry-breg/src/proposal_prepare/tests.rs @@ -33,9 +33,9 @@ fn source(effects: Value) -> Value { {"id":"two","type":"reference","target":"target","classification":"internal"}, {"id":"value","type":"string","maximumLength":64,"required":true,"classification":"internal"} ],"plan":{"type":"fixed","effects":effects}}}, - "accessProfiles":{"submitter": {"default":true,"principalClaim":"sub","requiredScopes":"unrestricted","permissions":{ + "accessProfiles":{"submitter": {"default":true,"principalClaim":"sub","requiredScopes":["proposals:write"],"permissions":{ "actions":[{"action":"change-target","operations":["start"],"targets":[{"recordType":"target","rowBoundaries":"unrestricted"}]}], - "proposals":[{"action":"change-target","operations":["get","submit","apply"],"ownership":"caller","targets":[{"recordType":"target","rowBoundaries":"unrestricted"}]}] + "proposals":[{"action":"change-target","operations":["get","submit","apply"],"party":"owner","targets":[{"recordType":"target","rowBoundaries":"unrestricted"}]}] }}} }) } diff --git a/crates/registry-breg/src/proposal_retention.rs b/crates/registry-breg/src/proposal_retention.rs index cbf9a184f4..d134bb9b13 100644 --- a/crates/registry-breg/src/proposal_retention.rs +++ b/crates/registry-breg/src/proposal_retention.rs @@ -145,6 +145,9 @@ pub struct ProposalDetailErasure { pub review_asks: u64, pub review_answers: u64, pub review_answer_files: u64, + pub messages: u64, + pub form_entries: u64, + pub review_answer_form_entries: u64, } #[derive(Clone, Debug, Eq, PartialEq, Serialize)] @@ -1251,6 +1254,94 @@ async fn load_erasure_plan( }) } +// A later round's response can include the earlier thread. Erase that +// exact receipt as well when its stored body contains text from this version. +// The message ID still identifies the round after its live text is erased. +const DETAIL_RECEIPT_KEYS: &str = " + SELECT l.key_reference + FROM registry_internal.registry_proposal_idempotency_links l + WHERE l.action_id=$1 AND l.proposal_id=$2 + AND (l.submission_version=$3 OR EXISTS ( + SELECT 1 FROM registry_internal.registry_proposal_messages m + WHERE m.action_id=$1 AND m.proposal_id=$2 + AND m.submission_version=$3 + AND jsonb_path_exists( + coalesce( + convert_from(receipt.response_body,'UTF8')::jsonb #> '{messages,items}', + convert_from(receipt.response_body,'UTF8')::jsonb #> '{context,messages,items}', + convert_from(receipt.response_body,'UTF8')::jsonb #> '{items}' + ), + '$[*] ? (@.id == $id && exists(@.text))', + jsonb_build_object('id',m.message_id) + ) + ))"; + +#[cfg(all(test, feature = "postgres-test"))] +mod receipt_erasure_tests { + use super::*; + use serde_json::json; + + #[tokio::test] + async fn message_receipt_erasure_covers_each_document_shape() { + let url = std::env::var("BREG_TEST_DATABASE_URL") + .expect("BREG_TEST_DATABASE_URL is required for erasure selection"); + let (client, connection) = tokio_postgres::connect(&url, tokio_postgres::NoTls) + .await + .expect("connect to disposable PostgreSQL"); + let connection = tokio::spawn(connection); + let message = Uuid::from_u128(1); + let item = json!({"id":message,"text":"example"}); + let receipts = json!({ + "proposal":{"version":2,"body":{"messages":{"items":[item]}}}, + "review":{"version":2,"body":{"context":{"messages":{"items":[item]}}}}, + "thread":{"version":2,"body":{"count":1,"items":[item]}}, + "textless":{"version":2,"body":{"count":1,"items":[{"id":message}]}}, + "unrelated":{"version":2,"body":{"count":1,"items":[{"id":Uuid::from_u128(2),"text":"example"}]}}, + "scoped":{"version":1,"body":{"state":"submitted"}} + }); + // Use the production selector over synthetic rows without creating or + // updating a registry. Repeat it with the source text already erased. + let selector = DETAIL_RECEIPT_KEYS.replace("registry_internal.", ""); + let query = format!( + "WITH registry_proposal_messages(action_id, proposal_id, submission_version, message_id, text) AS ( + VALUES ($1::text, $2::uuid, $3::bigint, $4::uuid, $5::text) + ), receipts AS ( + SELECT key AS key_reference, convert_to((value->'body')::text,'UTF8') AS response_body, + (value->>'version')::bigint AS submission_version + FROM jsonb_each($6) + ), registry_proposal_idempotency_links AS ( + SELECT key_reference, $1 AS action_id, $2 AS proposal_id, submission_version + FROM receipts + ) + SELECT key_reference FROM receipts receipt + WHERE key_reference IN ({selector}) ORDER BY key_reference" + ); + for text in [Some("example"), None] { + let rows = client + .query( + &query, + &[ + &"synthetic", + &Uuid::from_u128(3), + &1_i64, + &message, + &text, + &receipts, + ], + ) + .await + .expect("evaluate receipt erasure selection"); + let keys = rows + .iter() + .map(|row| row.get::<_, &str>(0)) + .collect::>(); + assert_eq!(keys, ["proposal", "review", "scoped", "thread"]); + } + drop(client); + connection.await.unwrap().unwrap(); + } +} + async fn count_request_detail_erasure( transaction: &tokio_postgres::Transaction<'_>, scope: ProposalDetailErasureScope<'_>, @@ -1258,7 +1349,7 @@ async fn count_request_detail_erasure( ) -> Result { let row = transaction .query_one( - "SELECT + &format!("SELECT (SELECT count(*) FROM registry_internal.registry_proposal_submissions WHERE action_id = $1 AND proposal_id = $2 @@ -1269,15 +1360,8 @@ async fn count_request_detail_erasure( AND proposal_id = $2 AND submission_version = $3 AND (base_snapshot IS NOT NULL OR after_snapshot IS NOT NULL)), - (SELECT count(*) FROM registry_internal.registry_idempotency - WHERE key_reference IN ( - SELECT key_reference - FROM registry_internal.registry_proposal_idempotency_links - WHERE action_id = $1 - AND proposal_id = $2 - AND submission_version = $3 - ) - AND response_body IS NOT NULL), + (SELECT count(*) FROM registry_internal.registry_idempotency receipt + WHERE response_body IS NOT NULL AND key_reference IN ({DETAIL_RECEIPT_KEYS})), (SELECT count(*) FROM registry_internal.registry_proposal_applications WHERE action_id = $1 AND proposal_id = $2 @@ -1292,7 +1376,7 @@ async fn count_request_detail_erasure( (SELECT count(*) FROM registry_internal.registry_proposal_review_submissions s WHERE s.action_id=$1 AND s.proposal_id=$2 AND s.submission_version=$3 - AND s.create_request <> '{}'::jsonb + AND s.create_request <> '{{}}'::jsonb AND (s.state IN ('cancelled','failed') OR ( s.state='accepted' AND EXISTS ( SELECT 1 @@ -1306,7 +1390,7 @@ async fn count_request_detail_erasure( FROM registry_internal.registry_proposal_review_submissions s WHERE s.action_id=$1 AND s.proposal_id=$2 AND s.submission_version=$3 AND s.accepted_binding IS NOT NULL - AND s.accepted_binding <> '{}'::jsonb + AND s.accepted_binding <> '{{}}'::jsonb AND (s.state IN ('cancelled','failed') OR ( s.state='accepted' AND EXISTS ( SELECT 1 @@ -1318,10 +1402,13 @@ async fn count_request_detail_erasure( ))), (SELECT count(*) FROM registry_internal.registry_proposal_review_results WHERE action_id=$1 AND proposal_id=$2 AND submission_version=$3 - AND result <> '{}'::jsonb), + AND result <> '{{}}'::jsonb), (SELECT count(*) FROM registry_internal.registry_proposal_review_asks WHERE action_id=$1 AND proposal_id=$2 AND submission_version=$3 AND text IS NOT NULL), (SELECT count(*) FROM registry_internal.registry_proposal_review_ask_answers WHERE action_id=$1 AND proposal_id=$2 AND submission_version=$3 AND detail_erased_at IS NULL), - (SELECT count(*) FROM registry_internal.registry_proposal_review_ask_files WHERE action_id=$1 AND proposal_id=$2 AND submission_version=$3)", + (SELECT count(*) FROM registry_internal.registry_proposal_review_ask_files WHERE action_id=$1 AND proposal_id=$2 AND submission_version=$3), + (SELECT count(*) FROM registry_internal.registry_proposal_form_entries WHERE action_id=$1 AND proposal_id=$2 AND submission_version=$3 AND detail_erased_at IS NULL), + (SELECT count(*) FROM registry_internal.registry_proposal_review_ask_form_entries WHERE action_id=$1 AND proposal_id=$2 AND submission_version=$3), + (SELECT count(*) FROM registry_internal.registry_proposal_messages WHERE action_id=$1 AND proposal_id=$2 AND submission_version=$3 AND detail_erased_at IS NULL)"), &[ &scope.action_id, &scope.proposal_id, @@ -1343,6 +1430,9 @@ async fn count_request_detail_erasure( review_asks: count_to_u64(row.get(8))?, review_answers: count_to_u64(row.get(9))?, review_answer_files: count_to_u64(row.get(10))?, + form_entries: count_to_u64(row.get(11))?, + review_answer_form_entries: count_to_u64(row.get(12))?, + messages: count_to_u64(row.get(13))?, }) } @@ -1369,6 +1459,24 @@ async fn erase_proposal_detail_in_transaction( .map_err(map_retention_error)?; // Remove citation references with their source-owned answer detail before // attachment erasure considers whether any bytes are still referenced. + let version = &[ + &scope.action_id as &(dyn tokio_postgres::types::ToSql + Sync), + &scope.proposal_id, + &scope.submission_version, + ]; + let review_answer_form_entries = transaction + .execute( + "DELETE FROM registry_internal.registry_proposal_review_ask_form_entries + WHERE action_id=$1 AND proposal_id=$2 AND submission_version=$3", + version, + ) + .await + .map_err(map_retention_error)?; + let form_entries = transaction.execute( + "UPDATE registry_internal.registry_proposal_form_entries + SET input=NULL, added_by=NULL, detail_erased_at=transaction_timestamp() + WHERE action_id=$1 AND proposal_id=$2 AND submission_version=$3 AND detail_erased_at IS NULL", version, + ).await.map_err(map_retention_error)?; let review_answer_files=transaction.execute("DELETE FROM registry_internal.registry_proposal_review_ask_files WHERE action_id=$1 AND proposal_id=$2 AND submission_version=$3",&[&scope.action_id,&scope.proposal_id,&scope.submission_version]).await.map_err(map_retention_error)?; let review_answers=transaction.execute("UPDATE registry_internal.registry_proposal_review_ask_answers SET text=NULL,answered_by=NULL,detail_erased_at=transaction_timestamp(),claim_token=NULL,lease_until=NULL,delivery_state=CASE WHEN delivery_state='pending' THEN 'superseded' ELSE delivery_state END WHERE action_id=$1 AND proposal_id=$2 AND submission_version=$3 AND detail_erased_at IS NULL",&[&scope.action_id,&scope.proposal_id,&scope.submission_version]).await.map_err(map_retention_error)?; let review_asks=transaction.execute("UPDATE registry_internal.registry_proposal_review_asks SET text=NULL,detail_erased_at=transaction_timestamp() WHERE action_id=$1 AND proposal_id=$2 AND submission_version=$3 AND text IS NOT NULL",&[&scope.action_id,&scope.proposal_id,&scope.submission_version]).await.map_err(map_retention_error)?; @@ -1495,30 +1603,26 @@ async fn erase_proposal_detail_in_transaction( .map_err(map_retention_error)?; let idempotency_results = transaction .execute( - "UPDATE registry_internal.registry_idempotency - SET response_body = NULL, - erased_at = transaction_timestamp() - WHERE key_reference IN ( - SELECT key_reference - FROM registry_internal.registry_proposal_idempotency_links - WHERE action_id = $1 - AND proposal_id = $2 - AND submission_version = $3 - ) - AND response_body IS NOT NULL", - &[ - &scope.action_id, - &scope.proposal_id, - &scope.submission_version, - ], + &format!( + "UPDATE registry_internal.registry_idempotency receipt + SET response_body=NULL,erased_at=transaction_timestamp() + WHERE response_body IS NOT NULL AND key_reference IN ({DETAIL_RECEIPT_KEYS})" + ), + version, ) .await .map_err(map_retention_error)?; + let messages = transaction.execute( + "UPDATE registry_internal.registry_proposal_messages + SET text=NULL,sent_by=NULL,detail_erased_at=transaction_timestamp() + WHERE action_id=$1 AND proposal_id=$2 AND submission_version=$3 AND detail_erased_at IS NULL", + version, + ).await.map_err(map_retention_error)?; let draft_inputs = if plan.erase_draft_input { transaction .execute( "UPDATE registry_internal.registry_proposal_state - SET input=NULL,action_title=NULL, + SET input=NULL,action_title=NULL,subject_reference=NULL, detail_erased_at=transaction_timestamp(),updated_at=transaction_timestamp() WHERE action_id=$1 AND proposal_id=$2 AND detail_erased_at IS NULL", &[&scope.action_id, &scope.proposal_id], @@ -1549,6 +1653,9 @@ async fn erase_proposal_detail_in_transaction( review_asks, review_answers, review_answer_files, + form_entries, + review_answer_form_entries, + messages, }; if erasure != plan.erasure { return Err(ProposalRetentionError::Unavailable); @@ -1637,6 +1744,9 @@ fn retention_terminal_entry( .and_then(|count| count.checked_add(erasure.review_asks)) .and_then(|count| count.checked_add(erasure.review_answers)) .and_then(|count| count.checked_add(erasure.review_answer_files)) + .and_then(|count| count.checked_add(erasure.messages)) + .and_then(|count| count.checked_add(erasure.form_entries)) + .and_then(|count| count.checked_add(erasure.review_answer_form_entries)) .ok_or(ProposalRetentionError::Unavailable)?; terminal_entry( profile, diff --git a/crates/registry-breg/src/proposal_store.rs b/crates/registry-breg/src/proposal_store.rs index 91068e69cf..0f8e69c605 100644 --- a/crates/registry-breg/src/proposal_store.rs +++ b/crates/registry-breg/src/proposal_store.rs @@ -33,6 +33,7 @@ pub(crate) const PROPOSAL_TABLES: &[(&str, &[&str])] = &[ ("registry_proposal_evidence_uses", &["INSERT"]), ("registry_proposal_results", &["INSERT", "SELECT"]), ("registry_proposal_idempotency_links", &["INSERT", "SELECT"]), + ("registry_proposal_messages", &["INSERT", "SELECT"]), ]; pub(crate) async fn install( @@ -168,6 +169,12 @@ pub(crate) async fn install( ON registry_internal.registry_proposal_targets (target_entity_id, target_record_id); CREATE INDEX IF NOT EXISTS registry_proposal_queue ON registry_internal.registry_proposal_state (action_id, state, proposal_id); + ALTER TABLE registry_internal.registry_proposal_state + ADD COLUMN IF NOT EXISTS subject_reference text + CHECK (subject_reference IS NULL OR subject_reference <> ''); + CREATE INDEX IF NOT EXISTS registry_proposal_subject + ON registry_internal.registry_proposal_state (subject_reference, proposal_id) + WHERE subject_reference IS NOT NULL; CREATE TABLE IF NOT EXISTS registry_internal.registry_proposal_applications ( action_id text NOT NULL, proposal_id uuid NOT NULL, @@ -230,6 +237,30 @@ pub(crate) async fn install( CREATE INDEX IF NOT EXISTS registry_proposal_idempotency_by_request ON registry_internal.registry_proposal_idempotency_links (action_id, proposal_id, submission_version); + ALTER TABLE registry_internal.registry_proposal_state + ADD COLUMN IF NOT EXISTS party_read_position bigint NOT NULL DEFAULT 0 + CHECK (party_read_position >= 0), + ADD COLUMN IF NOT EXISTS official_read_position bigint NOT NULL DEFAULT 0 + CHECK (official_read_position >= 0); + CREATE TABLE IF NOT EXISTS registry_internal.registry_proposal_messages ( + action_id text NOT NULL, + proposal_id uuid NOT NULL, + message_id uuid NOT NULL, + position bigint NOT NULL CHECK (position > 0), + submission_version bigint NOT NULL CHECK (submission_version > 0), + side text NOT NULL CHECK (side IN ('party','official')), + party_role text CHECK (party_role IS NULL OR party_role IN ('owner','subject')), + sent_by text CHECK (sent_by IS NULL OR sent_by <> ''), + text text CHECK (text IS NULL OR octet_length(text) BETWEEN 1 AND 2000), + sent_at timestamptz NOT NULL DEFAULT transaction_timestamp(), + detail_erased_at timestamptz, + PRIMARY KEY (action_id, proposal_id, message_id), + UNIQUE (action_id, proposal_id, position), + FOREIGN KEY (action_id, proposal_id) + REFERENCES registry_internal.registry_proposal_state, + CHECK ((side = 'party') = (party_role IS NOT NULL)), + CHECK ((text IS NULL) = (detail_erased_at IS NOT NULL)) + ); " ).await.map_err(|_| MutationError::Unavailable)?; crate::attachment_store::install(client, runtime_role).await?; @@ -350,6 +381,9 @@ pub(crate) async fn load_task_authority( #[allow(dead_code)] pub(crate) struct ProposalWorkflowHeader { pub owner_reference: String, + /// Bound once, at the first Submit of an Action that declares a subject. + /// Like `owner_reference`, an unkeyed hash that is never projected. + pub subject_reference: Option, pub state: String, pub submission_version: i64, pub workflow_revision: i64, @@ -363,6 +397,7 @@ impl std::fmt::Debug for ProposalWorkflowHeader { formatter .debug_struct("ProposalWorkflowHeader") .field("has_owner_reference", &!self.owner_reference.is_empty()) + .field("has_subject_reference", &self.subject_reference.is_some()) .field("state", &self.state) .field("submission_version", &self.submission_version) .field("workflow_revision", &self.workflow_revision) @@ -404,6 +439,29 @@ pub(crate) async fn initialize_draft( Ok(()) } +/// Bind the Proposal's subject. The caller holds the state lock and has +/// compared any reference already bound; a bound subject is never replaced. +pub(crate) async fn bind_subject( + transaction: &Transaction<'_>, + entity_id: &str, + record_id: Uuid, + subject_reference: &str, +) -> Result<(), MutationError> { + let updated = transaction + .execute( + "UPDATE registry_internal.registry_proposal_state SET subject_reference=$3 + WHERE action_id=$1 AND proposal_id=$2 + AND (subject_reference IS NULL OR subject_reference=$3)", + &[&entity_id, &record_id, &subject_reference], + ) + .await + .map_err(|_| MutationError::Unavailable)?; + if updated != 1 { + return Err(MutationError::Unavailable); + } + Ok(()) +} + /// Store the authored Action input directly, preserving missing versus null. /// The caller owns the state lock, transition fence, and current authority. pub(crate) async fn save_draft_input( @@ -525,6 +583,8 @@ pub(crate) struct ProposalDocument { pub input_targets: Vec<(String, Uuid)>, pub blocked_reason: Option, pub ask_open: bool, + /// An office message on the thread the party has not read. + pub party_message_unread: bool, /// When the draft was started, as RFC 3339 UTC text. pub created_at: String, pub header: ProposalWorkflowHeader, @@ -562,9 +622,11 @@ pub(crate) async fn load_document_with_ask( let sql = format!( "SELECT action_id, action_revision, action_title, input, blocked_reason, input_targets, to_char(created_at AT TIME ZONE 'UTC','YYYY-MM-DD\"T\"HH24:MI:SS.US\"Z\"'), - CASE WHEN $2::bigint=p.workflow_revision THEN $3::boolean ELSE ({OPEN_ASK_SQL}) END - FROM registry_internal.registry_proposal_state p WHERE proposal_id=$1{}", - match lock { + CASE WHEN $2::bigint=p.workflow_revision THEN $3::boolean ELSE ({OPEN_ASK_SQL}) END, + {PARTY_UNREAD_SQL} + FROM registry_internal.registry_proposal_state p WHERE proposal_id=$1{lock}", + PARTY_UNREAD_SQL = crate::proposal_messages::PARTY_UNREAD_SQL, + lock = match lock { DocumentLock::None => "", DocumentLock::Share => " FOR SHARE", DocumentLock::Update => " FOR UPDATE", @@ -597,6 +659,7 @@ pub(crate) async fn load_document_with_ask( blocked_reason: row.get(4), created_at: row.get(6), ask_open: row.get(7), + party_message_unread: row.get(8), header, input_targets: serde_json::from_value(row.get(5)) .map_err(|_| MutationError::Unavailable)?, @@ -773,7 +836,7 @@ pub(crate) async fn load_header( "SELECT s.owner_reference, s.state, s.submission_version, s.workflow_revision, COALESCE(s.detail_erased_at IS NOT NULL, false) OR COALESCE(p.erased_at IS NOT NULL, false), a.applied_by, - a.reason_present + a.reason_present, s.subject_reference FROM registry_internal.registry_proposal_state s LEFT JOIN registry_internal.registry_proposal_submissions p ON p.action_id = s.action_id @@ -808,6 +871,7 @@ pub(crate) async fn load_header( // The applications join is outer: a request without an application has // no reason to record. application_reason_present: row.get::<_, Option>(6).unwrap_or(false), + subject_reference: row.get(7), }) } @@ -1463,11 +1527,14 @@ mod tests { current_proposal_erased: false, applier_reference: Some("private-applier-reference-canary".to_owned()), application_reason_present: true, + subject_reference: Some("private-subject-reference-canary".to_owned()), }; let debug = format!("{header:?}"); assert!(!debug.contains("private-owner-reference-canary")); assert!(!debug.contains("private-applier-reference-canary")); + assert!(!debug.contains("private-subject-reference-canary")); assert!(debug.contains("has_owner_reference: true")); + assert!(debug.contains("has_subject_reference: true")); assert!(debug.contains("has_applier_reference: true")); } diff --git a/crates/registry-breg/src/proposal_subject.rs b/crates/registry-breg/src/proposal_subject.rs new file mode 100644 index 0000000000..35df9ce4f0 --- /dev/null +++ b/crates/registry-breg/src/proposal_subject.rs @@ -0,0 +1,237 @@ +// SPDX-License-Identifier: Apache-2.0 +//! A Record field a Proposal subject is read from decides who may follow +//! that Proposal, so writing it is authority, as writing a membership +//! principal is. + +use std::collections::{BTreeMap, BTreeSet}; + +use crate::contract::{ + ActionExecutionSource, ActionPlanSource, ActionSource, BoundaryOperator, EntitySource, + FieldTypeSource, Operation, ProjectAccessProfileSource, ProposalOperation, RegistryProject, + RowBoundarySource, +}; +use crate::diagnostics::Diagnostic; + +fn refuse(location: &str, record_type: &str, field: &str, errors: &mut Vec) { + errors.push(Diagnostic::error( + "breg.proposal.subject-field-write", + location, + &format!( + "`{record_type}.{field}` names the subject of a Proposal, so whoever writes it chooses who may follow that Proposal. Grant this write without row boundaries to staff who may decide who a Record is about, bound it on `{field}` by the profile's own principal claim, or use a Proposal Action with required review or manual application" + ), + )); +} + +/// The Record type and field each Action's `subject.field` reads. +fn subject_fields( + actions: &BTreeMap, +) -> BTreeSet<(String, String)> { + actions + .values() + .filter_map(|collected| { + let action = &collected.source; + let ActionExecutionSource::Proposal { proposal } = &action.execution else { + return None; + }; + let subject = proposal.subject.as_ref()?; + let field = subject.field.as_ref()?; + action + .inputs + .iter() + .find(|input| input.id == subject.input) + .and_then(|input| match &input.field_type { + FieldTypeSource::Reference { target, .. } => { + Some((target.clone(), field.clone())) + } + _ => None, + }) + }) + .collect() +} + +/// Whether a grant's rows let its writer name anyone in `field`: it is +/// bounded, yet not on `field` by the profile's own principal claim. A grant +/// with no boundary at all is unrestricted by the author's choice. +fn bounded_off_field( + rows: &[RowBoundarySource], + has_memberships: bool, + field: &str, + principal_claim: &str, +) -> bool { + (!rows.is_empty() || has_memberships) + && !rows.iter().any(|row| { + row.field == field + && row.operator == BoundaryOperator::Equals + && row.claim == principal_claim + }) +} + +/// Whether a plan can set `field` of `record_type` with no person deciding: +/// an immediate Action, or a Proposal Action with no required review that the +/// built-in executor applies. A reviewed or manually applied Proposal puts a +/// person between the writer and the write. +fn plan_sets_field(action: &ActionSource, record_type: &str, field: &str) -> bool { + if let ActionExecutionSource::Proposal { proposal } = &action.execution { + if matches!( + proposal.review, + crate::contract::ProposalReviewSource::Required { .. } + ) || matches!( + proposal.application, + crate::contract::ProposalApplicationSource::Manual {} + ) { + return false; + } + } + match &action.plan { + ActionPlanSource::Fixed { effects } => effects.iter().any(|effect| { + crate::membership::writes_target(action, &effect.target, record_type) + && matches!(effect.operation, Operation::Create | Operation::Patch) + && effect.set.contains_key(field) + }), + ActionPlanSource::Function { writes, .. } => writes.iter().any(|ceiling| { + crate::membership::writes_target(action, &ceiling.target, record_type) + && matches!(ceiling.operation, Operation::Create | Operation::Patch) + && ceiling.fields.iter().any(|candidate| candidate == field) + }), + } +} + +fn plan_target_grants<'a>( + profile: &'a ProjectAccessProfileSource, + record_type: &'a str, +) -> impl Iterator { + let actions = profile.permissions.actions.iter().filter_map(move |grant| { + let target = grant + .targets + .iter() + .find(|target| target.entity == record_type)?; + Some(( + "actions", + grant.action.as_str(), + target.row_boundaries.as_slice(), + !target.membership_row_boundaries.is_empty(), + )) + }); + // Submit freezes the plan under its own target grant and can enqueue + // automatic application. Draft edits cannot freeze a plan, and recovery + // uses the plan already frozen by Submit. + let proposals = profile + .permissions + .proposals + .iter() + .filter(|grant| grant.operations.contains(&ProposalOperation::Submit)) + .filter_map(move |grant| { + let target = grant + .targets + .iter() + .find(|target| target.record_type == record_type)?; + Some(( + "proposals", + grant.action.as_str(), + target.row_boundaries.as_slice(), + !target.membership_row_boundaries.is_empty(), + )) + }); + actions.chain(proposals) +} + +/// Refuse a bounded grant that can set a field a Proposal subject is read +/// from: a direct Create, Batch, Import or Patch of it, or an Action or +/// Proposal Submit grant whose plan sets it with no person deciding. +/// Unrestricted grants, grants bounded on the field by their own principal, +/// and reviewed or manually applied Proposal Actions stay admitted. +pub(crate) fn validate_field_writes( + project: &RegistryProject, + actions: &BTreeMap, + entities: &BTreeMap, + errors: &mut Vec, +) { + for (record_type, field) in subject_fields(actions) { + let Some(entity) = entities.get(&record_type) else { + continue; + }; + for grant in &entity.access_profiles { + let writes = grant.operations.iter().any(|operation| { + matches!( + operation, + Operation::Create | Operation::Batch | Operation::Import | Operation::Patch + ) + }) && grant.writable_fields.contains(&field); + if writes + && bounded_off_field( + &grant.row_boundaries, + !grant.membership_boundaries.is_empty(), + &field, + &grant.principal_claim, + ) + { + refuse( + &format!( + "recordTypes[id={record_type}].accessProfiles[id={}].writableFields", + grant.id + ), + &record_type, + &field, + errors, + ); + } + } + for profile in &project.access_profiles { + for (surface, action, rows, has_memberships) in + plan_target_grants(profile, &record_type) + { + if bounded_off_field(rows, has_memberships, &field, &profile.principal_claim) + && actions.get(action).is_some_and(|collected| { + plan_sets_field(&collected.source, &record_type, &field) + }) + { + refuse( + &format!( + "accessProfiles[id={}].permissions.{surface}[action={action}].targets[recordType={record_type}]", + profile.id + ), + &record_type, + &field, + errors, + ); + } + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn plan_targets_include_action_and_proposal_write_permissions() { + let target = serde_json::json!({"recordType":"entry","rowBoundaries":"unrestricted"}); + let profile = serde_json::from_value(serde_json::json!({ + "id":"editor", "principalClaim":"sub", "requiredScopes":["entry:edit"], + "permissions": { + "actions":[ + {"action":"update-entry", "operations":["invoke"], "targets":[target.clone()]}, + {"action":"propose-change", "operations":["start"], "targets":[target.clone()]} + ], + "proposals":[ + {"action":"propose-change", "operations":["submit"], "targets":[target.clone()]}, + {"action":"previous-change", "operations":["get","list"], "targets":[target.clone()]}, + {"action":"review-draft", "operations":["get","edit"], "targets":[target]} + ] + } + })) + .expect("profile parses"); + + assert_eq!( + plan_target_grants(&profile, "entry") + .map(|(surface, action, ..)| (surface, action)) + .collect::>(), + [ + ("actions", "update-entry"), + ("actions", "propose-change"), + ("proposals", "propose-change"), + ] + ); + } +} diff --git a/crates/registry-breg/src/proposal_workflow.rs b/crates/registry-breg/src/proposal_workflow.rs index 04a02bc258..8a551fc63c 100644 --- a/crates/registry-breg/src/proposal_workflow.rs +++ b/crates/registry-breg/src/proposal_workflow.rs @@ -292,6 +292,23 @@ impl ProposalWorkflow { Ok(transition) } + /// Record a message on the thread, or one side reading it, without + /// changing the submission. The thread is open while the Proposal is. + pub fn record_message( + mut self, + _context: TrustedTransitionContext, + ) -> Result { + self.refuse_rejected()?; + if !matches!(self.state, ProposalState::Draft | ProposalState::Submitted) { + return Err(WorkflowError::InvalidTransition); + } + self.workflow_revision = self.workflow_revision.next()?; + Ok(WorkflowTransition { + workflow: self, + effect: TransitionEffect::Messaged, + }) + } + /// Records the review authority's rejection of the current submission. /// A rejection is terminal: the review policy's changes-requested outcome, /// not this state, is how a reviewer allows another attempt. @@ -1740,6 +1757,7 @@ pub enum TransitionEffect { Asked, AskChanged, Answered, + Messaged, RetryScheduled, Submitted { version: SubmissionVersion, @@ -2374,6 +2392,7 @@ impl fmt::Debug for TransitionEffect { Self::Asked => formatter.write_str("Asked"), Self::AskChanged => formatter.write_str("AskChanged"), Self::Answered => formatter.write_str("Answered"), + Self::Messaged => formatter.write_str("Messaged"), Self::RetryScheduled => formatter.write_str("RetryScheduled"), Self::Submitted { version, .. } => formatter .debug_struct("Submitted") 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/src/review_store.rs b/crates/registry-breg/src/review_store.rs index 8eb1b5c6a2..fa0fe1d7be 100644 --- a/crates/registry-breg/src/review_store.rs +++ b/crates/registry-breg/src/review_store.rs @@ -1669,6 +1669,11 @@ pub(crate) const REVIEW_TABLES: &[(&str, &[&str])] = &[ "registry_proposal_review_ask_answers", &["INSERT", "SELECT", "UPDATE"], ), + ("registry_proposal_form_entries", &["INSERT", "SELECT"]), + ( + "registry_proposal_review_ask_form_entries", + &["INSERT", "SELECT"], + ), ("registry_proposal_review_ask_files", &["INSERT", "SELECT"]), ( "registry_proposal_review_ask_feed_events", diff --git a/crates/registry-breg/src/review_store/asks.rs b/crates/registry-breg/src/review_store/asks.rs index 321453e26c..e6be49718e 100644 --- a/crates/registry-breg/src/review_store/asks.rs +++ b/crates/registry-breg/src/review_store/asks.rs @@ -66,6 +66,43 @@ pub(super) async fn install(client: &impl GenericClient) -> Result<(), MutationE CREATE INDEX IF NOT EXISTS registry_proposal_review_ask_answer_jobs ON registry_internal.registry_proposal_review_ask_answers(next_attempt_at,answered_at) WHERE delivery_state='pending'; + CREATE TABLE IF NOT EXISTS registry_internal.registry_proposal_form_entries ( + action_id text NOT NULL, + proposal_id uuid NOT NULL, + submission_version bigint NOT NULL, + form_id text NOT NULL, + entry_id uuid NOT NULL, + input jsonb CHECK (jsonb_typeof(input)='object'), + contract_digest text NOT NULL, + added_by text, + added_at timestamptz NOT NULL DEFAULT transaction_timestamp(), + detail_erased_at timestamptz, + PRIMARY KEY (action_id,proposal_id,submission_version,entry_id), + FOREIGN KEY (action_id,proposal_id,submission_version) + REFERENCES registry_internal.registry_proposal_review_submissions, + CHECK ((detail_erased_at IS NULL) = (input IS NOT NULL)) + ); + CREATE INDEX IF NOT EXISTS registry_proposal_form_entries_form + ON registry_internal.registry_proposal_form_entries + (action_id,proposal_id,submission_version,form_id); + -- Keep the ask-files automatic constraint names stable on fresh installs. + CREATE TABLE IF NOT EXISTS registry_internal.registry_proposal_review_ask_form_entries ( + authority text NOT NULL, + review_request_id uuid NOT NULL, + ask_id uuid NOT NULL, + action_id text NOT NULL, + proposal_id uuid NOT NULL, + submission_version bigint NOT NULL, + entry_id uuid NOT NULL, + PRIMARY KEY (action_id,proposal_id,submission_version,entry_id), + CONSTRAINT breg_ask_form_answer_fkey + FOREIGN KEY (authority,review_request_id,ask_id,action_id,proposal_id,submission_version) + REFERENCES registry_internal.registry_proposal_review_ask_answers + (authority,review_request_id,ask_id,action_id,proposal_id,submission_version), + CONSTRAINT breg_ask_form_entry_fkey + FOREIGN KEY (action_id,proposal_id,submission_version,entry_id) + REFERENCES registry_internal.registry_proposal_form_entries + ); CREATE TABLE IF NOT EXISTS registry_internal.registry_proposal_review_ask_files ( authority text NOT NULL, review_request_id uuid NOT NULL, @@ -129,6 +166,8 @@ pub(crate) struct AnswerBody { pub(crate) text: Option, #[serde(default)] pub(crate) additions: Vec, + #[serde(default, rename = "formEntries", skip_serializing_if = "Vec::is_empty")] + pub(crate) form_entries: Vec, } #[derive(serde::Serialize)] @@ -168,7 +207,21 @@ impl AnswerBody { { return Err("additions"); } - if self.text.is_none() && self.additions.is_empty() { + let distinct = self + .form_entries + .iter() + .collect::>(); + if self.form_entries.len() > 32 + || distinct.len() != self.form_entries.len() + || self.form_entries.iter().any(Uuid::is_nil) + || (self.form_entries.is_empty() + && wants + .iter() + .any(|want| matches!(want, registry_review_client::ReviewAskWant::Form { .. }))) + { + return Err("formEntries"); + } + if self.text.is_none() && self.additions.is_empty() && self.form_entries.is_empty() { return Err("text"); } Ok(()) @@ -216,12 +269,14 @@ mod tests { let body = AnswerBody { text, additions: vec![], + form_entries: Vec::new(), }; assert_eq!(body.validate(&wants), Err("text")); } let body = AnswerBody { text: Some("A multiline\nanswer".to_owned()), additions: vec![], + form_entries: Vec::new(), }; assert_eq!(body.validate(&wants), Ok(())); assert!(serde_json::from_value::(json!({"other":"private"})).is_err()); @@ -232,20 +287,23 @@ mod tests { assert_eq!( AnswerBody { text: None, - additions: vec![] + additions: vec![], + form_entries: vec![], } .validate(&[]), Err("text") ); assert!(AnswerBody { text: Some("explanation".into()), - additions: vec![] + additions: vec![], + form_entries: vec![], } .validate(&[]) .is_ok()); assert!(AnswerBody { text: None, - additions: vec![Uuid::new_v4()] + additions: vec![Uuid::new_v4()], + form_entries: vec![], } .validate(&[]) .is_ok()); @@ -264,7 +322,8 @@ mod tests { assert_eq!( AnswerBody { text: None, - additions + additions, + form_entries: vec![], } .validate(&wants), Err("additions") @@ -273,7 +332,8 @@ mod tests { assert_eq!( AnswerBody { text: None, - additions: vec![id] + additions: vec![id], + form_entries: vec![], } .validate(&wants), Ok(()) @@ -281,7 +341,8 @@ mod tests { assert_eq!( AnswerBody { text: None, - additions: vec![] + additions: vec![], + form_entries: vec![], } .validate(&[]), Err("text") diff --git a/crates/registry-breg/src/runtime_config.rs b/crates/registry-breg/src/runtime_config.rs index f2bda3adb3..ae26b695ac 100644 --- a/crates/registry-breg/src/runtime_config.rs +++ b/crates/registry-breg/src/runtime_config.rs @@ -5502,6 +5502,80 @@ mod tests { use super::RuntimeConfigError; use crate::attachment_verification_worker::ATTEMPT_BUDGET; + fn open_membership_registry() -> crate::CompiledRegistry { + use serde_json::{json, Value}; + let mut source: Value = serde_json::from_str(include_str!( + "../../../products/breg/fixtures/organization-membership-access/registry.yaml" + )) + .unwrap(); + source["recordTypes"]["membership"] + .as_object_mut() + .unwrap() + .remove("accessRequirements"); + source["accessProfiles"] + .as_object_mut() + .unwrap() + .remove("steward"); + source["accessProfiles"]["member"]["principalClaim"] = json!("sub"); + source["accessProfiles"]["member"]["requiredScopes"] = json!("unrestricted"); + let project = crate::parse_project_json(&serde_json::to_vec(&source).unwrap()).unwrap(); + crate::compile_project(&project, &[], crate::CompileProfile::Authoring).unwrap() + } + + fn membership_runtime(two_issuers: bool) -> super::RuntimeConfig { + use registry_platform_config::{DeclaredPosture, Posture, PostureSource}; + let example = include_str!("../../../products/breg/examples/minimal/runtime.example.yaml"); + let mut runtime = example.replace("principal: registry_principal", "principal: sub"); + let first = runtime.find(" primary:\n").unwrap(); + let end = runtime.find(" authorityClaims:\n").unwrap(); + let definition = format!("{} actorKind: human\n", &runtime[first..end]); + let mut issuers = definition.clone(); + if two_issuers { + issuers.push_str( + &definition + .replace("primary:", "second:") + .replace( + "https://issuer.example.com", + "https://other-issuer.example.com", + ) + .replace("directory-client", "second-directory-client"), + ); + } + runtime.replace_range(first..end, &issuers); + super::parse_runtime_config( + &runtime, + DeclaredPosture { + posture: Posture::Development, + source: PostureSource::Flag, + }, + ) + .unwrap() + } + + #[test] + fn a_membership_bounded_profile_reachable_from_two_issuers_refuses_at_startup() { + let runtime = membership_runtime(true); + let diagnostics = runtime.authentication().access_profile_diagnostics( + &open_membership_registry(), + None, + None, + ); + assert_eq!(diagnostics.len(), 1); + assert_eq!(diagnostics[0].code, "breg.runtime.principal-across-issuers"); + } + + #[test] + fn an_open_profile_bounded_by_membership_is_not_listed_as_scopeless_without_subject_rule() { + let runtime = membership_runtime(false); + let registry = open_membership_registry(); + let settings = runtime + .authentication() + .combination_posture_settings(®istry); + assert!(!settings + .iter() + .any(|found| found.setting.code == "breg.posture.scopeless-without-subject-rule")); + } + #[test] fn a_loopback_name_reaches_the_pool_as_numeric_loopback_addresses() { // A fixed answer, so the test needs no particular `localhost` mapping diff --git a/crates/registry-breg/src/startup.rs b/crates/registry-breg/src/startup.rs index ecaccfdd3c..b1dcc77000 100644 --- a/crates/registry-breg/src/startup.rs +++ b/crates/registry-breg/src/startup.rs @@ -2650,7 +2650,7 @@ pub async fn serve_until_shutdown( BackgroundTask::AttachmentVerificationWorker, worker.run(worker_shutdown_rx.clone()), worker_shutdown_rx.clone(), - task_stopped_tx.clone(), + Some(task_stopped_tx.clone()), ) }); let mut record_timer_worker = record_timer_worker.map(|worker| { @@ -2658,7 +2658,7 @@ pub async fn serve_until_shutdown( BackgroundTask::RecordTimerWorker, worker.run(worker_shutdown_rx.clone()), worker_shutdown_rx.clone(), - task_stopped_tx.clone(), + Some(task_stopped_tx.clone()), ) }); let mut review_worker = review_worker.map(|worker| { @@ -2666,7 +2666,7 @@ pub async fn serve_until_shutdown( BackgroundTask::ReviewWorker, worker.run(worker_shutdown_rx.clone()), worker_shutdown_rx.clone(), - task_stopped_tx.clone(), + Some(task_stopped_tx.clone()), ) }); let mut evidence_worker = evidence_retention.map(|worker| { @@ -2674,7 +2674,7 @@ pub async fn serve_until_shutdown( BackgroundTask::EvidenceRetention, worker.run(worker_shutdown_rx.clone()), worker_shutdown_rx.clone(), - task_stopped_tx.clone(), + Some(task_stopped_tx.clone()), ) }); let mut external_projection_worker = @@ -2683,7 +2683,7 @@ pub async fn serve_until_shutdown( BackgroundTask::ExternalProjectionRetention, backend.run_retention(last_success, worker_shutdown_rx.clone()), worker_shutdown_rx.clone(), - task_stopped_tx.clone(), + Some(task_stopped_tx.clone()), ) }); let mut external_refresh_worker = external_refresh.map(|(service, last_success)| { @@ -2695,7 +2695,7 @@ pub async fn serve_until_shutdown( worker_shutdown_rx.clone(), ), worker_shutdown_rx.clone(), - task_stopped_tx.clone(), + Some(task_stopped_tx.clone()), ) }); let mut access_log_worker = access_log_retention.map(|(pool, last_success)| { @@ -2707,7 +2707,7 @@ pub async fn serve_until_shutdown( worker_shutdown_rx.clone(), ), worker_shutdown_rx.clone(), - task_stopped_tx.clone(), + Some(task_stopped_tx.clone()), ) }); let mut worker = hook_worker.map(|worker| { @@ -2715,7 +2715,7 @@ pub async fn serve_until_shutdown( BackgroundTask::HookWorker, worker.run(worker_shutdown_rx.clone()), worker_shutdown_rx.clone(), - task_stopped_tx.clone(), + Some(task_stopped_tx.clone()), ) }); let (shutdown_tx, shutdown_rx) = oneshot::channel::<()>(); @@ -2731,7 +2731,7 @@ pub async fn serve_until_shutdown( .await }, worker_shutdown_rx.clone(), - task_stopped_tx.clone(), + Some(task_stopped_tx.clone()), ) }); // Only the supervisors hold senders, so the stop branch below is disabled @@ -2843,10 +2843,9 @@ enum ServeExit { TaskStopped, } -/// One background task `serve` owns. The task runs under a supervisor that -/// reports how it ended; serve cancels the task itself and joins the -/// supervisor, so a joined supervisor means the task has stopped too. -struct SupervisedTask { +/// One owned background task. The supervisor reports how it ended. Joining +/// the supervisor also proves the task stopped. +pub(crate) struct SupervisedTask { task: BackgroundTask, supervisor: tokio::task::JoinHandle<()>, cancel: tokio::task::AbortHandle, @@ -2855,16 +2854,15 @@ struct SupervisedTask { impl SupervisedTask { /// Run `future` under a supervisor. A panic is always reported. A return - /// before `shutdown` turns true is reported and sent on `stopped`, which - /// ends serve; a return after it is the requested stop. Only the shutdown - /// grace timeout cancels a task, and serve reports that timeout itself. + /// before `shutdown` turns true is reported and sent to the optional + /// owner notification channel. A return after it is the requested stop. /// A task's own output, such as the metrics listener's accept error, /// counts as a return. - fn spawn( + pub(crate) fn spawn( task: BackgroundTask, future: F, shutdown: watch::Receiver, - stopped: mpsc::UnboundedSender, + stopped: Option>, ) -> Self where F: Future + Send + 'static, @@ -2883,10 +2881,9 @@ impl SupervisedTask { return; } OperationalEvent::BackgroundTaskStopped(task, stop).emit(); - if !requested { - // serve holds the receiver until it has joined every - // supervisor, so a refused send means serve is already - // stopping and has nothing left to end. + if let Some(stopped) = stopped.filter(|_| !requested) { + // Serve holds the receiver until its supervisors join. + // A refused send means serve is already stopping. let _ = stopped.send(task); } }); @@ -2900,7 +2897,7 @@ impl SupervisedTask { /// Wait for the supervisor once. A supervisor that panicked is reported /// as its task panicking. - async fn join(&mut self) { + pub(crate) async fn join(&mut self) { if self.joined { return; } @@ -2911,12 +2908,18 @@ impl SupervisedTask { } } - async fn abort_and_join(&mut self) { + pub(crate) async fn abort_and_join(&mut self) { self.cancel.abort(); self.join().await; } } +impl Drop for SupervisedTask { + fn drop(&mut self) { + self.cancel.abort(); + } +} + /// Install the stop-signal handlers with `install`. A failure refuses startup /// with [`StartupError::Shutdown`], so the runtime never serves with no way to /// be stopped by a signal. diff --git a/crates/registry-breg/src/tests/action_handler_benchmark_tests.rs b/crates/registry-breg/src/tests/action_handler_benchmark_tests.rs index 79b85cbfb0..e7a377bb58 100644 --- a/crates/registry-breg/src/tests/action_handler_benchmark_tests.rs +++ b/crates/registry-breg/src/tests/action_handler_benchmark_tests.rs @@ -51,7 +51,7 @@ fn acceptance_action() -> CompiledAction { "plan":{"type":"scripted","actionPlan":"register-plan","inputs":["identifier","given-name","family-name"], "refusals":[{"code":"blank-name","label":"At least one name part is required."}], "writes":[{"id":"person","target":{"recordType":"person"},"operation":"create","fields":["identifier","display-name"]}]}}}, - "accessProfiles":{"writer": {"principalClaim":"principal","requiredScopes":"unrestricted","permissions":{"actions":[ + "accessProfiles":{"writer": {"principalClaim":"principal","requiredScopes":["records:write"],"permissions":{"actions":[ {"action":"register-person","operations":["invoke"],"targets":[{"recordType":"person","rowBoundaries":"unrestricted"}],"results":["person"]}]}}} }); let project = parse_project_json(&serde_json::to_vec(&source).unwrap()).unwrap(); @@ -105,7 +105,7 @@ fn characterization_action(script: &str) -> CompiledAction { "refusals":[{"code":"blank-label","label":"A label is required."}], "writes":[{"id":"record","target":{"recordType":"record"},"operation":"create","fields":["label","count","amount"]}] }}}, - "accessProfiles":{"writer": {"default":true,"principalClaim":"principal","requiredScopes":"unrestricted","permissions":{ + "accessProfiles":{"writer": {"default":true,"principalClaim":"principal","requiredScopes":["records:write"],"permissions":{ "actions":[ {"action":"register-record","operations":["invoke"],"targets":[{"recordType":"record","rowBoundaries":"unrestricted"}],"results":["record"]} ] diff --git a/crates/registry-breg/src/tests/action_outcome_wasm_parity_tests.rs b/crates/registry-breg/src/tests/action_outcome_wasm_parity_tests.rs index e9fa4ba207..105b000a6f 100644 --- a/crates/registry-breg/src/tests/action_outcome_wasm_parity_tests.rs +++ b/crates/registry-breg/src/tests/action_outcome_wasm_parity_tests.rs @@ -57,7 +57,7 @@ fn person_action(script: &str) -> CompiledAction { {"id":"friend","target":{"recordType":"person"},"operation":"create","fields":["name","friend"]}, {"id":"existing","target":{"fromInput":"person"},"operation":"patch","fields":["name","friend"]} ]}}}, - "accessProfiles":{"registrar": {"default":true,"principalClaim":"principal","requiredScopes":"unrestricted","permissions":{"actions":[{"action":"register-person","operations":["invoke"],"targets":[{"recordType":"person","rowBoundaries":"unrestricted"}],"results":["person","friend","existing"]}]}}} + "accessProfiles":{"registrar": {"default":true,"principalClaim":"principal","requiredScopes":["records:write"],"permissions":{"actions":[{"action":"register-person","operations":["invoke"],"targets":[{"recordType":"person","rowBoundaries":"unrestricted"}],"results":["person","friend","existing"]}]}}} }); let project = parse_project_json(&serde_json::to_vec(&source).unwrap()).unwrap(); compile_project_with_assets( @@ -101,7 +101,7 @@ fn record_action(script: &str) -> CompiledAction { ],"plan":{"type":"scripted","actionPlan":"record-plan","inputs":["label","count","amount"],"refusals":[{"code":"blank-label","label":"A label is required."}], "writes":[{"id":"record","target":{"recordType":"record"},"operation":"create","fields":["label","count","amount"]}] }}}, - "accessProfiles":{"writer": {"default":true,"principalClaim":"principal","requiredScopes":"unrestricted","permissions":{ + "accessProfiles":{"writer": {"default":true,"principalClaim":"principal","requiredScopes":["records:write"],"permissions":{ "actions":[ {"action":"register-record","operations":["invoke"],"targets":[{"recordType":"record","rowBoundaries":"unrestricted"}],"results":["record"]} ] diff --git a/crates/registry-breg/src/tests/artifacts_response_schema_tests.rs b/crates/registry-breg/src/tests/artifacts_response_schema_tests.rs index b87c64c93b..55dfcbcdb0 100644 --- a/crates/registry-breg/src/tests/artifacts_response_schema_tests.rs +++ b/crates/registry-breg/src/tests/artifacts_response_schema_tests.rs @@ -1140,7 +1140,7 @@ fn compiled_bound_writer_registry() -> CompiledRegistry { "actions": [ {"action": "set-person-phone", "operations": ["invoke"], "targets": targets}, {"action": "propose-person-phone", "operations": ["start"], "targets": targets}], - "proposals": [{"action": "propose-person-phone", "ownership": "caller", + "proposals": [{"action": "propose-person-phone", "party": "owner", "operations": ["get", "list", "edit", "submit", "cancel", "apply"], "readableInputs": ["person", "phone"], "targets": targets}]}}) }; @@ -1318,7 +1318,7 @@ fn compiled_record_condition_writer_registry( "actions": [ {"action": "write-person", "operations": ["invoke"], "targets": targets}, {"action": "propose-person", "operations": ["start"], "targets": targets}], - "proposals": [{"action": "propose-person", "ownership": "caller", + "proposals": [{"action": "propose-person", "party": "owner", "operations": ["get", "list", "edit", "submit", "cancel", "apply"], "readableInputs": if effect == "patch" { json!(["person", "phone", "protected"]) } else { json!(["phone", "protected"]) }, "targets": targets}]}}) diff --git a/crates/registry-breg/src/tests/wasm_runtime_tests.rs b/crates/registry-breg/src/tests/wasm_runtime_tests.rs index 4187d57dd6..5aa29391c3 100644 --- a/crates/registry-breg/src/tests/wasm_runtime_tests.rs +++ b/crates/registry-breg/src/tests/wasm_runtime_tests.rs @@ -153,7 +153,7 @@ fn wasm_person_action(module_bytes: &[u8]) -> CompiledAction { ],"plan":{"type":"scripted","actionPlan":"person-plan","inputs":["given-name","family-name","person"],"refusals":[{"code":"blank-name","label":"A name is required."}],"writes":[ {"id":"person","target":{"recordType":"person"},"operation":"create","fields":["name","friend"]} ]}}}, - "accessProfiles":{"registrar": {"default":true,"principalClaim":"principal","requiredScopes":"unrestricted","permissions":{"actions":[{"action":"register-person","operations":["invoke"],"targets":[{"recordType":"person","rowBoundaries":"unrestricted"}],"results":["person"]}]}}} + "accessProfiles":{"registrar": {"default":true,"principalClaim":"principal","requiredScopes":["records:write"],"permissions":{"actions":[{"action":"register-person","operations":["invoke"],"targets":[{"recordType":"person","rowBoundaries":"unrestricted"}],"results":["person"]}]}}} }); let project = parse_project_json(&serde_json::to_vec(&source).unwrap()).unwrap(); compile_project_with_assets( diff --git a/crates/registry-breg/src/tooling.rs b/crates/registry-breg/src/tooling.rs index 5ef0f2222a..80b0984c83 100644 --- a/crates/registry-breg/src/tooling.rs +++ b/crates/registry-breg/src/tooling.rs @@ -587,6 +587,7 @@ fn action_details( let Some(before) = before else { return details; }; + details.extend(target_boundary_details(&before, &after)); let codes = |input: &crate::model::CompiledActionInput| match &input.field_type { crate::contract::FieldTypeSource::VocabularyCode { values, .. } => json!(values), _ => Value::Null, @@ -620,6 +621,84 @@ fn action_details( details } +fn target_boundary_details( + before: &crate::model::CompiledAction, + after: &crate::model::CompiledAction, +) -> Vec { + use crate::model::CompiledActionExecution; + use serde_json::json; + + let mut details = Vec::new(); + let mut compare = |profile: &str, entity: &str, surface: &str, before, after| { + details.extend( + object_details(&before, &after, |field, left, right| { + (access_direction(field, left, right), None) + }) + .into_iter() + .map(|mut detail| { + detail.reason = Some(format!("{surface} target {entity} in profile {profile}")); + detail + }), + ); + }; + for grant in &before.permissions { + let Some(next) = after + .permissions + .iter() + .find(|next| next.profile_id == grant.profile_id) + else { + continue; + }; + for target in grant.entity_target_locks() { + let Some(other) = next + .entity_target_locks() + .find(|other| other.entity_id == target.entity_id) + else { + continue; + }; + compare( + &grant.profile_id, + &target.entity_id, + "Action", + json!({"rowBoundaries": target.row_boundaries, "membershipBoundaries": target.membership_boundaries}), + json!({"rowBoundaries": other.row_boundaries, "membershipBoundaries": other.membership_boundaries}), + ); + } + } + if let ( + CompiledActionExecution::Proposal { proposal: before }, + CompiledActionExecution::Proposal { proposal: after }, + ) = (&before.execution, &after.execution) + { + for grant in &before.permissions { + let Some(next) = after + .permissions + .iter() + .find(|next| next.profile_id == grant.profile_id) + else { + continue; + }; + for target in &grant.targets { + let Some(other) = next + .targets + .iter() + .find(|other| other.entity_id == target.entity_id) + else { + continue; + }; + compare( + &grant.profile_id, + &target.entity_id, + "Proposal", + json!({"rowBoundaries": target.row_boundaries, "membershipBoundaries": target.membership_boundaries}), + json!({"rowBoundaries": other.row_boundaries, "membershipBoundaries": other.membership_boundaries}), + ); + } + } + } + details +} + fn access_direction( field: &str, before: &serde_json::Value, diff --git a/crates/registry-breg/tests/access_explanation.rs b/crates/registry-breg/tests/access_explanation.rs index 0ceb6bb9f8..e55b199017 100644 --- a/crates/registry-breg/tests/access_explanation.rs +++ b/crates/registry-breg/tests/access_explanation.rs @@ -150,11 +150,9 @@ fn membership_source() -> Value { let grant = &mut source["accessProfiles"]["clerk"]["permissions"]["records"][0]; grant["operations"] = json!(["get", "list"]); grant["writableFields"] = json!([]); - grant["rowBoundaries"] = json!("unrestricted"); - grant["membershipBoundaries"] = json!([{ - "field":"organization", "membershipRecordType":"membership", - "membershipKeyField":"organization", "principalField":"principal", "activeField":"active" - }]); + grant["rowBoundaries"] = json!([{"field":"organization","membership":"membership"}]); + source["recordTypes"]["membership"]["membership"] = + json!({"key":"organization","principal":"principal","active":"active"}); source } @@ -501,7 +499,7 @@ fn function_action_target_authority_uses_the_compiled_write_ceiling() { #[test] fn membership_row_reach_is_explicit_and_uses_the_selected_principal() { for (boundaries, rows, direct_claims) in [ - (json!("unrestricted"), "membership_bound", 0), + (json!([]), "membership_bound", 0), ( json!([{"field":"district", "claim":"districts", "operator":"in"}]), "claim_and_membership_bound", @@ -509,8 +507,11 @@ fn membership_row_reach_is_explicit_and_uses_the_selected_principal() { ), ] { let mut source = membership_source(); - source["accessProfiles"]["clerk"]["permissions"]["records"][0]["rowBoundaries"] = - boundaries.clone(); + let authored = + &mut source["accessProfiles"]["clerk"]["permissions"]["records"][0]["rowBoundaries"]; + if let Some(claims) = boundaries.as_array() { + authored.as_array_mut().unwrap().extend_from_slice(claims); + } let registry = compile(&source); let explanation = registry_breg::access::explain_access(®istry); let inspected = serde_json::to_value(&explanation).unwrap(); @@ -529,7 +530,10 @@ fn membership_row_reach_is_explicit_and_uses_the_selected_principal() { .unwrap(); assert_eq!(reach.rows, rows); assert_eq!(reach.membership_boundaries.len(), 1); - assert_eq!(reach.membership_boundaries[0].principal_field, "principal"); + assert_eq!( + serde_json::to_value(&reach.membership_boundaries[0]).unwrap()["principalField"], + "principal" + ); assert!(!registry.findings().iter().any(|finding| matches!( finding.code.as_str(), "breg.access.profile-unrestricted-rows" | "breg.access.profile-unrestricted-collection" @@ -546,24 +550,28 @@ fn membership_changes_report_authority_narrowing_and_widening() { use registry_breg::tooling::{classify_registry_diff, AccessChangeDirection}; let mut source = membership_source(); - source["recordTypes"]["membership"]["fields"] + let mut additional = source["recordTypes"]["membership"].clone(); + additional["route"] = json!("additional-memberships"); + additional["fields"] .as_array_mut() .unwrap() .push(json!({"id":"approved", "type":"boolean", "classification":"internal"})); - let mut additional = source["accessProfiles"]["clerk"]["permissions"]["records"][0] - ["membershipBoundaries"][0] - .clone(); - additional["activeField"] = json!("approved"); + additional["membership"]["active"] = json!("approved"); + source["recordTypes"]["additional-membership"] = additional; let mut boundaries = source["accessProfiles"]["clerk"]["permissions"]["records"][0] - ["membershipBoundaries"] + ["rowBoundaries"] .as_array() .unwrap() .clone(); - boundaries.push(additional); + boundaries.push(json!({"field":"organization","membership":"additional-membership"})); let registries = (0..=2) .map(|count| { - source["accessProfiles"]["clerk"]["permissions"]["records"][0] - ["membershipBoundaries"] = json!(&boundaries[..count]); + source["accessProfiles"]["clerk"]["permissions"]["records"][0]["rowBoundaries"] = + if count == 0 { + json!("unrestricted") + } else { + json!(&boundaries[..count]) + }; compile(&source) }) .collect::>(); @@ -615,3 +623,96 @@ fn synthetic_own_record_preview_reuses_principal_and_refuses_identity_override() ) .is_err()); } + +#[allow(dead_code)] +#[path = "support/proposal_hooks_model.rs"] +mod proposal_hooks_model; + +fn compiled_with_target_membership( + mut registry: Value, + targets: &str, +) -> registry_breg::CompiledRegistry { + let member_registry = compile(&membership_source()); + let boundary = &member_registry.entities()["entry"].membership_boundaries["clerk"][0]; + registry["entities"]["membership"] = json!(member_registry.entities()["membership"]); + for target in registry + .pointer_mut(targets) + .unwrap() + .as_array_mut() + .unwrap() + { + target["membershipBoundaries"] = json!([boundary]); + } + serde_json::from_value(registry).unwrap() +} + +const ACTION_TARGETS: &str = "/actionInventory/actions/0/permissions/0/targets"; +const PROPOSAL_TARGETS: &str = + "/actionInventory/actions/0/execution/proposal/permissions/0/targets"; + +#[test] +fn explain_access_lists_membership_entries_on_action_targets() { + let baseline = compile(&repeated_action_target_source()); + let candidate = compiled_with_target_membership(json!(baseline), ACTION_TARGETS); + let explanation = registry_breg::access::explain_access(&candidate); + let target = explanation + .row_reach + .iter() + .find(|reach| reach.surface == "action_target") + .unwrap(); + assert_eq!(target.rows, "claim_and_membership_bound"); + assert_eq!(target.membership_boundaries.len(), 1); + assert_eq!( + json!(target.membership_boundaries[0]), + json!({ + "field":"organization", "membershipRecordType":"membership", + "membershipKeyField":"organization","principalField":"principal","activeField":"active" + }) + ); +} + +#[test] +fn explain_access_lists_membership_entries_on_proposal_targets() { + let baseline = compile(&proposal_hooks_model::source(json!([]))); + let candidate = compiled_with_target_membership(json!(baseline), PROPOSAL_TARGETS); + let explanation = registry_breg::access::explain_access(&candidate); + let target = explanation + .row_reach + .iter() + .find(|reach| reach.surface == "proposal_target") + .unwrap(); + assert_eq!(target.rows, "membership_bound"); + assert_eq!(target.membership_boundaries.len(), 1); + assert_eq!( + json!(target.membership_boundaries[0]), + json!({ + "field":"organization", "membershipRecordType":"membership", + "membershipKeyField":"organization","principalField":"principal","activeField":"active" + }) + ); +} + +#[cfg(all(feature = "runtime", feature = "tooling"))] +#[test] +fn adding_a_membership_entry_to_an_action_target_reads_as_narrowing() { + use registry_breg::tooling::{classify_registry_diff, AccessChangeDirection}; + let baseline = compile(&repeated_action_target_source()); + let candidate = compiled_with_target_membership(json!(baseline), ACTION_TARGETS); + for (before, after, expected) in [ + (&baseline, &candidate, AccessChangeDirection::Narrowing), + (&candidate, &baseline, AccessChangeDirection::Widening), + ] { + let diff = classify_registry_diff(before, after, "baseline"); + let details = diff + .changes + .iter() + .flat_map(|change| &change.access_details); + assert_eq!( + details + .filter(|detail| detail.field == "membershipBoundaries") + .map(|detail| detail.direction) + .collect::>(), + [expected], + ); + } +} diff --git a/crates/registry-breg/tests/access_log.rs b/crates/registry-breg/tests/access_log.rs index bf4e9c4d4e..9a19dc5ccf 100644 --- a/crates/registry-breg/tests/access_log.rs +++ b/crates/registry-breg/tests/access_log.rs @@ -73,7 +73,7 @@ fn source() -> Value { }, "writer": { "principalClaim": "registry_principal", - "requiredScopes": "unrestricted", + "requiredScopes": ["records:write"], "permissions": {"records": [{ "recordType": "person", "operations": ["create"], diff --git a/crates/registry-breg/tests/access_sentinels.rs b/crates/registry-breg/tests/access_sentinels.rs index db8a755649..6b8278e09b 100644 --- a/crates/registry-breg/tests/access_sentinels.rs +++ b/crates/registry-breg/tests/access_sentinels.rs @@ -41,7 +41,7 @@ fn every_row_reach() -> Value { "rowBoundaries":[boundary()]}], "actions":[{"action":"register","operations":["invoke"], "targets":[{"recordType":"entry","rowBoundaries":[boundary()]}]}], - "proposals":[{"action":"register","operations":["get"],"ownership":"caller", + "proposals":[{"action":"register","operations":["get"],"party":"owner", "targets":[{"recordType":"entry","rowBoundaries":[boundary()]}]}] }); value diff --git a/crates/registry-breg/tests/action_evidence_compiler.rs b/crates/registry-breg/tests/action_evidence_compiler.rs index 5de966b153..a55ab1900c 100644 --- a/crates/registry-breg/tests/action_evidence_compiler.rs +++ b/crates/registry-breg/tests/action_evidence_compiler.rs @@ -28,7 +28,7 @@ fn project() -> Value { {"id":"friend","target":{"recordType":"person"},"operation":"create","fields":["name","friend"]}, {"id":"existing","target":{"fromInput":"person"},"operation":"patch","fields":["name","friend"]} ]}}}, - "accessProfiles":{"registrar": {"default":true,"principalClaim":"principal","requiredScopes":"unrestricted","permissions":{"actions":[{"action":"register-person","operations":["invoke"],"targets":[{"recordType":"person","rowBoundaries":"unrestricted"}],"results":["person","friend","existing"]}]}}} + "accessProfiles":{"registrar": {"default":true,"principalClaim":"principal","requiredScopes":["records:write"],"permissions":{"actions":[{"action":"register-person","operations":["invoke"],"targets":[{"recordType":"person","rowBoundaries":"unrestricted"}],"results":["person","friend","existing"]}]}}} }) } @@ -159,7 +159,7 @@ fn proposal_apply_declares_commit_evidence_failure_but_submit_does_not() { .unwrap() .remove("results"); permissions["proposals"] = json!([{"action":"register-person","operations":["get","submit","apply"], - "ownership":"caller","readableInputs":["given-name","family-name","person"], + "party":"owner","readableInputs":["given-name","family-name","person"], "targets":[{"recordType":"person","rowBoundaries":"unrestricted"}]}]); let mut contract = contracts(); contract["definitions"][0]["subjects"][0]["selector"]["fields"] = diff --git a/crates/registry-breg/tests/action_handler_declaration.rs b/crates/registry-breg/tests/action_handler_declaration.rs index df2fbe4dd0..5bfdc51c42 100644 --- a/crates/registry-breg/tests/action_handler_declaration.rs +++ b/crates/registry-breg/tests/action_handler_declaration.rs @@ -18,7 +18,7 @@ fn project() -> Value { {"id":"unbound","type":"string","maximumLength":64,"classification":"restricted"}], "plan":{"type":"scripted","actionPlan":"person-plan","inputs":["code"], "writes":[{"id":"person","target":{"recordType":"person"},"operation":"create","fields":["code"]}]}}}, - "accessProfiles":{"registrar": {"default":true,"principalClaim":"registry_principal","requiredScopes":"unrestricted", + "accessProfiles":{"registrar": {"default":true,"principalClaim":"registry_principal","requiredScopes":["records:write"], "permissions":{"actions":[{"action":"register-person","operations":["invoke"],"targets":[{"recordType":"person","rowBoundaries":"unrestricted"}],"results":["person"]}]}}} }) } diff --git a/crates/registry-breg/tests/attachment_promotion_compiler.rs b/crates/registry-breg/tests/attachment_promotion_compiler.rs index c8472d5dc7..87c784d75d 100644 --- a/crates/registry-breg/tests/attachment_promotion_compiler.rs +++ b/crates/registry-breg/tests/attachment_promotion_compiler.rs @@ -45,7 +45,7 @@ fn source() -> Value { "actions":[{"action":"amend","operations":["start"],"targets":[ {"recordType":"application","rowBoundaries":"unrestricted"}]}], "proposals":[{"action":"amend","operations":["get","list","edit","submit","apply"], - "ownership":"caller","readableInputs":["target","name"],"readableAttachments":["document"], + "party":"owner","readableInputs":["target","name"],"readableAttachments":["document"], "writableAttachments":["document"],"targets":[ {"recordType":"application","rowBoundaries":"unrestricted"}]}]}}}}) } diff --git a/crates/registry-breg/tests/compiled_ddl_pins.rs b/crates/registry-breg/tests/compiled_ddl_pins.rs index 188d7d13b2..a81e7b9fda 100644 --- a/crates/registry-breg/tests/compiled_ddl_pins.rs +++ b/crates/registry-breg/tests/compiled_ddl_pins.rs @@ -104,6 +104,16 @@ //! The generated project SDK passes `limit` to the native list calls, which //! changes the packaged SDK and artifact revisions. SQL and Action pins stay //! fixed. +//! The shared OpenAPI Problem schema adds `proposal.form-undeclared`, +//! `proposal.form-limit-reached`, and `proposal.message-limit-reached`. +//! Every fixture includes that schema in `generated/openapi.json`, so the +//! 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}; @@ -125,8 +135,8 @@ const FIXTURES: &[Fixture] = &[ "../../../products/breg/fixtures/organization-membership-access/registry.yaml" ), module: None, - ddl_sha256: "6d6431e3e4fb3eb254ef8f3b2e895aed2c09ed4ee7ca506627e1d063359f4578", - revision: "sha256:6ce101a4824207e4feaaca9c790de8580c07d280ca913937e6a643eb1ee48860", + ddl_sha256: include_str!("golden/membership-ddl.sha256"), + revision: include_str!("golden/membership-revision.txt"), }, Fixture { name: "asset-registration-actions", @@ -137,7 +147,7 @@ const FIXTURES: &[Fixture] = &[ "../../../products/breg/fixtures/asset-registration-actions/modules/asset-registration-actions-core/module.yaml" )), ddl_sha256: "43acdae956eb2f932fb22a2cccc5cee5ed19cf806f2f28bbc677eff219d00b99", - revision: "sha256:2ab48b17d42c7e06b9ca0bb33de9d3e17e7864656dc98fee4c15f386e55ddf55", + revision: "sha256:9f676cf2e5a97a63587659604a6a12c022b318856fa40a0ca34bdb6393387caf", }, Fixture { name: "facility-registry-actions", @@ -148,7 +158,7 @@ const FIXTURES: &[Fixture] = &[ "../../../products/breg/fixtures/facility-registry-actions/modules/facility-registry-actions-core/module.yaml" )), ddl_sha256: "6439a877ee6508b999a77242542695d8ccddc6d80518699d90eddc32b305780b", - revision: "sha256:9b46e4f5bf7d5d115411768b94b44db919c84648adc4cb6c5d8d9b976d3c6d6f", + revision: "sha256:7793a749c1ff75b9767cea3787adfc268bd38e9ba1ef906f0c700b2632ba9e2e", }, Fixture { name: "household-contact-actions", @@ -159,7 +169,7 @@ const FIXTURES: &[Fixture] = &[ "../../../products/breg/fixtures/household-contact-actions/modules/household-contact-actions-core/module.yaml" )), ddl_sha256: "f82f2f8376df97fb184c04d31c8e42c291f7a03dbd909828e1bf61612106de35", - revision: "sha256:a75cbc6e65d24415a55a5a949b01bfbbe68c3588ff2749b8ae7f68cd2934aa42", + revision: "sha256:bd6519bef876a12c56f66351d35f90eccff4c3b176a56fa7801ad8d1489ca06c", }, ]; @@ -174,6 +184,10 @@ fn compile(fixture: &Fixture) -> CompiledRegistry { fn ddl_sha256(registry: &CompiledRegistry) -> String { let bytes = serde_json::to_vec(registry.ddl()).expect("DDL inventory serializes"); + sha256(&bytes) +} + +fn sha256(bytes: &[u8]) -> String { Sha256::digest(bytes) .iter() .map(|byte| format!("{byte:02x}")) @@ -186,7 +200,9 @@ fn fixtures_without_consent_keep_their_exact_ddl_and_revision() { for fixture in FIXTURES { let registry = compile(fixture); let ddl = ddl_sha256(®istry); - if ddl != fixture.ddl_sha256 || registry.revision() != fixture.revision { + if ddl != fixture.ddl_sha256.trim_end() + || registry.revision() != fixture.revision.trim_end() + { drift.push(format!( "{}: ddl_sha256 {ddl}, revision {}", fixture.name, @@ -222,3 +238,131 @@ const ACTION_FINGERPRINTS: &[&str] = &[ "facility-registry-actions/transfer-facility: sha256:5f346eabb7d4a8f9bf959432ae47de3aaecaa07962d6fec954452848a31e84d4", "household-contact-actions/register-household-contact: sha256:cb90f8518169dafc15d6d66ca467e9f1093b5d04afe68c970d91b966e7f7c905", ]; + +#[test] +fn membership_fixture_compiles_to_the_recorded_ddl_and_access_inventory() { + let fixture = FIXTURES + .iter() + .find(|fixture| fixture.name == "organization-membership-access") + .expect("membership fixture is listed"); + let registry = compile(fixture); + let ddl = serde_json::to_string_pretty(registry.ddl()).expect("DDL serializes") + "\n"; + let access = serde_json::to_string_pretty(registry.access()) + .expect("access inventory serializes") + + "\n"; + if std::env::var("REGISTRY_BREG_WRITE_DDL_GOLDEN").as_deref() == Ok("1") { + let golden = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/golden"); + for (name, contents) in [ + ("membership-ddl.json", ddl), + ( + "membership-ddl.sha256", + format!("{}\n", ddl_sha256(®istry)), + ), + ( + "membership-revision.txt", + format!("{}\n", registry.revision()), + ), + ] { + std::fs::write(golden.join(name), contents).expect("membership golden writes"); + } + } else { + assert_eq!(ddl, include_str!("golden/membership-ddl.json")); + } + assert_eq!(access, include_str!("golden/membership-access.json")); +} + +#[test] +fn a_record_type_without_membership_compiles_to_the_same_bytes() { + let fixture = &FIXTURES[1]; + let registry = compile(fixture); + assert_eq!(registry.revision(), fixture.revision); + for entity in registry.entities().values() { + assert!(serde_json::to_value(entity) + .unwrap() + .get("membership") + .is_none()); + } +} + +#[test] +fn targets_without_membership_entries_generate_the_same_policies() { + for fixture in &FIXTURES[1..] { + let registry = compile(fixture); + assert_eq!(registry.revision(), fixture.revision); + assert_eq!(ddl_sha256(®istry), fixture.ddl_sha256); + let actions = serde_json::to_value(registry.actions()).unwrap(); + assert!(!actions.to_string().contains("membershipBoundaries")); + } +} + +const MEMBERSHIP_INDEX_ID: &str = "entity.membership.membership.key-index"; + +#[test] +fn a_membership_record_type_generates_its_unique_live_appointment_index() { + let registry = compile(&FIXTURES[0]); + let index = registry + .ddl() + .statements + .iter() + .find(|statement| statement.id == MEMBERSHIP_INDEX_ID) + .unwrap(); + assert_eq!(index.sql, concat!( + "CREATE UNIQUE INDEX \"breg_membership_key_b9ee6c3037\" ON registry_data.\"breg_e_membership_a36e7273b8ef4eb1\" ", + "(\"breg_f_membership_organization_bfa076d486640343\", \"breg_f_membership_principal_dbfb37e169be4783\") ", + "WHERE \"breg_f_membership_active_6e662651da1918d2\" IS TRUE AND record_lifecycle = 'active'" + )); + assert!(registry + .ddl() + .statements + .iter() + .any(|statement| statement.id == "entity.membership.index.reference:organization")); +} + +#[test] +fn a_record_type_without_membership_generates_no_membership_index() { + for fixture in &FIXTURES[1..] { + let registry = compile(fixture); + assert!(registry + .ddl() + .statements + .iter() + .all(|statement| !statement.id.ends_with(".membership.key-index"))); + } +} + +#[cfg(feature = "runtime")] +#[test] +fn an_unchanged_membership_declaration_acquires_its_index_over_a_pre_index_baseline() { + use registry_breg::package::{ + change_set_to_applicable_migration_plan, compiled_registry_change_set_from_baseline, + CompiledRegistryMigrationBaseline, + }; + let registry = compile(&FIXTURES[0]); + let mut baseline = CompiledRegistryMigrationBaseline::from_compiled("prior", ®istry); + let mut old_ddl = registry.ddl().clone(); + old_ddl + .statements + .retain(|statement| statement.id != MEMBERSHIP_INDEX_ID); + let old_digest = format!("sha256:{}", sha256(old_ddl.script().as_bytes())); + assert_eq!( + old_digest, + "sha256:88ce9380a31f7201ccda598870579c46fba1352db5598b0eb667bbb23bf68042" + ); + baseline.generated_ddl_sha256 = Some(old_digest); + let changes = compiled_registry_change_set_from_baseline(&baseline, ®istry, "prior"); + assert!(changes.changes.is_empty()); + let plan = change_set_to_applicable_migration_plan(&changes).unwrap(); + let statement = registry + .ddl() + .statements + .iter() + .find(|statement| statement.id == MEMBERSHIP_INDEX_ID) + .unwrap(); + assert!(plan.statements.contains(statement)); + let probe = plan + .statements + .iter() + .find(|statement| statement.id.starts_with("registry_context.membership_")) + .unwrap(); + assert!(probe.sql.starts_with("CREATE OR REPLACE FUNCTION")); +} diff --git a/crates/registry-breg/tests/compiler_contract.rs b/crates/registry-breg/tests/compiler_contract.rs index 1afb6353a9..593d0a68e3 100644 --- a/crates/registry-breg/tests/compiler_contract.rs +++ b/crates/registry-breg/tests/compiler_contract.rs @@ -17,9 +17,9 @@ use registry_breg::contract::{ parse_module_json, parse_module_yaml, parse_project_json, parse_project_yaml, ActionExecutionSource, ActionSource, BatchSource, Classification, ComparisonOperator, ConstraintSource, DerivedFieldSource, DerivedSource, DisplaySource, FieldTypeSource, - ModelDisplaySource, ModuleAssetSource, ModuleLockSource, Operation, PackageIdentitySource, - ReferenceDelete, RegistryModule, ReviewAuthoritySource, UniqueWhenPredicate, - MODULE_API_VERSION, MODULE_KIND, + ManifestProjectionEntitySource, ModelDisplaySource, ModuleAssetSource, ModuleLockSource, + Operation, PackageIdentitySource, ReferenceDelete, RegistryModule, ReviewAuthoritySource, + UniqueWhenPredicate, MODULE_API_VERSION, MODULE_KIND, }; use registry_breg::diagnostics::{CompileFailure, DiagnosticSeverity}; use registry_breg::generated_ddl::DdlStatementKind; @@ -1415,6 +1415,59 @@ fn manifest_projection_excludes_every_protected_resource_from_public_bytes() { } } +#[test] +fn projection_refuses_record_type_metadata_id_collisions() { + let mut source = multi_dataset_value(); + source["manifestProjection"]["entities"] = json!([ + {"id": "person-record"}, + {"id": "person_record"} + ]); + let failure = parse_project_json(&serde_json::to_vec(&source).unwrap()) + .expect_err("lookalike Record type metadata ids are refused"); + assert!( + failure.diagnostics().iter().any(|diagnostic| { + diagnostic.code == "breg.manifest.record-type-id-collision" + && diagnostic.path == "project.manifestProjection.entities[1].id" + }), + "{failure:?}" + ); +} + +#[test] +fn projection_refuses_duplicate_record_type_metadata() { + let mut project = multi_dataset_project(); + let metadata: ManifestProjectionEntitySource = + serde_json::from_value(json!({"id": "person"})).expect("valid projection metadata"); + // This typed input bypasses the document reader's identifier collision check. + project.manifest_projection.as_mut().unwrap().entities = vec![metadata.clone(), metadata]; + assert_compile_diagnostic(project, "breg.manifest-projection.record-type-duplicate"); +} + +#[test] +fn projection_refuses_record_types_in_an_unpublished_dataset() { + let mut project = multi_dataset_project(); + project + .manifest_projection + .as_mut() + .unwrap() + .datasets + .remove(0); + assert_compile_diagnostic( + project, + "breg.manifest-projection.record-type-dataset-dangling", + ); +} + +#[test] +fn projection_refuses_datasets_without_record_types() { + let mut empty_dataset = multi_dataset_project(); + empty_dataset.entities[1].primary_dataset = "people".to_owned(); + assert_compile_diagnostic( + empty_dataset, + "breg.manifest-projection.dataset-record-types-empty", + ); +} + #[test] fn plural_projection_refuses_duplicate_and_dangling_membership() { let mut missing_canonical_iri = multi_dataset_project(); @@ -1452,14 +1505,7 @@ fn plural_projection_refuses_duplicate_and_dangling_membership() { missing.entities[0].primary_dataset.clear(); assert_compile_diagnostic( missing, - "breg.manifest-projection.entity-primary-dataset-required", - ); - - let mut empty_dataset = multi_dataset_project(); - empty_dataset.entities[1].primary_dataset = "people".to_owned(); - assert_compile_diagnostic( - empty_dataset, - "breg.manifest-projection.dataset-entities-empty", + "breg.manifest-projection.record-type-primary-dataset-required", ); let mut duplicate_service = multi_dataset_project(); @@ -1601,7 +1647,7 @@ fn missing_resource_identity_members_have_actionable_authoring_diagnostics() { "project.project.canonicalBaseIri" ))); assert!(project_codes.contains(&( - "breg.manifest-projection.entity-primary-dataset-required", + "breg.manifest-projection.record-type-primary-dataset-required", "recordTypes[id=record].primaryDataset" ))); @@ -1621,7 +1667,7 @@ fn missing_resource_identity_members_have_actionable_authoring_diagnostics() { let module = compile_project(&project, &[module], CompileProfile::Authoring) .expect_err("module entity membership is required for compilation"); assert!(module.diagnostics().iter().any(|diagnostic| { - diagnostic.code == "breg.manifest-projection.entity-primary-dataset-required" + diagnostic.code == "breg.manifest-projection.record-type-primary-dataset-required" && diagnostic.path == "recordTypes[id=record].primaryDataset" })); } @@ -2277,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":"unrestricted","permissions":{{"records":[{{ + "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"] }}]}} }}}} }}"# @@ -2419,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"] @@ -3674,7 +3747,7 @@ fn manifest_projection_metadata_cannot_describe_hidden_entities_or_fields() { assert!(codes.contains("breg.manifest-projection.field-not-visible")); assert!(codes.contains("breg.manifest-projection.field-not-representable")); - assert!(codes.contains("breg.manifest-projection.entity-not-visible")); + assert!(codes.contains("breg.manifest-projection.record-type-not-visible")); } #[test] @@ -4024,7 +4097,7 @@ fn independent_additive_modules_are_order_independent() { "recordTypes":{"object": {"primaryDataset":"test-dataset","route":"objects","mutationMode":"mutable", "fields":[{"id":"code","type":"string","maximumLength":32,"required":true,"classification":"internal"}] }}, - "accessProfiles":{"operator": {"default":true,"principalClaim":"registry_principal","requiredScopes":"unrestricted","permissions":{"records":[{ + "accessProfiles":{"operator": {"default":true,"principalClaim":"registry_principal","requiredScopes":["records:write"],"permissions":{"records":[{ "recordType":"object","operations":["create","get","list","patch"], "readableFields":["code"],"writableFields":["code"], "rowBoundaries": "unrestricted" @@ -4893,7 +4966,7 @@ fn generic_decimal_crs84_point_and_structured_fields_compile_to_deterministic_dd }} ] }}, - "accessProfiles":{"operator": {"default":true,"principalClaim":"principal","requiredScopes":"unrestricted","permissions":{"records":[{ + "accessProfiles":{"operator": {"default":true,"principalClaim":"principal","requiredScopes":["records:write"],"permissions":{"records":[{ "recordType":"reading","operations":["create","get","list","patch"], "readableFields":["amount","location","payload"], "writableFields":["amount","location","payload"], @@ -5425,7 +5498,7 @@ fn action_decimal_bound_diagnostic_names_capacity_and_preserves_valid_bounds() { "accessProfiles": {"operator": { "default": true, "principalClaim": "principal", - "requiredScopes": "unrestricted", + "requiredScopes": ["records:write"], "permissions": {"actions": [{ "action": "create-entry", "operations": ["invoke"], @@ -6683,8 +6756,13 @@ fn generated_openapi_routes_and_physical_names_share_one_compiled_inventory() { "precondition.failed", "precondition.required", "profile.not-authorized", + "proposal.form-limit-reached", + "proposal.form-undeclared", + "proposal.message-limit-reached", "proposal.rejected", "proposal.review-result-mismatch", + "proposal.subject-changed", + "proposal.subject-not-caller", "proposal.submission-expired", "query.cursor-invalid", "query.filter-required", @@ -6810,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()); @@ -6863,7 +6955,7 @@ fn generated_openapi_separates_security_and_mutation_input_from_read_schema() { }]} },"business": { "principalClaim":"registry_principal", - "requiredScopes":"unrestricted", + "requiredScopes":["records:write"], "requiredPurposes":["business"], "permissions":{"records":[{ "recordType":"business-record", @@ -7657,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") @@ -8030,7 +8125,7 @@ fn revision_schemas_declare_the_proposal_link_only_for_a_registry_with_proposal_ "inputs":[{"id":"target","type":"reference","target":"target","required":true,"classification":"internal"}, {"id":"value","type":"string","required":true,"maximumLength":64,"classification":"internal"}], "plan":{"type":"fixed","effects":[{"id":"name","target":{"fromInput":"target"},"operation":"patch","set":{"name":{"fromInput":"value"}}}]}}}, - "accessProfiles":{"historian": {"default":true,"principalClaim":"principal","requiredScopes":"unrestricted","permissions":{ + "accessProfiles":{"historian": {"default":true,"principalClaim":"principal","requiredScopes":["records:write"],"permissions":{ "records":[{"recordType":"target","operations":["get","revisions"],"revisionAccess":true, "readableFields":["name"],"rowBoundaries":"unrestricted"}], "actions":[{"action":"correct-name","operations":[operation],"targets":targets}], @@ -8041,7 +8136,7 @@ fn revision_schemas_declare_the_proposal_link_only_for_a_registry_with_proposal_ json!({"mode":"proposal","proposal":{"review":{"type":"none"}, "application":{"mode":"manual"},"retention":{"mode":"operator-erase"}}}), "start", - json!([{"action":"correct-name","operations":["get"],"ownership":"caller","targets":targets}]), + json!([{"action":"correct-name","operations":["get"],"party":"owner","targets":targets}]), ); let immediate = source(json!({"mode":"immediate"}), "invoke", json!([])); let revision_schemas = |source: &Value| { diff --git a/crates/registry-breg/tests/compiler_statistics.rs b/crates/registry-breg/tests/compiler_statistics.rs index 5251512561..5fa3898b22 100644 --- a/crates/registry-breg/tests/compiler_statistics.rs +++ b/crates/registry-breg/tests/compiler_statistics.rs @@ -819,17 +819,16 @@ fn statistical_disclosure_bounds_are_refused_when_the_project_is_read() { } #[test] -fn statistical_dataset_refuses_caller_dependent_publisher_authority() { - assert_refused( - |value| { - value["recordTypes"]["record"]["fields"] - .as_array_mut() - .unwrap() - .push(json!({ - "id":"organization","type":"reference","target":"organization", - "required":true,"classification":"internal" - })); - value["recordTypes"].as_object_mut().unwrap().extend([ +fn the_statistics_dependency_diagnostic_names_row_boundaries_for_a_membership_entry() { + let mut value = source(); + value["recordTypes"]["record"]["fields"] + .as_array_mut() + .unwrap() + .push(json!({ + "id":"organization","type":"reference","target":"organization", + "required":true,"classification":"internal" + })); + value["recordTypes"].as_object_mut().unwrap().extend([ ("organization".to_owned(), json!({"primaryDataset":"statistics-test","route":"organizations", "mutationMode":"mutable","fields":[ {"id":"name","type":"string","maximumLength":80,"classification":"internal"} @@ -846,16 +845,25 @@ fn statistical_dataset_refuses_caller_dependent_publisher_authority() { "accessRequirements":{"requiredScopes":["membership:use"]} })) ]); - value["accessProfiles"]["publisher"]["requiredScopes"] = json!(["membership:use"]); - value["accessProfiles"]["publisher"]["permissions"]["records"][0] - ["membershipBoundaries"] = json!([{ - "field":"organization","membershipRecordType":"membership", - "membershipKeyField":"organization","principalField":"principal","activeField":"active" - }]); - }, - "breg.statistical-dataset.publisher-caller-dependent", + value["recordTypes"]["membership"]["membership"] = + json!({"key":"organization","principal":"principal","active":"active"}); + value["accessProfiles"]["publisher"]["requiredScopes"] = json!(["membership:use"]); + value["accessProfiles"]["publisher"]["permissions"]["records"][0]["rowBoundaries"] = + json!([{"field":"organization","membership":"membership"}]); + let refusal = compile(&value).unwrap_err(); + let diagnostic = refusal + .diagnostics() + .iter() + .find(|diagnostic| diagnostic.code == "breg.statistical-dataset.publisher-caller-dependent") + .unwrap(); + assert!( + diagnostic.message.contains("rowBoundaries"), + "{diagnostic:?}" ); +} +#[test] +fn statistical_dataset_refuses_caller_dependent_publisher_authority() { assert_refused( |value| { let boundary = json!({"field":"category","claim":"categories","operator":"in"}); @@ -2046,6 +2054,7 @@ fn without_publisher_derived_read(value: &mut Value) { #[test] fn derived_dimension_records_entity_and_evaluation_date_dependencies() { let mut value = source(); + value["accessProfiles"][PUBLISHER]["requiredScopes"] = json!(["statistics:publish"]); value["recordTypes"]["record"]["derived"] = json!([{ "id":"statistics","sql":"sql/statistics.sql","key":"id", "fields":[{"id":"evaluated-category","type":"vocabulary-code","vocabulary":"category","values":["a","b"],"classification":"internal"}] diff --git a/crates/registry-breg/tests/consent_access.rs b/crates/registry-breg/tests/consent_access.rs index 8c62320169..7a57c875ed 100644 --- a/crates/registry-breg/tests/consent_access.rs +++ b/crates/registry-breg/tests/consent_access.rs @@ -1548,9 +1548,34 @@ fn a_profile_that_only_writes_or_invokes_on_a_gated_entity_is_not_an_ungated_cli .collect::>() }; // A create response echoes only the row the caller just wrote, so a - // create-only permission reads no existing row without consent. + // create-only permission reads no existing row without consent. Naming a + // person or an enrolment in a write needs a read of it, so the create-only + // steward writes persons, and names neither persons nor enrolments. + let create_only_steward = |project: &mut Value| { + let records = project["accessProfiles"][STEWARD]["permissions"]["records"] + .as_array_mut() + .unwrap(); + records.retain(|permission| permission["recordType"] != "enrolment"); + for permission in records.iter_mut() { + if permission["recordType"] == "person" { + permission["operations"] = json!(["create"]); + } + if permission["recordType"] == "household-member" + || permission["recordType"] == "enrolment-household" + { + permission["operations"] = json!(["get"]); + permission.as_object_mut().unwrap().remove("writableFields"); + } + } + }; let mut create_only = source(); - for permission in create_only["accessProfiles"][STEWARD]["permissions"]["records"] + create_only_steward(&mut create_only); + assert_eq!(findings(&create_only), Vec::::new()); + + // A create-only enrolment names a person, so the steward needs a read of + // persons, which the gated person grant answers only with consent. + let mut create_only_enrolment = source(); + for permission in create_only_enrolment["accessProfiles"][STEWARD]["permissions"]["records"] .as_array_mut() .unwrap() { @@ -1558,7 +1583,16 @@ fn a_profile_that_only_writes_or_invokes_on_a_gated_entity_is_not_an_ungated_cli permission["operations"] = json!(["create"]); } } - assert_eq!(findings(&create_only), Vec::::new()); + let refused = compile(&create_only_enrolment).expect_err("naming a person needs a read of it"); + assert!( + refused.diagnostics().iter().any(|diagnostic| { + diagnostic.code == "breg.access.reference-target-ungranted" + && diagnostic.path + == "recordTypes[id=enrolment].accessProfiles[id=steward].writableFields[field=person]" + }), + "{:?}", + refused.diagnostics() + ); // A patch answers with an existing row, so it still reads without consent. let mut patching = create_only.clone(); @@ -1578,13 +1612,6 @@ fn a_profile_that_only_writes_or_invokes_on_a_gated_entity_is_not_an_ungated_cli // An action target with empty row boundaries on the gated entity only // lets the action reference a row; it reads nothing through the profile. let mut self_issued = self_issued_project(); - for permission in self_issued["accessProfiles"][STEWARD]["permissions"]["records"] - .as_array_mut() - .unwrap() - { - if permission["recordType"] == "person" || permission["recordType"] == "enrolment" { - permission["operations"] = json!(["create"]); - } - } + create_only_steward(&mut self_issued); assert_eq!(findings(&self_issued), Vec::::new()); } diff --git a/crates/registry-breg/tests/data_operations.rs b/crates/registry-breg/tests/data_operations.rs index 68f2c07ebb..94daa7e7ff 100644 --- a/crates/registry-breg/tests/data_operations.rs +++ b/crates/registry-breg/tests/data_operations.rs @@ -50,7 +50,7 @@ fn compiled(allow_data_export: bool) -> registry_breg::CompiledRegistry { }}, "accessProfiles": {PROFILE: { "principalClaim": "principal", - "requiredScopes": "unrestricted", + "requiredScopes": ["records:write"], "permissions": {"records": [{ "recordType": ENTITY, "operations": ["create", "patch", "batch", "list"], @@ -336,7 +336,7 @@ fn data_validate_and_chunk_plan_reuse_runtime_rules_and_compiled_batch_bounds() "batch":{"maximumItems":2,"maximumBytes":100}, "fields":[{"id":"code","type":"text","maximumLength":1000,"required":true, "classification":"internal"}]}}, - "accessProfiles":{PROFILE: {"principalClaim":"principal","requiredScopes":"unrestricted","permissions":{"records":[{ + "accessProfiles":{PROFILE: {"principalClaim":"principal","requiredScopes":["records:write"],"permissions":{"records":[{ "recordType":ENTITY, "operations":["create","batch"],"readableFields":["code"], "writableFields":["code"], "rowBoundaries": "unrestricted"}]}}} @@ -385,7 +385,7 @@ fn data_lifecycle_uses_exact_compiled_api_names() { }}, "accessProfiles": {PROFILE: { "principalClaim": "principal", - "requiredScopes": "unrestricted", + "requiredScopes": ["records:write"], "permissions": {"records": [{ "recordType": ENTITY, "operations": ["create", "patch", "batch", "list"], diff --git a/crates/registry-breg/tests/disclosure/fields.rs b/crates/registry-breg/tests/disclosure/fields.rs index 6f01d64af3..78e5ddc092 100644 --- a/crates/registry-breg/tests/disclosure/fields.rs +++ b/crates/registry-breg/tests/disclosure/fields.rs @@ -75,6 +75,7 @@ fn compile_writable_project(mut source: Value) -> registry_breg::CompiledRegistr .unwrap() .values_mut() { + profile["requiredScopes"] = json!(["records:write"]); let grant = &mut profile["permissions"]["records"][0]; assert_eq!(grant["recordType"], "person"); grant["operations"] = json!(["create", "get", "list", "patch", "batch"]); @@ -206,7 +207,7 @@ async fn send( let claims = VerifiedRequestClaims::authenticated( "registry_principal", "canary-principal", - BTreeSet::new(), + BTreeSet::from(["records:write".to_owned()]), None, std::collections::BTreeMap::new(), ) diff --git a/crates/registry-breg/tests/disclosure/history.rs b/crates/registry-breg/tests/disclosure/history.rs index 8d319bc5b0..fb02bb846b 100644 --- a/crates/registry-breg/tests/disclosure/history.rs +++ b/crates/registry-breg/tests/disclosure/history.rs @@ -79,7 +79,7 @@ fn history_source() -> Value { }; let person_target = json!([{"recordType": "person", "rowBoundaries": "unrestricted"}]); source["accessProfiles"][WRITER] = json!({ - "principalClaim": "registry_principal", "requiredScopes": "unrestricted", + "principalClaim": "registry_principal", "requiredScopes": ["records:write"], "permissions": { "records": [ writable("person", &PERSON_FIELDS), @@ -91,7 +91,7 @@ fn history_source() -> Value { {"action": "correct-person-name", "operations": ["start"], "targets": person_target.clone()}], "proposals": [ - {"action": "correct-person-name", "ownership": "caller", + {"action": "correct-person-name", "party": "owner", "operations": ["get", "list", "edit", "submit", "revise", "rebase", "retry", "cancel", "apply"], "targets": person_target}]}}); source["actions"] = json!({ @@ -131,7 +131,7 @@ fn claims() -> VerifiedRequestClaims { VerifiedRequestClaims::authenticated_with_actor_kind( "registry_principal", "history-principal", - BTreeSet::new(), + BTreeSet::from(["records:write".to_owned()]), None, BTreeMap::::new(), registry_platform_oidc::ActorKind::Human, @@ -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/disclosure/proposals.rs b/crates/registry-breg/tests/disclosure/proposals.rs index 285aa26542..1247cc76d5 100644 --- a/crates/registry-breg/tests/disclosure/proposals.rs +++ b/crates/registry-breg/tests/disclosure/proposals.rs @@ -38,7 +38,7 @@ fn claims() -> VerifiedRequestClaims { VerifiedRequestClaims::authenticated_with_actor_kind( "sub", "reviewer", - BTreeSet::new(), + BTreeSet::from(["proposals:write".to_owned()]), None, BTreeMap::new(), registry_platform_oidc::ActorKind::Human, @@ -50,7 +50,7 @@ fn action_grant(action: &str, record_type: &str, context: &[&str]) -> (Value, Va ( json!({"action": action, "operations": ["start"], "targets": [{"recordType": record_type, "rowBoundaries": "unrestricted"}]}), - json!({"action": action, "ownership": "caller", + json!({"action": action, "party": "owner", "operations": ["get", "list", "edit", "submit", "revise", "rebase", "retry", "cancel", "apply", "get-review-context"], "readableAttachments": [], "writableAttachments": [], @@ -111,6 +111,7 @@ fn proposal_project() -> Value { .values_mut() { profile["principalClaim"] = json!("sub"); + profile["requiredScopes"] = json!(["proposals:write"]); let records = profile["permissions"]["records"].as_array_mut().unwrap(); for grant in records.iter_mut() { let writable: &[&str] = match grant["recordType"].as_str().unwrap() { diff --git a/crates/registry-breg/tests/disclosure/writes.rs b/crates/registry-breg/tests/disclosure/writes.rs index b05d4341a3..16651105d4 100644 --- a/crates/registry-breg/tests/disclosure/writes.rs +++ b/crates/registry-breg/tests/disclosure/writes.rs @@ -51,6 +51,7 @@ fn writes_source() -> Value { let lifecycle = proposal_lifecycle(); for (id, profile) in source["accessProfiles"].as_object_mut().unwrap() { let writer = id == WRITER; + profile["requiredScopes"] = json!(["records:write"]); let permissions = &mut profile["permissions"]; if !writer { let grant = &mut permissions["records"][0]; @@ -83,9 +84,9 @@ fn writes_source() -> Value { json!({"action": "correct-person-email", "operations": ["start"], "targets": targets}), ]); permissions["proposals"].as_array_mut().unwrap().extend([ - json!({"action": "propose-person-email", "ownership": "caller", + json!({"action": "propose-person-email", "party": "owner", "operations": lifecycle, "targets": targets}), - json!({"action": "correct-person-email", "ownership": "caller", + json!({"action": "correct-person-email", "party": "owner", "operations": lifecycle, "targets": targets}), ]); } @@ -619,7 +620,7 @@ const ACTION_CLERK: &str = "action-clerk"; fn action_clerk_source(exempt: bool) -> Value { let mut source = writes_source(); source["accessProfiles"][ACTION_CLERK] = json!({ - "principalClaim": "registry_principal", "requiredScopes": "unrestricted", + "principalClaim": "registry_principal", "requiredScopes": ["records:write"], "permissions": {"actions": [ {"action": "set-person-email", "operations": ["invoke"], "targets": [{"recordType": "person", "rowBoundaries": "unrestricted"}]}]}}); @@ -1165,9 +1166,9 @@ fn residence_source() -> Value { "targets": targets}), ]); permissions["proposals"].as_array_mut().unwrap().extend([ - json!({"action": "propose-residence-protection", "ownership": "caller", + json!({"action": "propose-residence-protection", "party": "owner", "operations": proposal_lifecycle(), "targets": targets}), - json!({"action": "correct-residence-protection", "ownership": "caller", + json!({"action": "correct-residence-protection", "party": "owner", "operations": proposal_lifecycle(), "targets": targets}), ]); } diff --git a/crates/registry-breg/tests/disclosure_compile.rs b/crates/registry-breg/tests/disclosure_compile.rs index 6ea24a82e0..66ac5d40b3 100644 --- a/crates/registry-breg/tests/disclosure_compile.rs +++ b/crates/registry-breg/tests/disclosure_compile.rs @@ -313,9 +313,10 @@ fn workflow_source() -> Value { let targets = |record_type: &str| json!([{"recordType":record_type,"rowBoundaries":"unrestricted"}]); let clerk = |permissions: Value| { - json!({"principalClaim":"registry_principal","requiredScopes":"unrestricted", + json!({"principalClaim":"registry_principal","requiredScopes":["registry:workflow"], "permissions":permissions}) }; + value["accessProfiles"]["protection-officer"]["requiredScopes"] = json!(["registry:workflow"]); value["accessProfiles"]["protection-officer"]["permissions"]["actions"] = json!([ {"action":"propose-person-name","operations":["start"],"targets":targets("person")}]); let profiles = value["accessProfiles"].as_object_mut().unwrap(); @@ -327,7 +328,7 @@ fn workflow_source() -> Value { profiles.insert( "proposal-clerk".to_owned(), clerk(json!({"proposals":[ - {"action":"propose-person-name","ownership":"caller","operations":["get","list","apply"], + {"action":"propose-person-name","party":"owner","operations":["get","list","apply"], "targets":targets("person")}]})), ); profiles.insert( @@ -1360,6 +1361,43 @@ fn a_derived_field_cannot_read_a_record_type_its_reader_cannot_read() { assert!(codes(compile_with_sql(&value, VISIT_SQL)).contains(&UNREADABLE_SOURCE.to_owned())); } +#[test] +fn a_reference_grant_does_not_let_a_derived_field_read_its_record_type() { + // A reference grant only lets the profile's writes name records. It reads + // no field, so a derived field computed over that type still needs a + // grant that reads it. + let with_grant = |operations: Value| { + let mut value = visit_source(); + value["recordTypes"]["person"]["fields"] + .as_array_mut() + .unwrap() + .push(json!({"id":"last-visit","type":"reference","target":"visit","classification":"internal"})); + // A writing profile admits only callers with its scope. + value["accessProfiles"][REGISTRAR]["requiredScopes"] = json!(["people:write"]); + let person = person_permission(&mut value, REGISTRAR); + person["operations"] = json!(["get", "list", "patch"]); + person["writableFields"] = json!(["last-visit"]); + let mut grant = json!({"recordType":"visit","operations":operations, + "rowBoundaries":"unrestricted","readableFields":[]}); + if grant["operations"] == json!(["get"]) { + grant["readableFields"] = json!(["person"]); + } + value["accessProfiles"][REGISTRAR]["permissions"]["records"] + .as_array_mut() + .unwrap() + .push(grant); + value + }; + let found = derived_diagnostics(&with_grant(json!(["reference"])), VISIT_SQL); + assert!( + found.iter().any(|(code, path, _)| code == UNREADABLE_SOURCE + && path == "recordTypes[id=visit].accessProfiles[id=registrar].operations"), + "expected {UNREADABLE_SOURCE}, got {found:?}" + ); + // The same project with a grant that reads visits compiles. + assert_compiles_with_sql(&with_grant(json!(["get"])), VISIT_SQL); +} + #[test] fn a_derived_field_may_read_a_record_type_under_the_same_row_boundaries() { let mut unrestricted = visit_source(); @@ -1597,8 +1635,7 @@ fn a_membership_boundary_on_a_derived_source_grant_is_a_finding() { value["recordTypes"]["facility"]["derived"] = json!([{"id":"inspection-state","sql":"sql/derived.sql","key":"id", "fields":[{"id":"has-passed-inspection","type":"boolean","classification":"internal"}]}]); let sql = "SELECT f.id AS id, (count(i.id) FILTER (WHERE i.passed IS TRUE) > 0) AS has_passed_inspection FROM registry_source.facility f LEFT JOIN registry_source.inspection i ON i.facility = f.id GROUP BY f.id"; - let membership = json!([{"field":"organization","membershipRecordType":"membership", - "membershipKeyField":"organization","principalField":"principal","activeField":"active"}]); + let membership = json!([{"field":"organization","membership":"membership"}]); let grant = |profile: &str, value: &mut Value, membership: Option<&Value>| { let records = value["accessProfiles"][profile]["permissions"]["records"] .as_array_mut() @@ -1614,7 +1651,7 @@ fn a_membership_boundary_on_a_derived_source_grant_is_a_finding() { let mut inspection = json!({"recordType":"inspection","operations":["get"], "rowBoundaries":"unrestricted","readableFields":["facility"]}); if let Some(membership) = membership { - inspection["membershipBoundaries"] = membership.clone(); + inspection["rowBoundaries"] = membership.clone(); } records.push(inspection); }; @@ -1623,13 +1660,53 @@ fn a_membership_boundary_on_a_derived_source_grant_is_a_finding() { grant("member", &mut member, None); assert!(withheld_source_rows(compile_with_sql(&member, sql)).is_empty()); + let mut missing = member.clone(); + missing["accessProfiles"]["member"]["permissions"]["records"] + .as_array_mut() + .unwrap() + .pop(); + let unreadable = compile_with_sql(&missing, sql).unwrap_err(); + let message = &unreadable + .diagnostics() + .iter() + .find(|diagnostic| diagnostic.code == UNREADABLE_SOURCE) + .unwrap() + .message; + assert!( + message.contains("requires membership through `membership`"), + "{message}" + ); + assert!(!message.contains("`unrestricted`"), "{message}"); + + let mut different = member.clone(); + different["recordTypes"]["inspection"]["fields"] + .as_array_mut() + .unwrap() + .push( + json!({"id":"region","type":"string","maximumLength":16,"classification":"internal"}), + ); + different["accessProfiles"]["member"]["permissions"]["records"][1]["rowBoundaries"] = + json!([{"field":"region","claim":"region","operator":"equals"}]); + let mismatch = compile_with_sql(&different, sql).unwrap_err(); + let message = &mismatch + .diagnostics() + .iter() + .find(|diagnostic| diagnostic.code == SOURCE_BOUNDARY) + .unwrap() + .message; + assert!( + message.contains("retaining the required membership restrictions"), + "{message}" + ); + assert!(!message.contains("`unrestricted`"), "{message}"); + // The reader's grant on the facility carries the same membership. let mut member = value.clone(); grant("member", &mut member, Some(&membership)); let found = withheld_source_rows(compile_with_sql(&member, sql)); assert_eq!( finding_paths(&found), - ["recordTypes[id=inspection].accessProfiles[id=member].membershipBoundaries"] + ["recordTypes[id=inspection].accessProfiles[id=member].rowBoundaries"] ); for named in [ "`member`", @@ -1647,14 +1724,22 @@ fn a_membership_boundary_on_a_derived_source_grant_is_a_finding() { grant("member", &mut member, Some(&other_field)); assert_eq!( finding_paths(&withheld_source_rows(compile_with_sql(&member, sql))), - ["recordTypes[id=inspection].accessProfiles[id=member].membershipBoundaries"] + ["recordTypes[id=inspection].accessProfiles[id=member].rowBoundaries"] ); - // The steward's grant on the facility carries none. - grant("steward", &mut value, Some(&membership)); + // A profile whose own facility grant carries none. It cannot be the + // membership writer: a profile bounded through a source cannot also + // create that source's rows. + let mut auditor = value["accessProfiles"]["steward"].clone(); + auditor["permissions"]["records"] + .as_array_mut() + .unwrap() + .retain(|record| record["recordType"] != "membership"); + value["accessProfiles"]["auditor"] = auditor; + grant("auditor", &mut value, Some(&membership)); assert_eq!( finding_paths(&withheld_source_rows(compile_with_sql(&value, sql))), - ["recordTypes[id=inspection].accessProfiles[id=steward].membershipBoundaries"] + ["recordTypes[id=inspection].accessProfiles[id=auditor].rowBoundaries"] ); } diff --git a/crates/registry-breg/tests/disclosure_exposure.rs b/crates/registry-breg/tests/disclosure_exposure.rs index 79213fb0ce..d60f093c11 100644 --- a/crates/registry-breg/tests/disclosure_exposure.rs +++ b/crates/registry-breg/tests/disclosure_exposure.rs @@ -5,6 +5,7 @@ //! caller, but the author surfaces list the conditions in full. use registry_breg::access::explain_access; +#[cfg(all(feature = "runtime", feature = "tooling"))] use registry_breg::access_preview::{preview_access, AccessScenario}; use registry_breg::artifacts::inspect_registry; use registry_breg::odrl_export::export_odrl; @@ -67,6 +68,7 @@ fn author_inspection_lists_the_conditions_in_full() { ); } +#[cfg(all(feature = "runtime", feature = "tooling"))] fn scenario(profile: &str) -> AccessScenario { serde_json::from_value( json!({"recordType":"person","accessProfile":profile,"operation":"get", @@ -76,6 +78,7 @@ fn scenario(profile: &str) -> AccessScenario { .unwrap() } +#[cfg(all(feature = "runtime", feature = "tooling"))] #[test] fn the_access_preview_names_the_conditions_that_bind_the_profile() { let registry = compiled(); @@ -213,7 +216,7 @@ fn acting(bound_by: Option<&str>) -> Value { {"action": "set-person-phone", "operations": ["invoke"], "targets": targets}, {"action": "propose-person-phone", "operations": ["start"], "targets": targets}]); registrar["permissions"]["proposals"] = json!([ - {"action": "propose-person-phone", "ownership": "caller", + {"action": "propose-person-phone", "party": "owner", "operations": ["get", "list", "edit", "submit", "cancel", "apply"], "readableInputs": ["person", "phone"], "targets": targets}]); value diff --git a/crates/registry-breg/tests/explicit_row_authority.rs b/crates/registry-breg/tests/explicit_row_authority.rs index e57c8ecf39..9bb8095ef4 100644 --- a/crates/registry-breg/tests/explicit_row_authority.rs +++ b/crates/registry-breg/tests/explicit_row_authority.rs @@ -66,25 +66,23 @@ fn invocation_and_mandatory_requirements_do_not_invent_row_grants() { #[test] fn membership_preserves_explicit_row_declarations_and_round_trips() { - let boundaries = json!([{ - "field":"organization", "membershipRecordType":"membership", - "membershipKeyField":"organization", "principalField":"principal", - "activeField":"active" - }]); - let mut grant = json!({ - "recordType":"record", "operations":["get"], "membershipBoundaries": boundaries - }); + let entry = json!([{"field":"organization", "membership":"membership"}]); + let mut grant = json!({"recordType":"record", "operations":["get"]}); requires_explicit_rows::(grant.clone()); - grant["rowBoundaries"] = json!("unrestricted"); + grant["rowBoundaries"] = entry.clone(); + grant["readableFields"] = json!({"upToClassification":"restricted"}); + let readable_fields = grant["readableFields"].clone(); let parsed: EntityPermissionSource = serde_json::from_value(grant).unwrap(); - assert_eq!(parsed.membership_boundaries.len(), 1); - assert_eq!( - serde_json::to_value(parsed).unwrap()["membershipBoundaries"], - boundaries - ); + assert_eq!(parsed.membership_row_boundaries.len(), 1); + let written = serde_json::to_value(parsed).unwrap(); + assert_eq!(written["rowBoundaries"], entry); + assert_eq!(written["readableFields"], readable_fields); carries_compiled_rows::(json!({ "id":"member", "principalClaim":"sub", "operations":["get"], - "membershipBoundaries": boundaries + "membershipBoundaries": [{ + "field":"organization", "membershipRecordType":"membership", + "membershipKeyField":"organization", "principalField":"principal", "activeField":"active" + }] })); } diff --git a/crates/registry-breg/tests/field_encryption_contract.rs b/crates/registry-breg/tests/field_encryption_contract.rs index 149b03beb6..3f125171af 100644 --- a/crates/registry-breg/tests/field_encryption_contract.rs +++ b/crates/registry-breg/tests/field_encryption_contract.rs @@ -34,7 +34,7 @@ fn encrypted_project() -> Value { "lookup":{"normalization":["trim","uppercase"],"unique":true}} ] }}, - "accessProfiles":{"caseworker": {"default":true,"principalClaim":"principal","requiredScopes":"unrestricted","permissions":{"records":[{ + "accessProfiles":{"caseworker": {"default":true,"principalClaim":"principal","requiredScopes":["records:write"],"permissions":{"records":[{ "recordType":"case","rowBoundaries":"unrestricted","operations":["get","list","create","patch"], "readableFields":["label","secret"],"writableFields":["label","secret"] }]}}} @@ -706,7 +706,7 @@ fn proposal_project() -> Value { .unwrap() .remove("writableFields"); permissions["actions"] = json!([{"action":"correct-case","operations":["start"],"targets":[{"recordType":"case","rowBoundaries":"unrestricted"}]}]); - permissions["proposals"] = json!([{"action":"correct-case","operations":["get","edit","submit","apply"],"ownership":"caller","readableInputs":["case","label"],"targets":[{"recordType":"case","rowBoundaries":"unrestricted"}]}]); + permissions["proposals"] = json!([{"action":"correct-case","operations":["get","edit","submit","apply"],"party":"owner","readableInputs":["case","label"],"targets":[{"recordType":"case","rowBoundaries":"unrestricted"}]}]); source } diff --git a/crates/registry-breg/tests/fixture_tooling.rs b/crates/registry-breg/tests/fixture_tooling.rs index c89d286d26..158a4e8f69 100644 --- a/crates/registry-breg/tests/fixture_tooling.rs +++ b/crates/registry-breg/tests/fixture_tooling.rs @@ -154,6 +154,7 @@ journeys: accessProfile: registrar claims: principal: fixture-registrar + scopes: [person:write] purpose: case-management directClaims: {{jurisdiction: {value}}} request: {{type: query, select: [personCode]}} @@ -227,8 +228,8 @@ journeys: ); let unknown_scope = journey("[zone-a, zone-b]").replace( - "purpose: case-management", - "purpose: case-management\n scopes: [registry:extra]", + "scopes: [person:write]", + "scopes: [person:write, registry:extra]", ); let error = validate_fixture_journeys(unknown_scope.as_bytes(), ®istry) .expect_err("sets do not permit undeclared scopes"); @@ -251,6 +252,7 @@ journeys: accessProfile: registrar claims: principal: fixture-registrar + scopes: [person:write] purpose: case-management directClaims: {jurisdiction: zone-a} request: @@ -266,6 +268,7 @@ journeys: accessProfile: registrar claims: principal: fixture-registrar + scopes: [person:write] purpose: case-management directClaims: {jurisdiction: zone-a} request: {type: query, select: [personCode, legalName], count: true} @@ -275,6 +278,7 @@ journeys: accessProfile: registrar claims: principal: fixture-registrar + scopes: [person:write] purpose: case-management directClaims: {jurisdiction: zone-a} request: @@ -349,6 +353,7 @@ journeys: accessProfile: household-seed claims: principal: fixture-seed + scopes: [household:write] purpose: case-management directClaims: {jurisdiction: zone-a} request: @@ -800,7 +805,7 @@ fn compiled_crud_alias_fixture() -> registry_breg::CompiledRegistry { ], "constraints":[{"type":"unique","fields":["person-code"]}] }}, - "accessProfiles":{"registrar": {"default":true,"principalClaim":"registry_principal","requiredScopes":"unrestricted","requiredPurposes":["case-management"], + "accessProfiles":{"registrar": {"default":true,"principalClaim":"registry_principal","requiredScopes":["person:write"],"requiredPurposes":["case-management"], "permissions":{"records":[{ "recordType":"person","operations":["create","get","list","patch"], "readableFields":["jurisdiction","person-code","legal-name"], @@ -859,7 +864,7 @@ fn compiled_action_fixture() -> registry_breg::CompiledRegistry { "set":{"contact-person":{"fromEffect":"person"}}} ]} }}, - "accessProfiles":{"household-seed": {"default":true,"principalClaim":"registry_principal","requiredScopes":"unrestricted","requiredPurposes":["case-management"], + "accessProfiles":{"household-seed": {"default":true,"principalClaim":"registry_principal","requiredScopes":["household:write"],"requiredPurposes":["case-management"], "permissions":{"records":[{ "recordType":"household","operations":["create","get"],"readableFields":["jurisdiction","household-code","contact-person"], "writableFields":["jurisdiction","household-code"],"rowBoundaries":[{"field":"jurisdiction","claim":"jurisdiction","operator":"equals"}] @@ -1013,7 +1018,7 @@ fn fixture_journey_reader_reports_every_unknown_removed_and_anchored_key_with_it (source.line, source.column) }) .collect::>(); - assert_eq!(positions, [(Some(8), Some(9)), (Some(16), Some(11))]); + assert_eq!(positions, [(Some(8), Some(9)), (Some(17), Some(11))]); assert!( !format!("{error:?}").contains("canary"), "the refusal carries no authored value: {error:?}" @@ -1500,6 +1505,7 @@ journeys: accessProfile: registrar claims: principal: private-principal-canary + scopes: [person:write] purpose: case-management directClaims: {direct_claims} request: {{type: list}} diff --git a/crates/registry-breg/tests/fixtures/absent-optional-action-inputs.yaml b/crates/registry-breg/tests/fixtures/absent-optional-action-inputs.yaml index f2534634fe..90d2461489 100644 --- a/crates/registry-breg/tests/fixtures/absent-optional-action-inputs.yaml +++ b/crates/registry-breg/tests/fixtures/absent-optional-action-inputs.yaml @@ -46,7 +46,7 @@ accessProfiles: registrar: default: true principalClaim: registry_principal - requiredScopes: unrestricted + requiredScopes: [registry:contact:register] permissions: actions: - action: create-entry diff --git a/crates/registry-breg/tests/fixtures/authority-mapping.yaml b/crates/registry-breg/tests/fixtures/authority-mapping.yaml index e6ea50048c..08c03711b3 100644 --- a/crates/registry-breg/tests/fixtures/authority-mapping.yaml +++ b/crates/registry-breg/tests/fixtures/authority-mapping.yaml @@ -52,7 +52,7 @@ accessProfiles: reviewer: default: true principalClaim: registry_principal - requiredScopes: unrestricted + requiredScopes: [proposals:write] permissions: actions: - action: correction @@ -63,7 +63,7 @@ accessProfiles: proposals: - action: correction operations: [get, edit, submit, apply] - ownership: caller + party: owner readableInputs: [asset, label] targets: - recordType: asset diff --git a/crates/registry-breg/tests/fixtures/automatic-application/journeys.yaml b/crates/registry-breg/tests/fixtures/automatic-application/journeys.yaml new file mode 100644 index 0000000000..6a820dd42d --- /dev/null +++ b/crates/registry-breg/tests/fixtures/automatic-application/journeys.yaml @@ -0,0 +1,35 @@ +# yaml-language-server: $schema=https://id.registrystack.org/schemas/breg/journeys/journeys.v1.schema.json +apiVersion: id.registrystack.org/formats/breg/journeys/v1 +kind: BRegJourneys +journeys: + - id: applied + steps: + - id: start-note + action: file-note + accessProfile: clerk + claims: {principal: synthetic-clerk, scopes: ['notes:file'], purpose: note-handling} + request: {type: proposal, transition: start, input: {body: Filed note}} + expect: {outcome: success, status: 201, fields: {state: draft}} + capture: draft + - id: submit-note + action: file-note + accessProfile: clerk + claims: {principal: synthetic-clerk, scopes: ['notes:file'], purpose: note-handling} + request: {type: proposal, transition: submit, proposalCapture: draft, idempotencyKey: submit-note} + expect: {outcome: success, status: 200, fields: {state: submitted}} + - id: await-application + action: file-note + accessProfile: clerk + claims: {principal: synthetic-clerk, scopes: ['notes:file'], purpose: note-handling} + request: {type: proposal, transition: get, proposalCapture: draft, waitSeconds: 10} + expect: + outcome: success + status: 200 + fields: {state: applied, applicationStatus: {mode: automatic, state: applied}} + captureResults: {filed: filed-note} + - id: read-note + recordType: note + accessProfile: clerk + claims: {principal: synthetic-clerk, scopes: ['notes:file'], purpose: note-handling} + request: {type: get, recordCapture: filed-note} + expect: {outcome: success, status: 200, fields: {body: Filed note}} diff --git a/crates/registry-breg/tests/fixtures/automatic-application/never-applied.yaml b/crates/registry-breg/tests/fixtures/automatic-application/never-applied.yaml new file mode 100644 index 0000000000..a4033ea1c9 --- /dev/null +++ b/crates/registry-breg/tests/fixtures/automatic-application/never-applied.yaml @@ -0,0 +1,25 @@ +# yaml-language-server: $schema=https://id.registrystack.org/schemas/breg/journeys/journeys.v1.schema.json +apiVersion: id.registrystack.org/formats/breg/journeys/v1 +kind: BRegJourneys +journeys: + - id: held + steps: + - id: start-note + action: hold-note + accessProfile: clerk + claims: {principal: synthetic-clerk, scopes: ['notes:file'], purpose: note-handling} + request: {type: proposal, transition: start, input: {body: Held note}} + expect: {outcome: success, status: 201, fields: {state: draft}} + capture: draft + - id: submit-note + action: hold-note + accessProfile: clerk + claims: {principal: synthetic-clerk, scopes: ['notes:file'], purpose: note-handling} + request: {type: proposal, transition: submit, proposalCapture: draft, idempotencyKey: submit-note} + expect: {outcome: success, status: 200, fields: {state: submitted}} + - id: await-application + action: hold-note + accessProfile: clerk + claims: {principal: synthetic-clerk, scopes: ['notes:file'], purpose: note-handling} + request: {type: proposal, transition: get, proposalCapture: draft, waitSeconds: 1} + expect: {outcome: success, status: 200, fields: {state: applied}} diff --git a/crates/registry-breg/tests/fixtures/automatic-application/project.yaml b/crates/registry-breg/tests/fixtures/automatic-application/project.yaml new file mode 100644 index 0000000000..ba3fd0f3ec --- /dev/null +++ b/crates/registry-breg/tests/fixtures/automatic-application/project.yaml @@ -0,0 +1,54 @@ +# Synthetic project for journeys that wait for automatic Proposal application. +apiVersion: id.registrystack.org/formats/breg/project/v1alpha1 +kind: BRegProject +project: {id: journey-automatic-application, version: '1', defaultLanguage: en, canonicalBaseIri: 'https://journey-automatic-application.example.test'} +package: {sourceRevision: fixture-project-source} +datasets: {notes: {}} +recordTypes: + note: + route: notes + primaryDataset: notes + mutationMode: mutable + classification: internal + fields: + - {id: body, type: string, maximumLength: 64, required: true, classification: internal} +actions: + file-note: + execution: + mode: proposal + proposal: + review: {type: none} + retention: {mode: retain} + inputs: + - {id: body, type: string, maximumLength: 64, required: true, classification: internal} + plan: + type: fixed + effects: + - {id: filed, target: {recordType: note}, operation: create, set: {body: {fromInput: body}}} + hold-note: + execution: + mode: proposal + proposal: + review: {type: none} + application: {mode: manual} + retention: {mode: retain} + inputs: + - {id: body, type: string, maximumLength: 64, required: true, classification: internal} + plan: + type: fixed + effects: + - {id: note, target: {recordType: note}, operation: create, set: {body: {fromInput: body}}} +accessProfiles: + clerk: + principalClaim: registry_principal + requiredPurposes: [note-handling] + requiredScopes: ['notes:file'] + permissions: + records: + - {recordType: note, operations: [get], readableFields: [body], rowBoundaries: unrestricted} + actions: + - {action: file-note, operations: [start], targets: [{recordType: note, rowBoundaries: unrestricted}]} + - {action: hold-note, operations: [start], targets: [{recordType: note, rowBoundaries: unrestricted}]} + proposals: + - {action: file-note, party: owner, operations: [get, list, submit], readableInputs: [body], targets: [{recordType: note, rowBoundaries: unrestricted}]} + - {action: hold-note, party: owner, operations: [get, list, submit], readableInputs: [body], targets: [{recordType: note, rowBoundaries: unrestricted}]} diff --git a/crates/registry-breg/tests/fixtures/event-record/shapes.yaml b/crates/registry-breg/tests/fixtures/event-record/shapes.yaml index 3a79eaba91..05fd27f1f2 100644 --- a/crates/registry-breg/tests/fixtures/event-record/shapes.yaml +++ b/crates/registry-breg/tests/fixtures/event-record/shapes.yaml @@ -196,7 +196,7 @@ accessProfiles: registrar: default: true principalClaim: registry_principal - requiredScopes: unrestricted + requiredScopes: [records:write] permissions: actions: - action: record-grant-pause @@ -216,5 +216,5 @@ accessProfiles: - action: correct-grant-number operations: [get, list, edit, submit, revise, rebase, retry, cancel, apply] readableInputs: [grant-ref, value] - ownership: caller + party: owner targets: [{recordType: grant, rowBoundaries: unrestricted}] diff --git a/crates/registry-breg/tests/fixtures/fixed-optional-action-input.yaml b/crates/registry-breg/tests/fixtures/fixed-optional-action-input.yaml index f8233e7a78..15cba4f6bb 100644 --- a/crates/registry-breg/tests/fixtures/fixed-optional-action-input.yaml +++ b/crates/registry-breg/tests/fixtures/fixed-optional-action-input.yaml @@ -25,7 +25,7 @@ accessProfiles: registrar: default: true principalClaim: registry_principal - requiredScopes: unrestricted + requiredScopes: [records:write] permissions: actions: - action: create-entry diff --git a/crates/registry-breg/tests/fixtures/fixture-tooling/journeys.yaml b/crates/registry-breg/tests/fixtures/fixture-tooling/journeys.yaml index 9e5302129b..918a59864a 100644 --- a/crates/registry-breg/tests/fixtures/fixture-tooling/journeys.yaml +++ b/crates/registry-breg/tests/fixtures/fixture-tooling/journeys.yaml @@ -8,6 +8,7 @@ journeys: accessProfile: operator claims: principal: fixture-operator + scopes: [fixture:write] purpose: case-management directClaims: {jurisdiction: zone-a} request: @@ -23,6 +24,7 @@ journeys: accessProfile: operator claims: principal: fixture-operator + scopes: [fixture:write] purpose: case-management directClaims: {jurisdiction: zone-a} request: {type: get, recordCapture: first-widget} @@ -35,6 +37,7 @@ journeys: accessProfile: operator claims: principal: fixture-operator + scopes: [fixture:write] purpose: case-management directClaims: {jurisdiction: zone-a} request: {type: list} @@ -50,6 +53,7 @@ journeys: accessProfile: operator claims: principal: fixture-operator + scopes: [fixture:write] purpose: case-management directClaims: {jurisdiction: zone-a} request: @@ -68,6 +72,7 @@ journeys: accessProfile: operator claims: principal: fixture-operator + scopes: [fixture:write] purpose: case-management directClaims: {jurisdiction: zone-a} request: @@ -81,6 +86,7 @@ journeys: accessProfile: operator claims: principal: fixture-operator + scopes: [fixture:write] directClaims: {jurisdiction: zone-a} request: {type: get, recordCapture: revised-widget} expect: diff --git a/crates/registry-breg/tests/fixtures/fixture-tooling/project.yaml b/crates/registry-breg/tests/fixtures/fixture-tooling/project.yaml index 41ca3ca45f..f24f127afe 100644 --- a/crates/registry-breg/tests/fixtures/fixture-tooling/project.yaml +++ b/crates/registry-breg/tests/fixtures/fixture-tooling/project.yaml @@ -52,7 +52,7 @@ accessProfiles: operator: default: true principalClaim: registry_principal - requiredScopes: unrestricted + requiredScopes: [fixture:write] requiredPurposes: [case-management] permissions: records: diff --git a/crates/registry-breg/tests/fixtures/fixture-tooling/terminal-failure.yaml b/crates/registry-breg/tests/fixtures/fixture-tooling/terminal-failure.yaml index e3c1de6a7b..07dee6db7a 100644 --- a/crates/registry-breg/tests/fixtures/fixture-tooling/terminal-failure.yaml +++ b/crates/registry-breg/tests/fixtures/fixture-tooling/terminal-failure.yaml @@ -8,6 +8,7 @@ journeys: accessProfile: operator claims: principal: fixture-operator + scopes: [fixture:write] purpose: case-management directClaims: {jurisdiction: zone-a} request: @@ -22,6 +23,7 @@ journeys: accessProfile: operator claims: principal: fixture-operator + scopes: [fixture:write] purpose: case-management directClaims: {jurisdiction: zone-a} request: diff --git a/crates/registry-breg/tests/fixtures/message-journeys/journeys.yaml b/crates/registry-breg/tests/fixtures/message-journeys/journeys.yaml new file mode 100644 index 0000000000..81654a91ac --- /dev/null +++ b/crates/registry-breg/tests/fixtures/message-journeys/journeys.yaml @@ -0,0 +1,52 @@ +# yaml-language-server: $schema=https://id.registrystack.org/schemas/breg/journeys/journeys.v1.schema.json +apiVersion: id.registrystack.org/formats/breg/journeys/v1 +kind: BRegJourneys +journeys: + - id: thread + steps: + - id: start-note + actor: applicant + action: file-note + accessProfile: applicant + claims: {principal: synthetic-applicant, scopes: ['notes:file'], purpose: note-handling, actorKind: human} + request: {type: proposal, transition: start, input: {body: First note}} + expect: {outcome: success, status: 201, fields: {state: draft}} + capture: draft + - id: submit-note + actor: applicant + action: file-note + accessProfile: applicant + claims: {principal: synthetic-applicant, scopes: ['notes:file'], purpose: note-handling, actorKind: human} + request: {type: proposal, transition: submit, proposalCapture: draft} + expect: {outcome: success, status: 200, fields: {state: submitted, turn: official}} + capture: submitted + - id: office-view + actor: office + action: file-note + accessProfile: office + claims: {principal: synthetic-officer, scopes: ['notes:office'], purpose: note-handling, actorKind: human} + request: {type: proposal, transition: get, proposalCapture: submitted} + expect: {outcome: success, status: 200} + capture: office-view + - id: office-writes + actor: office + action: file-note + accessProfile: office + claims: {principal: synthetic-officer, scopes: ['notes:office'], purpose: note-handling, actorKind: human} + request: {type: proposal, transition: message, proposalCapture: office-view, text: Please add the full address.} + expect: {outcome: success, status: 200} + - id: applicant-view + actor: applicant + action: file-note + accessProfile: applicant + claims: {principal: synthetic-applicant, scopes: ['notes:file'], purpose: note-handling, actorKind: human} + request: {type: proposal, transition: get, proposalCapture: submitted} + expect: {outcome: success, status: 200, fields: {status: processing, turn: party}} + capture: applicant-view + - id: applicant-reads + actor: applicant + action: file-note + accessProfile: applicant + claims: {principal: synthetic-applicant, scopes: ['notes:file'], purpose: note-handling, actorKind: human} + request: {type: proposal, transition: read-messages, proposalCapture: applicant-view} + expect: {outcome: success, status: 200, fields: {status: processing, turn: official}} diff --git a/crates/registry-breg/tests/fixtures/message-journeys/project.yaml b/crates/registry-breg/tests/fixtures/message-journeys/project.yaml new file mode 100644 index 0000000000..71cc548c80 --- /dev/null +++ b/crates/registry-breg/tests/fixtures/message-journeys/project.yaml @@ -0,0 +1,50 @@ +# Synthetic project for the Proposal message thread journey operations. +apiVersion: id.registrystack.org/formats/breg/project/v1alpha1 +kind: BRegProject +project: {id: journey-messages, version: '1', defaultLanguage: en, canonicalBaseIri: 'https://journey-messages.example.test'} +package: {sourceRevision: fixture-project-source} +datasets: {notes: {}} +recordTypes: + note: + route: notes + primaryDataset: notes + mutationMode: mutable + classification: internal + fields: + - {id: body, type: string, maximumLength: 64, required: true, classification: internal} +actions: + file-note: + execution: + mode: proposal + proposal: + review: {type: none} + application: {mode: manual} + retention: {mode: retain} + messages: {maximumCount: 10} + inputs: + - {id: body, type: string, maximumLength: 64, required: true, classification: internal} + plan: + type: fixed + effects: + - {id: note, target: {recordType: note}, operation: create, set: {body: {fromInput: body}}} +accessProfiles: + applicant: + actorKind: human + principalClaim: registry_principal + requiredPurposes: [note-handling] + requiredScopes: ['notes:file'] + permissions: + actions: + - {action: file-note, operations: [start], targets: [{recordType: note, rowBoundaries: unrestricted}]} + proposals: + - {action: file-note, party: owner, operations: [get, list, edit, submit, cancel, message], readableInputs: [body], targets: [{recordType: note, rowBoundaries: unrestricted}]} + office: + actorKind: human + principalClaim: registry_principal + requiredPurposes: [note-handling] + requiredScopes: ['notes:office'] + permissions: + records: + - {recordType: note, operations: [create, get], readableFields: [body], writableFields: [body], rowBoundaries: unrestricted} + proposals: + - {action: file-note, operations: [get, list, apply, message], readableInputs: [body], targets: [{recordType: note, rowBoundaries: unrestricted}]} diff --git a/crates/registry-breg/tests/fixtures/v0.51.0-reference-predecessor/package/SHA256SUMS b/crates/registry-breg/tests/fixtures/v0.51.0-reference-predecessor/package/SHA256SUMS new file mode 100644 index 0000000000..8048190472 --- /dev/null +++ b/crates/registry-breg/tests/fixtures/v0.51.0-reference-predecessor/package/SHA256SUMS @@ -0,0 +1,15 @@ +231f9b5bf3fce34d03b94f4c7469d04e634864a57f85f2b22ff41ff111fe98c2 database/ddl.sql +1872670a4b4f6a2761877597f1e677715451ec449afc9159356f5c0e744de198 database/migration-plan.json +dcdf1f9af83cef41567f887808163c04a85e1bc76e2622433ef4d1c31802efeb effective-model.json +9e9e0afc5fbbb8b65552729c9e74e0cfd37087b0ebb26f82a5f434dbfa0fc9a9 inventories/access.json +7263162aa981e58eb0b8fd4ba058a1b17ff622c1e8784820b8ec1f407e9bd384 inventories/events.json +0c555a61a985021bdcdedfdef81156079962659de269c782263af19e8279f334 inventories/physical-names.json +ede4e9f3f991500b3e38fa652047cbdf3eabcc5168373f65acb8f1770c1c262b inventories/queries.json +e17e0adccd7e52b3d6579afc74483f5159cd320ddbc0c484c70dacf34239c5a2 inventories/routes.json +64ddb25ba9ea8800af3b108765b900ac54369b60da6158269c6529b76bce2ca3 metadata/registry.json +41eef0f04f9ba4606aba7dcb71036be68a5e1773a341a3dd5623814703084de5 openapi/openapi.json +72eaea44c13c0d8dbcbf28a5afcc955411fc12d8aa1a3c8abf99d8a466950eae package.json +a6542b2f94ec89880a609577351ca881466e06874cef4a985c8e17e1f6ac6b76 schemas/category.schema.json +cbdf09590e36cff2afecc0e3d536ed33779a4657ba624ec44d37ecae3c1a8619 schemas/entry.schema.json +e9e13030735f24824b4eb2be56c394692afc91956090aceb2e655f69c84d0eb8 source/registry.yaml +253493af5c5fd85d65bc3fa645ba4f0b0f56c4b154c7a77525b677e0213d4f5b tests/journeys.yaml diff --git a/crates/registry-breg/tests/fixtures/v0.51.0-reference-predecessor/package/database/ddl.sql b/crates/registry-breg/tests/fixtures/v0.51.0-reference-predecessor/package/database/ddl.sql new file mode 100644 index 0000000000..7aa2de6fed --- /dev/null +++ b/crates/registry-breg/tests/fixtures/v0.51.0-reference-predecessor/package/database/ddl.sql @@ -0,0 +1,44 @@ +CREATE SCHEMA IF NOT EXISTS registry_data; +CREATE SCHEMA IF NOT EXISTS registry_source; +CREATE SCHEMA IF NOT EXISTS registry_derived; +CREATE SCHEMA IF NOT EXISTS registry_context; +CREATE OR REPLACE FUNCTION registry_context.evaluation_date() + RETURNS date + LANGUAGE sql + STABLE + SECURITY INVOKER + AS $breg_function$ + SELECT NULLIF(current_setting('registry.evaluation_date', true), '')::date + $breg_function$; +CREATE TABLE registry_data."breg_e_category_284c16a2a34063e5" (record_id uuid NOT NULL, record_revision bigint NOT NULL DEFAULT 1 CHECK (record_revision > 0), record_lifecycle text COLLATE pg_catalog.pg_c_utf8 NOT NULL DEFAULT 'active' CHECK (record_lifecycle IN ('active', 'tombstoned')), created_at timestamptz NOT NULL DEFAULT transaction_timestamp(), updated_at timestamptz NOT NULL DEFAULT transaction_timestamp(), active_package_revision text COLLATE pg_catalog.pg_c_utf8 NOT NULL DEFAULT NULLIF(current_setting('registry.active_package_revision', true), '') CHECK (active_package_revision <> ''), PRIMARY KEY (record_id), "breg_f_category_name_b74daabde89a5552" varchar(64) COLLATE pg_catalog.pg_c_utf8); +CREATE TABLE registry_data."breg_e_entry_c691cfb82ab6e25e" (record_id uuid NOT NULL, record_revision bigint NOT NULL DEFAULT 1 CHECK (record_revision > 0), record_lifecycle text COLLATE pg_catalog.pg_c_utf8 NOT NULL DEFAULT 'active' CHECK (record_lifecycle IN ('active', 'tombstoned')), created_at timestamptz NOT NULL DEFAULT transaction_timestamp(), updated_at timestamptz NOT NULL DEFAULT transaction_timestamp(), active_package_revision text COLLATE pg_catalog.pg_c_utf8 NOT NULL DEFAULT NULLIF(current_setting('registry.active_package_revision', true), '') CHECK (active_package_revision <> ''), PRIMARY KEY (record_id), "breg_f_entry_category_0a2a03f0519a4bb7" uuid, "breg_f_entry_name_b223a4d2b68b84ee" varchar(64) COLLATE pg_catalog.pg_c_utf8); +ALTER TABLE registry_data."breg_e_category_284c16a2a34063e5" ADD CONSTRAINT "breg_rk_category_e09350e5c007cb8e" UNIQUE (record_id, record_lifecycle); +ALTER TABLE registry_data."breg_e_entry_c691cfb82ab6e25e" ADD COLUMN record_reference_lifecycle text COLLATE pg_catalog.pg_c_utf8 + GENERATED ALWAYS AS (CASE WHEN record_lifecycle = 'active' THEN 'active'::text ELSE NULL::text END) STORED; +ALTER TABLE registry_data."breg_e_entry_c691cfb82ab6e25e" ADD CONSTRAINT "breg_r_entry_category_5aba7f6cb64640e7" FOREIGN KEY ("breg_f_entry_category_0a2a03f0519a4bb7") REFERENCES registry_data."breg_e_category_284c16a2a34063e5" (record_id) ON DELETE RESTRICT; +ALTER TABLE registry_data."breg_e_entry_c691cfb82ab6e25e" NO FORCE ROW LEVEL SECURITY; +ALTER TABLE registry_data."breg_e_category_284c16a2a34063e5" NO FORCE ROW LEVEL SECURITY; +ALTER TABLE registry_data."breg_e_entry_c691cfb82ab6e25e" ADD CONSTRAINT "breg_ar_entry_category_7b190379404e320b" FOREIGN KEY ("breg_f_entry_category_0a2a03f0519a4bb7", record_reference_lifecycle) REFERENCES registry_data."breg_e_category_284c16a2a34063e5" (record_id, record_lifecycle) MATCH SIMPLE ON UPDATE NO ACTION ON DELETE RESTRICT; +ALTER TABLE registry_data."breg_e_entry_c691cfb82ab6e25e" FORCE ROW LEVEL SECURITY; +ALTER TABLE registry_data."breg_e_category_284c16a2a34063e5" FORCE ROW LEVEL SECURITY; +CREATE INDEX "breg_ri_entry_category_ff9998a3c15186b6" ON registry_data."breg_e_entry_c691cfb82ab6e25e" ("breg_f_entry_category_0a2a03f0519a4bb7"); +ALTER TABLE registry_data."breg_e_category_284c16a2a34063e5" ENABLE ROW LEVEL SECURITY; +ALTER TABLE registry_data."breg_e_category_284c16a2a34063e5" FORCE ROW LEVEL SECURITY; +ALTER TABLE registry_data."breg_e_entry_c691cfb82ab6e25e" ENABLE ROW LEVEL SECURITY; +ALTER TABLE registry_data."breg_e_entry_c691cfb82ab6e25e" FORCE ROW LEVEL SECURITY; +CREATE POLICY "registry_rls_insert_c20605ed93691b2b174e27bc" ON registry_data."breg_e_entry_c691cfb82ab6e25e" FOR INSERT WITH CHECK ((NULLIF(current_setting('registry.access_profile', true), '') = 'editor' AND NULLIF(current_setting('registry.principal', true), '') IS NOT NULL AND jsonb_typeof(NULLIF(current_setting('registry.row_boundaries', true), '')::jsonb) = 'array' AND jsonb_array_length(NULLIF(current_setting('registry.row_boundaries', true), '')::jsonb) = 0) AND record_lifecycle = 'active'); +COMMENT ON POLICY "registry_rls_insert_c20605ed93691b2b174e27bc" ON registry_data."breg_e_entry_c691cfb82ab6e25e" IS 'breg/policy/v1/aac8da39bc88f49c906e0a58432a7340b49909bce3d0a0caab365c86f4847071'; +CREATE POLICY "registry_create_returning_rls_93972995e60731bc7464c338" ON registry_data."breg_e_entry_c691cfb82ab6e25e" FOR SELECT USING ((NULLIF(current_setting('registry.access_profile', true), '') = 'editor' AND NULLIF(current_setting('registry.principal', true), '') IS NOT NULL AND jsonb_typeof(NULLIF(current_setting('registry.row_boundaries', true), '')::jsonb) = 'array' AND jsonb_array_length(NULLIF(current_setting('registry.row_boundaries', true), '')::jsonb) = 0) AND record_lifecycle = 'active' AND 'entry' = NULLIF(current_setting('registry.created_entity_id', true), '') AND record_id = NULLIF(current_setting('registry.created_record_id', true), '')::uuid); +COMMENT ON POLICY "registry_create_returning_rls_93972995e60731bc7464c338" ON registry_data."breg_e_entry_c691cfb82ab6e25e" IS 'breg/policy/v1/a7736c35bb0a78bc4f0a557b10ee5d4199921da7e15134436d10f2c4c0ea78d3'; +CREATE POLICY "registry_rls_select_a949aa044b11815c56813b65" ON registry_data."breg_e_entry_c691cfb82ab6e25e" FOR SELECT USING ((NULLIF(current_setting('registry.access_profile', true), '') = 'reader' AND NULLIF(current_setting('registry.principal', true), '') IS NOT NULL AND jsonb_typeof(NULLIF(current_setting('registry.row_boundaries', true), '')::jsonb) = 'array' AND jsonb_array_length(NULLIF(current_setting('registry.row_boundaries', true), '')::jsonb) = 0) AND (record_lifecycle = 'active')); +COMMENT ON POLICY "registry_rls_select_a949aa044b11815c56813b65" ON registry_data."breg_e_entry_c691cfb82ab6e25e" IS 'breg/policy/v1/db3a8229a6ca7c86cba13bd0889ac61c2bb486fd1fcb5bc88dfce541bf639627'; +CREATE VIEW registry_source."category" + WITH (security_invoker=true) + AS SELECT record_id AS "id", "breg_f_category_name_b74daabde89a5552" AS "name" + FROM registry_data."breg_e_category_284c16a2a34063e5" + WHERE record_lifecycle = 'active'; +CREATE VIEW registry_source."entry" + WITH (security_invoker=true) + AS SELECT record_id AS "id", "breg_f_entry_name_b223a4d2b68b84ee" AS "name", "breg_f_entry_category_0a2a03f0519a4bb7" AS "category" + FROM registry_data."breg_e_entry_c691cfb82ab6e25e" + WHERE record_lifecycle = 'active'; diff --git a/crates/registry-breg/tests/fixtures/v0.51.0-reference-predecessor/package/database/migration-plan.json b/crates/registry-breg/tests/fixtures/v0.51.0-reference-predecessor/package/database/migration-plan.json new file mode 100644 index 0000000000..42b657adae --- /dev/null +++ b/crates/registry-breg/tests/fixtures/v0.51.0-reference-predecessor/package/database/migration-plan.json @@ -0,0 +1 @@ +{"statements":[{"id":"schema.registry_data","kind":"schema","sql":"CREATE SCHEMA IF NOT EXISTS registry_data"},{"id":"schema.registry_source","kind":"schema","sql":"CREATE SCHEMA IF NOT EXISTS registry_source"},{"id":"schema.registry_derived","kind":"schema","sql":"CREATE SCHEMA IF NOT EXISTS registry_derived"},{"id":"schema.registry_context","kind":"schema","sql":"CREATE SCHEMA IF NOT EXISTS registry_context"},{"id":"function.registry_context.evaluation_date","kind":"function","sql":"CREATE OR REPLACE FUNCTION registry_context.evaluation_date()\n RETURNS date\n LANGUAGE sql\n STABLE\n SECURITY INVOKER\n AS $breg_function$\n SELECT NULLIF(current_setting('registry.evaluation_date', true), '')::date\n $breg_function$"},{"id":"entity.category.table","kind":"table","sql":"CREATE TABLE registry_data.\"breg_e_category_284c16a2a34063e5\" (record_id uuid NOT NULL, record_revision bigint NOT NULL DEFAULT 1 CHECK (record_revision > 0), record_lifecycle text COLLATE pg_catalog.pg_c_utf8 NOT NULL DEFAULT 'active' CHECK (record_lifecycle IN ('active', 'tombstoned')), created_at timestamptz NOT NULL DEFAULT transaction_timestamp(), updated_at timestamptz NOT NULL DEFAULT transaction_timestamp(), active_package_revision text COLLATE pg_catalog.pg_c_utf8 NOT NULL DEFAULT NULLIF(current_setting('registry.active_package_revision', true), '') CHECK (active_package_revision <> ''), PRIMARY KEY (record_id), \"breg_f_category_name_b74daabde89a5552\" varchar(64) COLLATE pg_catalog.pg_c_utf8)"},{"id":"entity.entry.table","kind":"table","sql":"CREATE TABLE registry_data.\"breg_e_entry_c691cfb82ab6e25e\" (record_id uuid NOT NULL, record_revision bigint NOT NULL DEFAULT 1 CHECK (record_revision > 0), record_lifecycle text COLLATE pg_catalog.pg_c_utf8 NOT NULL DEFAULT 'active' CHECK (record_lifecycle IN ('active', 'tombstoned')), created_at timestamptz NOT NULL DEFAULT transaction_timestamp(), updated_at timestamptz NOT NULL DEFAULT transaction_timestamp(), active_package_revision text COLLATE pg_catalog.pg_c_utf8 NOT NULL DEFAULT NULLIF(current_setting('registry.active_package_revision', true), '') CHECK (active_package_revision <> ''), PRIMARY KEY (record_id), \"breg_f_entry_category_0a2a03f0519a4bb7\" uuid, \"breg_f_entry_name_b223a4d2b68b84ee\" varchar(64) COLLATE pg_catalog.pg_c_utf8)"},{"id":"entity.category.reference-lifecycle.key","kind":"constraint","sql":"ALTER TABLE registry_data.\"breg_e_category_284c16a2a34063e5\" ADD CONSTRAINT \"breg_rk_category_e09350e5c007cb8e\" UNIQUE (record_id, record_lifecycle)"},{"id":"entity.entry.reference-lifecycle.column","kind":"column","sql":"ALTER TABLE registry_data.\"breg_e_entry_c691cfb82ab6e25e\" ADD COLUMN record_reference_lifecycle text COLLATE pg_catalog.pg_c_utf8\n GENERATED ALWAYS AS (CASE WHEN record_lifecycle = 'active' THEN 'active'::text ELSE NULL::text END) STORED"},{"id":"entity.entry.field.category.reference","kind":"reference","sql":"ALTER TABLE registry_data.\"breg_e_entry_c691cfb82ab6e25e\" ADD CONSTRAINT \"breg_r_entry_category_5aba7f6cb64640e7\" FOREIGN KEY (\"breg_f_entry_category_0a2a03f0519a4bb7\") REFERENCES registry_data.\"breg_e_category_284c16a2a34063e5\" (record_id) ON DELETE RESTRICT"},{"id":"entity.entry.field.category.active-reference","kind":"reference","sql":"ALTER TABLE registry_data.\"breg_e_entry_c691cfb82ab6e25e\" NO FORCE ROW LEVEL SECURITY;\nALTER TABLE registry_data.\"breg_e_category_284c16a2a34063e5\" NO FORCE ROW LEVEL SECURITY;\nALTER TABLE registry_data.\"breg_e_entry_c691cfb82ab6e25e\" ADD CONSTRAINT \"breg_ar_entry_category_7b190379404e320b\" FOREIGN KEY (\"breg_f_entry_category_0a2a03f0519a4bb7\", record_reference_lifecycle) REFERENCES registry_data.\"breg_e_category_284c16a2a34063e5\" (record_id, record_lifecycle) MATCH SIMPLE ON UPDATE NO ACTION ON DELETE RESTRICT;\nALTER TABLE registry_data.\"breg_e_entry_c691cfb82ab6e25e\" FORCE ROW LEVEL SECURITY;\nALTER TABLE registry_data.\"breg_e_category_284c16a2a34063e5\" FORCE ROW LEVEL SECURITY"},{"id":"entity.entry.index.reference:category","kind":"index","sql":"CREATE INDEX \"breg_ri_entry_category_ff9998a3c15186b6\" ON registry_data.\"breg_e_entry_c691cfb82ab6e25e\" (\"breg_f_entry_category_0a2a03f0519a4bb7\")"},{"id":"entity.category.rls.enable","kind":"row_security","sql":"ALTER TABLE registry_data.\"breg_e_category_284c16a2a34063e5\" ENABLE ROW LEVEL SECURITY"},{"id":"entity.category.rls.force","kind":"row_security","sql":"ALTER TABLE registry_data.\"breg_e_category_284c16a2a34063e5\" FORCE ROW LEVEL SECURITY"},{"id":"entity.entry.rls.enable","kind":"row_security","sql":"ALTER TABLE registry_data.\"breg_e_entry_c691cfb82ab6e25e\" ENABLE ROW LEVEL SECURITY"},{"id":"entity.entry.rls.force","kind":"row_security","sql":"ALTER TABLE registry_data.\"breg_e_entry_c691cfb82ab6e25e\" FORCE ROW LEVEL SECURITY"},{"id":"entity.entry.policy.registry_rls_insert_c20605ed93691b2b174e27bc","kind":"policy","sql":"CREATE POLICY \"registry_rls_insert_c20605ed93691b2b174e27bc\" ON registry_data.\"breg_e_entry_c691cfb82ab6e25e\" FOR INSERT WITH CHECK ((NULLIF(current_setting('registry.access_profile', true), '') = 'editor' AND NULLIF(current_setting('registry.principal', true), '') IS NOT NULL AND jsonb_typeof(NULLIF(current_setting('registry.row_boundaries', true), '')::jsonb) = 'array' AND jsonb_array_length(NULLIF(current_setting('registry.row_boundaries', true), '')::jsonb) = 0) AND record_lifecycle = 'active');\nCOMMENT ON POLICY \"registry_rls_insert_c20605ed93691b2b174e27bc\" ON registry_data.\"breg_e_entry_c691cfb82ab6e25e\" IS 'breg/policy/v1/aac8da39bc88f49c906e0a58432a7340b49909bce3d0a0caab365c86f4847071'"},{"id":"entity.entry.policy.registry_create_returning_rls_93972995e60731bc7464c338","kind":"policy","sql":"CREATE POLICY \"registry_create_returning_rls_93972995e60731bc7464c338\" ON registry_data.\"breg_e_entry_c691cfb82ab6e25e\" FOR SELECT USING ((NULLIF(current_setting('registry.access_profile', true), '') = 'editor' AND NULLIF(current_setting('registry.principal', true), '') IS NOT NULL AND jsonb_typeof(NULLIF(current_setting('registry.row_boundaries', true), '')::jsonb) = 'array' AND jsonb_array_length(NULLIF(current_setting('registry.row_boundaries', true), '')::jsonb) = 0) AND record_lifecycle = 'active' AND 'entry' = NULLIF(current_setting('registry.created_entity_id', true), '') AND record_id = NULLIF(current_setting('registry.created_record_id', true), '')::uuid);\nCOMMENT ON POLICY \"registry_create_returning_rls_93972995e60731bc7464c338\" ON registry_data.\"breg_e_entry_c691cfb82ab6e25e\" IS 'breg/policy/v1/a7736c35bb0a78bc4f0a557b10ee5d4199921da7e15134436d10f2c4c0ea78d3'"},{"id":"entity.entry.policy.registry_rls_select_a949aa044b11815c56813b65","kind":"policy","sql":"CREATE POLICY \"registry_rls_select_a949aa044b11815c56813b65\" ON registry_data.\"breg_e_entry_c691cfb82ab6e25e\" FOR SELECT USING ((NULLIF(current_setting('registry.access_profile', true), '') = 'reader' AND NULLIF(current_setting('registry.principal', true), '') IS NOT NULL AND jsonb_typeof(NULLIF(current_setting('registry.row_boundaries', true), '')::jsonb) = 'array' AND jsonb_array_length(NULLIF(current_setting('registry.row_boundaries', true), '')::jsonb) = 0) AND (record_lifecycle = 'active'));\nCOMMENT ON POLICY \"registry_rls_select_a949aa044b11815c56813b65\" ON registry_data.\"breg_e_entry_c691cfb82ab6e25e\" IS 'breg/policy/v1/db3a8229a6ca7c86cba13bd0889ac61c2bb486fd1fcb5bc88dfce541bf639627'"},{"id":"entity.category.source-view","kind":"view","sql":"CREATE VIEW registry_source.\"category\"\n WITH (security_invoker=true)\n AS SELECT record_id AS \"id\", \"breg_f_category_name_b74daabde89a5552\" AS \"name\"\n FROM registry_data.\"breg_e_category_284c16a2a34063e5\"\n WHERE record_lifecycle = 'active'"},{"id":"entity.entry.source-view","kind":"view","sql":"CREATE VIEW registry_source.\"entry\"\n WITH (security_invoker=true)\n AS SELECT record_id AS \"id\", \"breg_f_entry_name_b223a4d2b68b84ee\" AS \"name\", \"breg_f_entry_category_0a2a03f0519a4bb7\" AS \"category\"\n FROM registry_data.\"breg_e_entry_c691cfb82ab6e25e\"\n WHERE record_lifecycle = 'active'"}]} \ No newline at end of file diff --git a/crates/registry-breg/tests/fixtures/v0.51.0-reference-predecessor/package/effective-model.json b/crates/registry-breg/tests/fixtures/v0.51.0-reference-predecessor/package/effective-model.json new file mode 100644 index 0000000000..2a86fc7810 --- /dev/null +++ b/crates/registry-breg/tests/fixtures/v0.51.0-reference-predecessor/package/effective-model.json @@ -0,0 +1 @@ +{"accessProfiles":[{"display":{},"id":"editor"},{"display":{},"id":"reader"}],"datasets":[{"display":{},"id":"records"}],"defaultLanguage":"en","eventDeliveryInventory":{"deliveries":[]},"metadataInventory":{"recordTypes":[{"entries":[{"accessProfile":"editor","operation":"create","readableFields":[],"responseRecordType":"entry","routeId":"records.entry.create"},{"accessProfile":"reader","operation":"list","readableFields":["name"],"responseRecordType":"entry","routeId":"records.entry.list"}],"id":"entry","route":"entries","schemaPath":"/v1/schemas/entry"}],"registryId":"reference-rehearsal","version":"1"},"moduleClosure":[],"moduleOrder":[],"physicalNames":{"entities":{"category":{"constraints":{"active-reference-key:record-lifecycle":"breg_rk_category_e09350e5c007cb8e"},"fields":{"name":"breg_f_category_name_b74daabde89a5552"},"indexes":{},"policies":{},"table":"breg_e_category_284c16a2a34063e5"},"entry":{"constraints":{"active-reference:category":"breg_ar_entry_category_7b190379404e320b","reference:category":"breg_r_entry_category_5aba7f6cb64640e7"},"fields":{"category":"breg_f_entry_category_0a2a03f0519a4bb7","name":"breg_f_entry_name_b223a4d2b68b84ee"},"indexes":{"reference:category":"breg_ri_entry_category_ff9998a3c15186b6"},"policies":{"editor":"breg_p_entry_editor_5d13998f2140ec0a","reader":"breg_p_entry_reader_9153097a6905bab0"},"table":"breg_e_entry_c691cfb82ab6e25e"}}},"queryInventory":{"operations":[{"allowCount":false,"filterFields":[],"id":"records.entry.reader.list","kind":"list","maxPageSize":100,"processingFields":["name"],"profileId":"reader","projectionFields":["name"],"recordType":"entry","routeId":"records.entry.list","sortFields":[],"stableTieBreaker":"record_id"}]},"recordTypes":{"category":{"accessProfiles":{},"apiName":"Category","canonicalId":{"apiName":"id","classification":"internal","fieldType":{"type":"uuid"},"id":"id","sqlName":"id"},"classification":"internal","constraints":{},"definitionRevision":"sha256:971b32921711e92e732d820de6b8c350b4a156ab221e03cda35dacf416c2233b","derivedFields":{},"derivedRelations":{},"display":{},"fields":{"name":{"classification":"internal","display":{},"fieldType":{"maximumLength":64,"minimumLength":0,"type":"string"},"id":"name","physicalName":"breg_f_category_name_b74daabde89a5552","relationship":null,"required":false}},"hooks":{},"id":"category","indexes":{},"lookups":{},"mutationMode":"create-only","physicalTable":"breg_e_category_284c16a2a34063e5","primaryDataset":"records","readPaths":{},"route":"categories","sourceRelation":{"recordType":"category","sqlName":"category","storedFields":["name"]},"storedFields":[{"apiName":"name","classification":"internal","fieldType":{"maximumLength":64,"minimumLength":0,"type":"string"},"id":"name","physicalName":"breg_f_category_name_b74daabde89a5552","required":false,"sqlName":"name"}],"tombstone":false},"entry":{"accessProfiles":{"editor":{"allowDataExport":false,"default":false,"filterableFields":[],"id":"editor","operations":["create"],"principalClaim":"principal","readableFields":[],"requiredPurposes":[],"requiredScopes":["records:write"],"revisionAccess":false,"rowBoundaries":[],"sortableFields":[],"writableFields":["category","name"]},"reader":{"allowDataExport":false,"default":false,"filterableFields":[],"id":"reader","operations":["list"],"principalClaim":"principal","readableFields":["name"],"requiredPurposes":[],"requiredScopes":["records:read"],"revisionAccess":false,"rowBoundaries":[],"sortableFields":[],"writableFields":[]}},"apiName":"Entry","canonicalId":{"apiName":"id","classification":"internal","fieldType":{"type":"uuid"},"id":"id","sqlName":"id"},"classification":"internal","constraints":{},"definitionRevision":"sha256:782116b67d9710b99d2c120618f7cde3cf9320c8c605a62ab2812c0c92d0b2d1","derivedFields":{},"derivedRelations":{},"display":{},"fields":{"category":{"classification":"internal","display":{},"fieldType":{"onDelete":"restrict","target":"category","type":"reference"},"id":"category","physicalName":"breg_f_entry_category_0a2a03f0519a4bb7","relationship":null,"required":false},"name":{"classification":"internal","display":{},"fieldType":{"maximumLength":64,"minimumLength":0,"type":"string"},"id":"name","physicalName":"breg_f_entry_name_b223a4d2b68b84ee","relationship":null,"required":false}},"hooks":{},"id":"entry","indexes":{"reference:category":["category"]},"lookups":{},"mutationMode":"create-only","physicalTable":"breg_e_entry_c691cfb82ab6e25e","primaryDataset":"records","readPaths":{},"relationships":{"category":{"cardinality":"optional-one","fieldId":"category","inverse":false,"inverseName":null,"name":"category","readPath":null,"sourceRecordType":"entry","targetRecordType":"category"}},"route":"entries","sourceRelation":{"recordType":"entry","sqlName":"entry","storedFields":["name","category"]},"storedFields":[{"apiName":"name","classification":"internal","fieldType":{"maximumLength":64,"minimumLength":0,"type":"string"},"id":"name","physicalName":"breg_f_entry_name_b223a4d2b68b84ee","required":false,"sqlName":"name"},{"apiName":"category","classification":"internal","fieldType":{"onDelete":"restrict","target":"category","type":"reference"},"id":"category","physicalName":"breg_f_entry_category_0a2a03f0519a4bb7","required":false,"sqlName":"category"}],"tombstone":false}},"registryId":"reference-rehearsal","version":"1"} \ No newline at end of file diff --git a/crates/registry-breg/tests/fixtures/v0.51.0-reference-predecessor/package/inventories/access.json b/crates/registry-breg/tests/fixtures/v0.51.0-reference-predecessor/package/inventories/access.json new file mode 100644 index 0000000000..d2393f08a7 --- /dev/null +++ b/crates/registry-breg/tests/fixtures/v0.51.0-reference-predecessor/package/inventories/access.json @@ -0,0 +1 @@ +{"entries":[{"defaultProfileId":"editor","operation":"create","profileIds":["editor"],"recordType":"entry","routeId":"records.entry.create"},{"defaultProfileId":"reader","operation":"list","profileIds":["reader"],"recordType":"entry","routeId":"records.entry.list"}]} \ No newline at end of file diff --git a/crates/registry-breg/tests/fixtures/v0.51.0-reference-predecessor/package/inventories/events.json b/crates/registry-breg/tests/fixtures/v0.51.0-reference-predecessor/package/inventories/events.json new file mode 100644 index 0000000000..f2eb5d89c8 --- /dev/null +++ b/crates/registry-breg/tests/fixtures/v0.51.0-reference-predecessor/package/inventories/events.json @@ -0,0 +1 @@ +{"deliveries":[]} \ No newline at end of file diff --git a/crates/registry-breg/tests/fixtures/v0.51.0-reference-predecessor/package/inventories/physical-names.json b/crates/registry-breg/tests/fixtures/v0.51.0-reference-predecessor/package/inventories/physical-names.json new file mode 100644 index 0000000000..bc88f8e8f5 --- /dev/null +++ b/crates/registry-breg/tests/fixtures/v0.51.0-reference-predecessor/package/inventories/physical-names.json @@ -0,0 +1 @@ +{"entities":{"category":{"constraints":{"active-reference-key:record-lifecycle":"breg_rk_category_e09350e5c007cb8e"},"fields":{"name":"breg_f_category_name_b74daabde89a5552"},"indexes":{},"policies":{},"table":"breg_e_category_284c16a2a34063e5"},"entry":{"constraints":{"active-reference:category":"breg_ar_entry_category_7b190379404e320b","reference:category":"breg_r_entry_category_5aba7f6cb64640e7"},"fields":{"category":"breg_f_entry_category_0a2a03f0519a4bb7","name":"breg_f_entry_name_b223a4d2b68b84ee"},"indexes":{"reference:category":"breg_ri_entry_category_ff9998a3c15186b6"},"policies":{"editor":"breg_p_entry_editor_5d13998f2140ec0a","reader":"breg_p_entry_reader_9153097a6905bab0"},"table":"breg_e_entry_c691cfb82ab6e25e"}}} \ No newline at end of file diff --git a/crates/registry-breg/tests/fixtures/v0.51.0-reference-predecessor/package/inventories/queries.json b/crates/registry-breg/tests/fixtures/v0.51.0-reference-predecessor/package/inventories/queries.json new file mode 100644 index 0000000000..57a8c61f31 --- /dev/null +++ b/crates/registry-breg/tests/fixtures/v0.51.0-reference-predecessor/package/inventories/queries.json @@ -0,0 +1 @@ +{"operations":[{"allowCount":false,"filterFields":[],"id":"records.entry.reader.list","kind":"list","maxPageSize":100,"processingFields":["name"],"profileId":"reader","projectionFields":["name"],"recordType":"entry","routeId":"records.entry.list","sortFields":[],"stableTieBreaker":"record_id"}]} \ No newline at end of file diff --git a/crates/registry-breg/tests/fixtures/v0.51.0-reference-predecessor/package/inventories/routes.json b/crates/registry-breg/tests/fixtures/v0.51.0-reference-predecessor/package/inventories/routes.json new file mode 100644 index 0000000000..6b02f5d87f --- /dev/null +++ b/crates/registry-breg/tests/fixtures/v0.51.0-reference-predecessor/package/inventories/routes.json @@ -0,0 +1 @@ +{"routes":[{"accessProfiles":["reader"],"defaultAccessProfile":"reader","id":"records.entry.list","method":"GET","operation":"list","path":"/v1/records/entries","queryKind":"list","recordType":"entry"},{"accessProfiles":["editor"],"defaultAccessProfile":"editor","id":"records.entry.create","method":"POST","operation":"create","path":"/v1/records/entries","recordType":"entry"}]} \ No newline at end of file diff --git a/crates/registry-breg/tests/fixtures/v0.51.0-reference-predecessor/package/metadata/registry.json b/crates/registry-breg/tests/fixtures/v0.51.0-reference-predecessor/package/metadata/registry.json new file mode 100644 index 0000000000..d1a7e131a7 --- /dev/null +++ b/crates/registry-breg/tests/fixtures/v0.51.0-reference-predecessor/package/metadata/registry.json @@ -0,0 +1 @@ +{"recordTypes":[{"entries":[{"accessProfile":"editor","operation":"create","readableFields":[],"responseRecordType":"entry","routeId":"records.entry.create"},{"accessProfile":"reader","operation":"list","readableFields":["name"],"responseRecordType":"entry","routeId":"records.entry.list"}],"id":"entry","route":"entries","schemaPath":"/v1/schemas/entry"}],"registryId":"reference-rehearsal","version":"1"} \ No newline at end of file diff --git a/crates/registry-breg/tests/fixtures/v0.51.0-reference-predecessor/package/openapi/openapi.json b/crates/registry-breg/tests/fixtures/v0.51.0-reference-predecessor/package/openapi/openapi.json new file mode 100644 index 0000000000..73b9549504 --- /dev/null +++ b/crates/registry-breg/tests/fixtures/v0.51.0-reference-predecessor/package/openapi/openapi.json @@ -0,0 +1 @@ +{"components":{"schemas":{"Problem":{"additionalProperties":false,"allOf":[{"if":{"properties":{"code":{"enum":["attachment.required","attachment.verification-pending","attachment.verification-rejected"]}}},"then":{"allOf":[{"else":{"properties":{"status":{"const":422}}},"if":{"properties":{"code":{"const":"attachment.verification-pending"}}},"then":{"properties":{"status":{"const":409}}}}],"properties":{"fieldPath":{"pattern":"^/attachments/[a-z][a-z0-9_-]{0,63}$","type":"string"}},"propertyNames":{"enum":["type","title","status","detail","code","traceId","fieldPath"]},"required":["fieldPath"]}},{"if":{"properties":{"code":{"const":"write.outside-boundary"}}},"then":{"properties":{"code":{"const":"write.outside-boundary"},"detail":{"const":"The write falls outside what the selected access profile may write: its row boundary or a disclosure condition."},"status":{"const":403},"title":{"const":"Forbidden"},"type":{"const":"https://id.registrystack.org/problems/registry-breg/write/outside-boundary"}},"propertyNames":{"enum":["type","title","status","detail","code","traceId","failedCheck"]}}},{"if":{"properties":{"code":{"not":{"const":"action.guard-failed"}}}},"then":{"not":{"required":["guardReason"]}}},{"if":{"properties":{"code":{"const":"action.refused"}}},"then":{"properties":{"status":{"const":422}},"required":["refusalCode"]}},{"if":{"properties":{"code":{"const":"statistical-dataset.release-refused"}}},"then":{"properties":{"refusalCode":{"enum":["period-not-ended","before-first-period","provisional-after-final","already-withdrawn","negative-value"]},"status":{"const":422}},"required":["refusalCode"]}},{"if":{"properties":{"code":{"not":{"enum":["action.refused","statistical-dataset.release-refused"]}}}},"then":{"not":{"required":["refusalCode"]}}},{"if":{"properties":{"code":{"const":"statistical-dataset.version-withdrawn"}}},"then":{"properties":{"status":{"const":410}},"required":["reasonCode"]}},{"if":{"properties":{"code":{"not":{"const":"statistical-dataset.version-withdrawn"}}}},"then":{"not":{"required":["reasonCode"]}}},{"if":{"properties":{"code":{"const":"access-profile.ambiguous"}}},"then":{"additionalProperties":true,"not":{"required":["failedCheck"]},"properties":{"status":{"const":400}},"required":["accessProfiles"]}},{"if":{"properties":{"code":{"not":{"const":"access-profile.ambiguous"}}}},"then":{"not":{"required":["accessProfiles"]}}},{"if":{"properties":{"code":{"const":"action.evidence-failed"}}},"then":{"properties":{"detail":{"const":"The declared Evidence dependency could not be accepted."},"fieldPath":{"pattern":"^/evidence/[a-z][a-z0-9_-]{0,63}$","type":"string"},"status":{"const":503}}}},{"if":{"properties":{"code":{"const":"action.handler-failed"}}},"then":{"properties":{"status":{"const":500}}}},{"if":{"anyOf":[{"required":["atField"]},{"required":["notAfterField"]}]},"then":{"properties":{"code":{"const":"request.invalid"},"status":{"const":400}},"required":["atField","notAfterField"]}},{"if":{"anyOf":[{"required":["recordType"]},{"required":["fieldId"]},{"required":["constraintId"]},{"required":["constraintKind"]},{"required":["left"]},{"required":["right"]},{"required":["field"]}]},"then":{"oneOf":[{"not":{"anyOf":[{"required":["constraintId"]},{"required":["constraintKind"]},{"required":["left"]},{"required":["right"]},{"required":["field"]}]},"required":["fieldId"]},{"not":{"required":["fieldId"]},"oneOf":[{"not":{"required":["field"]},"properties":{"constraintKind":{"const":"compare"}},"required":["left","right"]},{"not":{"anyOf":[{"required":["left"]},{"required":["right"]}]},"properties":{"constraintKind":{"enum":["int-range","vocabulary"]}},"required":["field"]}],"required":["constraintId","constraintKind"]}],"properties":{"code":{"const":"mutation.conflict"},"status":{"const":409}},"required":["recordType"]}}],"anyOf":[{"properties":{"code":{"const":"access-profile.ambiguous"},"status":{"const":400},"type":{"const":"https://id.registrystack.org/problems/registry-breg/access-profile/ambiguous"}}},{"properties":{"code":{"const":"action.evidence-failed"},"status":{"const":503},"type":{"const":"https://id.registrystack.org/problems/registry-breg/action/evidence-failed"}}},{"properties":{"code":{"const":"action.guard-failed"},"status":{"const":412},"type":{"const":"https://id.registrystack.org/problems/registry-breg/action/guard-failed"}}},{"properties":{"code":{"const":"action.handler-failed"},"status":{"const":500},"type":{"const":"https://id.registrystack.org/problems/registry-breg/action/handler-failed"}}},{"properties":{"code":{"const":"action.refused"},"status":{"const":422},"type":{"const":"https://id.registrystack.org/problems/registry-breg/action/refused"}}},{"properties":{"code":{"const":"attachment.content-type"},"status":{"const":415},"type":{"const":"https://id.registrystack.org/problems/registry-breg/attachment/content-type"}}},{"properties":{"code":{"const":"attachment.digest-mismatch"},"status":{"const":422},"type":{"const":"https://id.registrystack.org/problems/registry-breg/attachment/digest-mismatch"}}},{"properties":{"code":{"const":"attachment.limit-reached"},"status":{"const":409},"type":{"const":"https://id.registrystack.org/problems/registry-breg/attachment/limit-reached"}}},{"properties":{"code":{"const":"attachment.required"},"status":{"const":422},"type":{"const":"https://id.registrystack.org/problems/registry-breg/attachment/required"}}},{"properties":{"code":{"const":"attachment.slot-write-once"},"status":{"const":409},"type":{"const":"https://id.registrystack.org/problems/registry-breg/attachment/slot-write-once"}}},{"properties":{"code":{"const":"attachment.too-large"},"status":{"const":413},"type":{"const":"https://id.registrystack.org/problems/registry-breg/attachment/too-large"}}},{"properties":{"code":{"const":"attachment.verification-pending"},"status":{"const":409},"type":{"const":"https://id.registrystack.org/problems/registry-breg/attachment/verification-pending"}}},{"properties":{"code":{"const":"attachment.verification-rejected"},"status":{"const":422},"type":{"const":"https://id.registrystack.org/problems/registry-breg/attachment/verification-rejected"}}},{"properties":{"code":{"const":"authentication.refused"},"status":{"const":401},"type":{"const":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},{"properties":{"code":{"const":"idempotency.expired"},"status":{"const":410},"type":{"const":"https://id.registrystack.org/problems/registry-breg/idempotency/expired"}}},{"properties":{"code":{"const":"idempotency.key-reused"},"status":{"const":409},"type":{"const":"https://id.registrystack.org/problems/registry-breg/idempotency/key-reused"}}},{"properties":{"code":{"const":"ingestion.chunk-mismatch"},"status":{"const":409},"type":{"const":"https://id.registrystack.org/problems/registry-breg/ingestion/chunk-mismatch"}}},{"properties":{"code":{"const":"ingestion.profile-mismatch"},"status":{"const":403},"type":{"const":"https://id.registrystack.org/problems/registry-breg/ingestion/profile-mismatch"}}},{"properties":{"code":{"const":"ingestion.receipt-erased"},"status":{"const":410},"type":{"const":"https://id.registrystack.org/problems/registry-breg/ingestion/receipt-erased"}}},{"properties":{"code":{"const":"ingestion.run-blocked"},"status":{"const":409},"type":{"const":"https://id.registrystack.org/problems/registry-breg/ingestion/run-blocked"}}},{"properties":{"code":{"const":"ingestion.run-not-open"},"status":{"const":409},"type":{"const":"https://id.registrystack.org/problems/registry-breg/ingestion/run-not-open"}}},{"properties":{"code":{"const":"lookup.unresolved"},"status":{"const":404},"type":{"const":"https://id.registrystack.org/problems/registry-breg/lookup/unresolved"}}},{"properties":{"code":{"const":"mutation.conflict"},"status":{"const":409},"type":{"const":"https://id.registrystack.org/problems/registry-breg/mutation/conflict"}}},{"properties":{"code":{"const":"precondition.failed"},"status":{"const":412},"type":{"const":"https://id.registrystack.org/problems/registry-breg/precondition/failed"}}},{"properties":{"code":{"const":"precondition.required"},"status":{"const":428},"type":{"const":"https://id.registrystack.org/problems/registry-breg/precondition/required"}}},{"properties":{"code":{"const":"profile.not-authorized"},"status":{"const":403},"type":{"const":"https://id.registrystack.org/problems/registry-breg/profile/not-authorized"}}},{"properties":{"code":{"const":"proposal.rejected"},"status":{"const":409},"type":{"const":"https://id.registrystack.org/problems/registry-breg/proposal/rejected"}}},{"properties":{"code":{"const":"proposal.review-result-mismatch"},"status":{"const":412},"type":{"const":"https://id.registrystack.org/problems/registry-breg/proposal/review-result-mismatch"}}},{"properties":{"code":{"const":"proposal.submission-expired"},"status":{"const":410},"type":{"const":"https://id.registrystack.org/problems/registry-breg/proposal/submission-expired"}}},{"properties":{"code":{"const":"query.cursor-invalid"},"status":{"const":400},"type":{"const":"https://id.registrystack.org/problems/registry-breg/query/cursor-invalid"}}},{"properties":{"code":{"const":"query.filter-required"},"status":{"const":400},"type":{"const":"https://id.registrystack.org/problems/registry-breg/query/filter-required"}}},{"properties":{"code":{"const":"query.invalid"},"status":{"const":400},"type":{"const":"https://id.registrystack.org/problems/registry-breg/query/invalid"}}},{"properties":{"code":{"const":"request.access-reason-required"},"status":{"const":400},"type":{"const":"https://id.registrystack.org/problems/registry-breg/request/access-reason-required"}}},{"properties":{"code":{"const":"request.invalid"},"status":{"const":400},"type":{"const":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},{"properties":{"code":{"const":"request.timeout"},"status":{"const":504},"type":{"const":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},{"properties":{"code":{"const":"resource.not-found"},"status":{"const":404},"type":{"const":"https://id.registrystack.org/problems/registry-breg/resource/not-found"}}},{"properties":{"code":{"const":"runtime.field-encryption.unavailable"},"status":{"const":503},"type":{"const":"https://id.registrystack.org/problems/registry-breg/runtime/field-encryption/unavailable"}}},{"properties":{"code":{"const":"service.unavailable"},"status":{"const":503},"type":{"const":"https://id.registrystack.org/problems/registry-breg/service/unavailable"}}},{"properties":{"code":{"const":"source.unavailable"},"status":{"const":503},"type":{"const":"https://id.registrystack.org/problems/registry-breg/source/unavailable"}}},{"properties":{"code":{"const":"statistical-dataset.domain-violation"},"status":{"const":500},"type":{"const":"https://id.registrystack.org/problems/registry-breg/statistical-dataset/domain-violation"}}},{"properties":{"code":{"const":"statistical-dataset.release-refused"},"status":{"const":422},"type":{"const":"https://id.registrystack.org/problems/registry-breg/statistical-dataset/release-refused"}}},{"properties":{"code":{"const":"statistical-dataset.version-conflict"},"status":{"const":409},"type":{"const":"https://id.registrystack.org/problems/registry-breg/statistical-dataset/version-conflict"}}},{"properties":{"code":{"const":"statistical-dataset.version-withdrawn"},"status":{"const":410},"type":{"const":"https://id.registrystack.org/problems/registry-breg/statistical-dataset/version-withdrawn"}}},{"properties":{"code":{"const":"unsupported.media-type"},"status":{"const":415},"type":{"const":"https://id.registrystack.org/problems/registry-breg/unsupported/media-type"}}},{"properties":{"code":{"const":"write.outside-boundary"},"status":{"const":403},"type":{"const":"https://id.registrystack.org/problems/registry-breg/write/outside-boundary"}}}],"properties":{"accessProfiles":{"items":{"maxLength":128,"minLength":1,"type":"string"},"minItems":2,"type":"array","uniqueItems":true},"atField":{"maxLength":128,"minLength":1,"type":"string"},"code":{"enum":["access-profile.ambiguous","action.evidence-failed","action.guard-failed","action.handler-failed","action.refused","attachment.content-type","attachment.digest-mismatch","attachment.limit-reached","attachment.required","attachment.slot-write-once","attachment.too-large","attachment.verification-pending","attachment.verification-rejected","authentication.refused","idempotency.expired","idempotency.key-reused","ingestion.chunk-mismatch","ingestion.profile-mismatch","ingestion.receipt-erased","ingestion.run-blocked","ingestion.run-not-open","lookup.unresolved","mutation.conflict","precondition.failed","precondition.required","profile.not-authorized","proposal.rejected","proposal.review-result-mismatch","proposal.submission-expired","query.cursor-invalid","query.filter-required","query.invalid","request.access-reason-required","request.invalid","request.timeout","resource.not-found","runtime.field-encryption.unavailable","service.unavailable","source.unavailable","statistical-dataset.domain-violation","statistical-dataset.release-refused","statistical-dataset.version-conflict","statistical-dataset.version-withdrawn","unsupported.media-type","write.outside-boundary"],"type":"string"},"constraintId":{"maxLength":128,"minLength":1,"type":"string"},"constraintKind":{"enum":["compare","int-range","vocabulary"],"type":"string"},"detail":{"maxLength":256,"type":"string"},"failedCheck":{"description":"The check that refused the request, included only in development.","type":"string"},"field":{"maxLength":128,"minLength":1,"type":"string"},"fieldId":{"maxLength":128,"minLength":1,"type":"string"},"fieldPath":{"maxLength":256,"type":"string"},"guardReason":{"pattern":"^[a-z][a-z0-9_-]{0,63}$","type":"string"},"left":{"maxLength":128,"minLength":1,"type":"string"},"notAfterField":{"maxLength":128,"minLength":1,"type":"string"},"reasonCode":{"enum":["computation-error","source-data-error","disclosure-risk"],"type":"string"},"recordType":{"maxLength":128,"minLength":1,"type":"string"},"refusalCode":{"maxLength":128,"minLength":1,"type":"string"},"requiredFilters":{"items":{"items":{"maxLength":64,"minLength":1,"type":"string"},"maxItems":32,"minItems":1,"type":"array","uniqueItems":true},"maxItems":8,"minItems":1,"type":"array"},"right":{"maxLength":128,"minLength":1,"type":"string"},"status":{"maximum":599,"minimum":400,"type":"integer"},"title":{"maxLength":128,"type":"string"},"traceId":{"maxLength":32,"minLength":32,"pattern":"^[0-9a-f]{32}$","type":"string"},"type":{"format":"uri","maxLength":256,"type":"string"}},"required":["type","title","status","detail","code","traceId"],"type":"object"},"ReviewCompletion":{"additionalProperties":false,"properties":{"completedAt":{"format":"date-time","type":"string"},"eventId":{"format":"uuid","type":"string"},"requestId":{"format":"uuid","type":"string"},"resultId":{"format":"uuid","type":"string"},"type":{"const":"review.completed"}},"required":["type","eventId","requestId","resultId","completedAt"],"type":"object"},"category":{"$id":"urn:breg:record-type:category","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"name":{"anyOf":[{"maxLength":64,"minLength":0,"type":"string"},{"type":"null"}]}},"required":[],"type":"object","x-registry-mutationMode":"create-only"},"entry":{"$id":"urn:breg:record-type:entry","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"category":{"anyOf":[{"format":"uuid","type":"string"},{"type":"null"}]},"name":{"anyOf":[{"maxLength":64,"minLength":0,"type":"string"},{"type":"null"}]}},"required":[],"type":"object","x-registry-mutationMode":"create-only"},"entry-create-input":{"$id":"urn:breg:record-type:entry:input","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"category":{"anyOf":[{"format":"uuid","type":"string"},{"type":"null"}]},"name":{"anyOf":[{"maxLength":64,"minLength":0,"type":"string"},{"type":"null"}]}},"required":[],"type":"object","x-registry-mutationMode":"create-only"}},"securitySchemes":{"bearerAuth":{"bearerFormat":"JWT","scheme":"bearer","type":"http"},"reviewCompletion":{"description":"The review authority's configured completion key verifies the Standard Webhooks signature.","in":"header","name":"webhook-signature","type":"apiKey"}}},"info":{"title":"reference-rehearsal","version":"1"},"openapi":"3.1.0","paths":{"/v1/records/entries":{"get":{"operationId":"records.entry.list","parameters":[{"description":"Optional W3C trace context. Responses carry Registry trace context for the request.","in":"header","name":"traceparent","required":false,"schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}},{"description":"Select one compiled access profile. When omitted, the sole admitting profile or the route default is used; if several admit with no default, the route answers 400 access-profile.ambiguous.","explode":false,"in":"query","name":"accessProfile","required":false,"schema":{"maxLength":128,"type":"string"}},{"description":"Comma-separated subset of readable API property names.","explode":false,"in":"query","name":"$select","required":false,"schema":{"maxLength":16384,"type":"string"}},{"description":"Strict Registry read filter expression over compiled filterable API properties.","explode":false,"in":"query","name":"$filter","required":false,"schema":{"maxLength":16384,"type":"string"}},{"description":"One compiled sortable property, ascending only.","explode":false,"in":"query","name":"$orderby","required":false,"schema":{"maxLength":128,"type":"string"}},{"description":"Bounded page size.","explode":false,"in":"query","name":"limit","required":false,"schema":{"maximum":100,"minimum":1,"type":"integer"}},{"description":"Request count when the selected compiled query profile allows it.","explode":false,"in":"query","name":"$count","required":false,"schema":{"type":"boolean"}},{"description":"Opaque continuation cursor for the next page.","explode":false,"in":"query","name":"cursor","required":false,"schema":{"maxLength":10978,"type":"string"}},{"description":"Choose the ordinary JSON or JSON-LD Registry Record representation.","in":"header","name":"Accept","required":false,"schema":{"enum":["application/json","application/ld+json"],"type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"count":{"format":"int64","minimum":0,"type":"integer"},"items":{"items":{"additionalProperties":false,"properties":{"domainData":{"additionalProperties":false,"properties":{"name":{"anyOf":[{"maxLength":64,"minLength":0,"type":"string"},{"type":"null"}]}},"type":"object"},"recordId":{"format":"uuid","type":"string"},"revisionId":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordId","revisionId","domainData"],"type":"object"},"type":"array"},"meta":{"additionalProperties":false,"properties":{"datasetId":{"const":"records"},"recordTypeId":{"const":"entry"},"registryId":{"const":"reference-rehearsal"}},"required":["registryId","datasetId","recordTypeId"],"type":"object"},"pageInfo":{"additionalProperties":false,"properties":{"nextCursor":{"maxLength":10978,"type":["string","null"]}},"required":["nextCursor"],"type":"object"}},"required":["items","pageInfo","meta"],"type":"object"}},"application/ld+json":{"schema":{"additionalProperties":false,"properties":{"@context":{"const":"https://id.registrystack.org/contexts/registry-record/v1"},"count":{"format":"int64","minimum":0,"type":"integer"},"items":{"items":{"additionalProperties":false,"properties":{"domainData":{"additionalProperties":false,"properties":{"name":{"anyOf":[{"maxLength":64,"minLength":0,"type":"string"},{"type":"null"}]}},"type":"object"},"recordId":{"format":"uuid","type":"string"},"revisionId":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordId","revisionId","domainData"],"type":"object"},"type":"array"},"meta":{"additionalProperties":false,"properties":{"datasetId":{"const":"records"},"recordTypeId":{"const":"entry"},"registryId":{"const":"reference-rehearsal"}},"required":["registryId","datasetId","recordTypeId"],"type":"object"},"pageInfo":{"additionalProperties":false,"properties":{"nextCursor":{"maxLength":10978,"type":["string","null"]}},"required":["nextCursor"],"type":"object"}},"required":["items","pageInfo","meta","@context"],"type":"object"}}},"description":"Records returned","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"Link":{"description":"Emitted only for application/json and application/ld+json Registry Record responses and omitted for application/geo+json. Carries the Registry Record profile and caller-visible record type schema. The describedby target includes the configured deployment prefix and is never derived from Host or forwarded headers.","schema":{"example":"; rel=\"profile\", ; rel=\"describedby\"","type":"string"}},"Vary":{"description":"Responses vary by authorization and negotiated representation.","schema":{"type":"string"}},"traceparent":{"description":"Trace context for this response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"400":{"content":{"application/problem+json":{"examples":{"access-profile.ambiguous":{"value":{"accessProfiles":["profile-a","profile-b"],"code":"access-profile.ambiguous","detail":"Multiple access profiles admit this request on this route; select one with accessProfile.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/access-profile/ambiguous"}},"query.cursor-invalid":{"value":{"code":"query.cursor-invalid","detail":"The query cursor is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/query/cursor-invalid"}},"query.invalid":{"value":{"code":"query.invalid","detail":"The query request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/query/invalid"}},"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer token or delivery signature was not accepted.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"WWW-Authenticate":{"description":"The authentication scheme the route accepts. The challenge is the same for every refused credential.","schema":{"const":"Bearer","type":"string"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"403":{"content":{"application/problem+json":{"examples":{"profile.not-authorized":{"value":{"code":"profile.not-authorized","detail":"No access profile admits this caller for this request.","status":403,"title":"Forbidden","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/profile/not-authorized"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not-found":{"value":{"code":"resource.not-found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not-found"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"source.unavailable":{"value":{"code":"source.unavailable","detail":"The Registry data service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/source/unavailable"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"security":[{"bearerAuth":[]}],"x-registry-accessProfiles":["reader"],"x-registry-operation":"list","x-registry-queryKind":"list","x-registry-queryProfiles":{"reader":{"allowCount":false,"filterableProperties":[],"kind":"list","maximumPageSize":100,"profile":"reader","requiredFilters":[],"selectableProperties":["name"],"selectorProperties":[],"sortableProperties":[],"temporal":null}},"x-registry-recordType":"entry","x-registry-responseProfile":"https://id.registrystack.org/profiles/registry-record/v1","x-registry-responseRecordType":"entry","x-registry-responseShape":"RegistryRecordCollectionV1"},"post":{"operationId":"records.entry.create","parameters":[{"description":"Optional W3C trace context. Responses carry Registry trace context for the request.","in":"header","name":"traceparent","required":false,"schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}},{"description":"Select one compiled access profile. When omitted, the sole admitting profile or the route default is used; if several admit with no default, the route answers 400 access-profile.ambiguous.","explode":false,"in":"query","name":"accessProfile","required":false,"schema":{"maxLength":128,"type":"string"}},{"description":"Idempotency key bound to method, route, caller, target record, package revision, request body, and response field set.","in":"header","name":"Idempotency-Key","required":true,"schema":{"maxLength":256,"minLength":1,"pattern":"^[\\x21-\\x2B\\x2D-\\x3A\\x3C-\\x7E]+$","type":"string"}},{"description":"Choose the ordinary JSON or JSON-LD Registry Record representation.","in":"header","name":"Accept","required":false,"schema":{"enum":["application/json","application/ld+json"],"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"data":{"$ref":"#/components/schemas/entry-create-input"}},"required":["data"],"type":"object"}}},"required":true},"responses":{"201":{"content":{"application/json":{"schema":{"additionalProperties":false,"properties":{"data":{"additionalProperties":false,"properties":{"domainData":{"$ref":"#/components/schemas/entry"},"recordId":{"format":"uuid","type":"string"},"revisionId":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordId","revisionId","domainData"],"type":"object"},"meta":{"additionalProperties":false,"properties":{"datasetId":{"const":"records"},"recordTypeId":{"const":"entry"},"registryId":{"const":"reference-rehearsal"}},"required":["registryId","datasetId","recordTypeId"],"type":"object"}},"required":["data","meta"],"type":"object"}},"application/ld+json":{"schema":{"additionalProperties":false,"properties":{"@context":{"const":"https://id.registrystack.org/contexts/registry-record/v1"},"data":{"additionalProperties":false,"properties":{"domainData":{"$ref":"#/components/schemas/entry"},"recordId":{"format":"uuid","type":"string"},"revisionId":{"pattern":"^[1-9][0-9]*$","type":"string"}},"required":["recordId","revisionId","domainData"],"type":"object"},"meta":{"additionalProperties":false,"properties":{"datasetId":{"const":"records"},"recordTypeId":{"const":"entry"},"registryId":{"const":"reference-rehearsal"}},"required":["registryId","datasetId","recordTypeId"],"type":"object"}},"required":["data","meta","@context"],"type":"object"}}},"description":"Record created","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"ETag":{"description":"Strong Registry ETag bound to the record, package revision, caller profile, and response field set.","schema":{"pattern":"^\\\"breg-[\\x21\\x23-\\x7E]+\\\"$","type":"string"}},"Link":{"description":"Emitted only for application/json and application/ld+json Registry Record responses and omitted for application/geo+json. Carries the Registry Record profile and caller-visible record type schema. The describedby target includes the configured deployment prefix and is never derived from Host or forwarded headers.","schema":{"example":"; rel=\"profile\", ; rel=\"describedby\"","type":"string"}},"Location":{"description":"Relative URL of the created record.","schema":{"type":"string"}},"Vary":{"description":"Responses vary by authorization and negotiated representation.","schema":{"type":"string"}},"traceparent":{"description":"Trace context for this response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"400":{"content":{"application/problem+json":{"examples":{"access-profile.ambiguous":{"value":{"accessProfiles":["profile-a","profile-b"],"code":"access-profile.ambiguous","detail":"Multiple access profiles admit this request on this route; select one with accessProfile.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/access-profile/ambiguous"}},"request.invalid":{"value":{"code":"request.invalid","detail":"The request is invalid.","status":400,"title":"Bad Request","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/invalid"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"401":{"content":{"application/problem+json":{"examples":{"authentication.refused":{"value":{"code":"authentication.refused","detail":"The bearer token or delivery signature was not accepted.","status":401,"title":"Unauthorized","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/authentication/refused"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"WWW-Authenticate":{"description":"The authentication scheme the route accepts. The challenge is the same for every refused credential.","schema":{"const":"Bearer","type":"string"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"403":{"content":{"application/problem+json":{"examples":{"profile.not-authorized":{"value":{"code":"profile.not-authorized","detail":"No access profile admits this caller for this request.","status":403,"title":"Forbidden","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/profile/not-authorized"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"404":{"content":{"application/problem+json":{"examples":{"resource.not-found":{"value":{"code":"resource.not-found","detail":"The requested resource was not found.","status":404,"title":"Not Found","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/resource/not-found"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"409":{"content":{"application/problem+json":{"examples":{"idempotency.key-reused":{"value":{"code":"idempotency.key-reused","detail":"The idempotency key is bound to another request.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/key-reused"}},"mutation.conflict":{"value":{"code":"mutation.conflict","detail":"The mutation conflicts with current state.","status":409,"title":"Conflict","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/mutation/conflict"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"410":{"content":{"application/problem+json":{"examples":{"idempotency.expired":{"value":{"code":"idempotency.expired","detail":"The held response of the idempotency key expired; the key stays spent.","status":410,"title":"Gone","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/idempotency/expired"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"415":{"content":{"application/problem+json":{"examples":{"unsupported.media-type":{"value":{"code":"unsupported.media-type","detail":"The request media type is not supported.","status":415,"title":"Unsupported Media Type","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/unsupported/media-type"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"503":{"content":{"application/problem+json":{"examples":{"service.unavailable":{"value":{"code":"service.unavailable","detail":"The Registry mutation service is unavailable.","status":503,"title":"Service Unavailable","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/service/unavailable"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}},"504":{"content":{"application/problem+json":{"examples":{"request.timeout":{"value":{"code":"request.timeout","detail":"The request timed out.","status":504,"title":"Gateway Timeout","traceId":"11111111111111111111111111111111","type":"https://id.registrystack.org/problems/registry-breg/request/timeout"}}},"schema":{"$ref":"#/components/schemas/Problem"}}},"description":"Problem response","headers":{"Cache-Control":{"description":"Caller-dependent responses must not be stored.","schema":{"const":"no-store"}},"traceparent":{"description":"Trace context for this problem response.","example":"00-11111111111111111111111111111111-2222222222222222-01","schema":{"maxLength":55,"minLength":55,"pattern":"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$","type":"string"}}}}},"security":[{"bearerAuth":[]}],"x-registry-accessProfiles":["editor"],"x-registry-operation":"create","x-registry-recordType":"entry","x-registry-responseProfile":"https://id.registrystack.org/profiles/registry-record/v1","x-registry-responseRecordType":"entry","x-registry-responseShape":"RegistryRecordSingleV1"}},"/v1/review-completions":{"post":{"description":"Available when a review authority configures a completion block.","operationId":"receiveReviewCompletion","parameters":[{"in":"header","name":"Registry-Recipient-Binding","required":true,"schema":{"maxLength":256,"minLength":1,"type":"string"}},{"description":"Must equal eventId.","in":"header","name":"webhook-id","required":true,"schema":{"format":"uuid","type":"string"}},{"in":"header","name":"webhook-timestamp","required":true,"schema":{"pattern":"^(0|[1-9][0-9]{0,19})$","type":"string"}},{"in":"header","name":"webhook-signature","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ReviewCompletion"}}},"required":true},"responses":{"204":{"description":"Completion accepted or already recorded."},"400":{"description":"The completion is invalid or eventId differs from webhook-id."},"401":{"description":"The completion authority could not be authenticated.","headers":{"WWW-Authenticate":{"schema":{"const":"Registry-Signature scheme=\"standard-webhooks\", version=\"v1\"","type":"string"}}}},"413":{"description":"The completion body exceeds 2048 bytes. The response body is empty."},"415":{"description":"The request is not application/json."},"503":{"description":"The completion could not be durably recorded."}},"security":[{"reviewCompletion":[]}],"summary":"Receive a Casework review completion"}}}} \ No newline at end of file diff --git a/crates/registry-breg/tests/fixtures/v0.51.0-reference-predecessor/package/package.json b/crates/registry-breg/tests/fixtures/v0.51.0-reference-predecessor/package/package.json new file mode 100644 index 0000000000..c52bd72969 --- /dev/null +++ b/crates/registry-breg/tests/fixtures/v0.51.0-reference-predecessor/package/package.json @@ -0,0 +1 @@ +{"apiVersion":"id.registrystack.org/formats/breg/package/v2","kind":"BRegPackage","manifest":{"compiler":{"id":"breg","profile":"production","sourceRevision":"v0.51.0-reference-rehearsal-fixture"},"engineFeatures":["statistical_release_store","caller_scoped_idempotency","record_timer_store"],"files":[{"path":"database/ddl.sql","role":"generated_ddl","sha256":"sha256:231f9b5bf3fce34d03b94f4c7469d04e634864a57f85f2b22ff41ff111fe98c2","size":6777},{"path":"database/migration-plan.json","role":"migration_plan","sha256":"sha256:1872670a4b4f6a2761877597f1e677715451ec449afc9159356f5c0e744de198","size":8353},{"path":"effective-model.json","role":"governed_model","sha256":"sha256:dcdf1f9af83cef41567f887808163c04a85e1bc76e2622433ef4d1c31802efeb","size":5349},{"path":"inventories/access.json","role":"access_inventory","sha256":"sha256:9e9e0afc5fbbb8b65552729c9e74e0cfd37087b0ebb26f82a5f434dbfa0fc9a9","size":267},{"path":"inventories/events.json","role":"event_inventory","sha256":"sha256:7263162aa981e58eb0b8fd4ba058a1b17ff622c1e8784820b8ec1f407e9bd384","size":17},{"path":"inventories/physical-names.json","role":"physical_name_inventory","sha256":"sha256:0c555a61a985021bdcdedfdef81156079962659de269c782263af19e8279f334","size":736},{"path":"inventories/queries.json","role":"query_inventory","sha256":"sha256:ede4e9f3f991500b3e38fa652047cbdf3eabcc5168373f65acb8f1770c1c262b","size":296},{"path":"inventories/routes.json","role":"route_inventory","sha256":"sha256:e17e0adccd7e52b3d6579afc74483f5159cd320ddbc0c484c70dacf34239c5a2","size":380},{"path":"metadata/registry.json","role":"caller_safe_metadata","sha256":"sha256:64ddb25ba9ea8800af3b108765b900ac54369b60da6158269c6529b76bce2ca3","size":406},{"path":"openapi/openapi.json","role":"generated_openapi","sha256":"sha256:41eef0f04f9ba4606aba7dcb71036be68a5e1773a341a3dd5623814703084de5","size":41834},{"path":"schemas/category.schema.json","role":"entity_json_schema","sha256":"sha256:a6542b2f94ec89880a609577351ca881466e06874cef4a985c8e17e1f6ac6b76","size":292},{"path":"schemas/entry.schema.json","role":"entity_json_schema","sha256":"sha256:cbdf09590e36cff2afecc0e3d536ed33779a4657ba624ec44d37ecae3c1a8619","size":362},{"path":"source/registry.yaml","role":"source_project","sha256":"sha256:e9e13030735f24824b4eb2be56c394692afc91956090aceb2e655f69c84d0eb8","size":1633},{"path":"tests/journeys.yaml","role":"fixture_journeys","sha256":"sha256:253493af5c5fd85d65bc3fa645ba4f0b0f56c4b154c7a77525b677e0213d4f5b","size":398}],"migrationPlan":{"statements":[{"id":"schema.registry_data","kind":"schema","sql":"CREATE SCHEMA IF NOT EXISTS registry_data"},{"id":"schema.registry_source","kind":"schema","sql":"CREATE SCHEMA IF NOT EXISTS registry_source"},{"id":"schema.registry_derived","kind":"schema","sql":"CREATE SCHEMA IF NOT EXISTS registry_derived"},{"id":"schema.registry_context","kind":"schema","sql":"CREATE SCHEMA IF NOT EXISTS registry_context"},{"id":"function.registry_context.evaluation_date","kind":"function","sql":"CREATE OR REPLACE FUNCTION registry_context.evaluation_date()\n RETURNS date\n LANGUAGE sql\n STABLE\n SECURITY INVOKER\n AS $breg_function$\n SELECT NULLIF(current_setting('registry.evaluation_date', true), '')::date\n $breg_function$"},{"id":"entity.category.table","kind":"table","sql":"CREATE TABLE registry_data.\"breg_e_category_284c16a2a34063e5\" (record_id uuid NOT NULL, record_revision bigint NOT NULL DEFAULT 1 CHECK (record_revision > 0), record_lifecycle text COLLATE pg_catalog.pg_c_utf8 NOT NULL DEFAULT 'active' CHECK (record_lifecycle IN ('active', 'tombstoned')), created_at timestamptz NOT NULL DEFAULT transaction_timestamp(), updated_at timestamptz NOT NULL DEFAULT transaction_timestamp(), active_package_revision text COLLATE pg_catalog.pg_c_utf8 NOT NULL DEFAULT NULLIF(current_setting('registry.active_package_revision', true), '') CHECK (active_package_revision <> ''), PRIMARY KEY (record_id), \"breg_f_category_name_b74daabde89a5552\" varchar(64) COLLATE pg_catalog.pg_c_utf8)"},{"id":"entity.entry.table","kind":"table","sql":"CREATE TABLE registry_data.\"breg_e_entry_c691cfb82ab6e25e\" (record_id uuid NOT NULL, record_revision bigint NOT NULL DEFAULT 1 CHECK (record_revision > 0), record_lifecycle text COLLATE pg_catalog.pg_c_utf8 NOT NULL DEFAULT 'active' CHECK (record_lifecycle IN ('active', 'tombstoned')), created_at timestamptz NOT NULL DEFAULT transaction_timestamp(), updated_at timestamptz NOT NULL DEFAULT transaction_timestamp(), active_package_revision text COLLATE pg_catalog.pg_c_utf8 NOT NULL DEFAULT NULLIF(current_setting('registry.active_package_revision', true), '') CHECK (active_package_revision <> ''), PRIMARY KEY (record_id), \"breg_f_entry_category_0a2a03f0519a4bb7\" uuid, \"breg_f_entry_name_b223a4d2b68b84ee\" varchar(64) COLLATE pg_catalog.pg_c_utf8)"},{"id":"entity.category.reference-lifecycle.key","kind":"constraint","sql":"ALTER TABLE registry_data.\"breg_e_category_284c16a2a34063e5\" ADD CONSTRAINT \"breg_rk_category_e09350e5c007cb8e\" UNIQUE (record_id, record_lifecycle)"},{"id":"entity.entry.reference-lifecycle.column","kind":"column","sql":"ALTER TABLE registry_data.\"breg_e_entry_c691cfb82ab6e25e\" ADD COLUMN record_reference_lifecycle text COLLATE pg_catalog.pg_c_utf8\n GENERATED ALWAYS AS (CASE WHEN record_lifecycle = 'active' THEN 'active'::text ELSE NULL::text END) STORED"},{"id":"entity.entry.field.category.reference","kind":"reference","sql":"ALTER TABLE registry_data.\"breg_e_entry_c691cfb82ab6e25e\" ADD CONSTRAINT \"breg_r_entry_category_5aba7f6cb64640e7\" FOREIGN KEY (\"breg_f_entry_category_0a2a03f0519a4bb7\") REFERENCES registry_data.\"breg_e_category_284c16a2a34063e5\" (record_id) ON DELETE RESTRICT"},{"id":"entity.entry.field.category.active-reference","kind":"reference","sql":"ALTER TABLE registry_data.\"breg_e_entry_c691cfb82ab6e25e\" NO FORCE ROW LEVEL SECURITY;\nALTER TABLE registry_data.\"breg_e_category_284c16a2a34063e5\" NO FORCE ROW LEVEL SECURITY;\nALTER TABLE registry_data.\"breg_e_entry_c691cfb82ab6e25e\" ADD CONSTRAINT \"breg_ar_entry_category_7b190379404e320b\" FOREIGN KEY (\"breg_f_entry_category_0a2a03f0519a4bb7\", record_reference_lifecycle) REFERENCES registry_data.\"breg_e_category_284c16a2a34063e5\" (record_id, record_lifecycle) MATCH SIMPLE ON UPDATE NO ACTION ON DELETE RESTRICT;\nALTER TABLE registry_data.\"breg_e_entry_c691cfb82ab6e25e\" FORCE ROW LEVEL SECURITY;\nALTER TABLE registry_data.\"breg_e_category_284c16a2a34063e5\" FORCE ROW LEVEL SECURITY"},{"id":"entity.entry.index.reference:category","kind":"index","sql":"CREATE INDEX \"breg_ri_entry_category_ff9998a3c15186b6\" ON registry_data.\"breg_e_entry_c691cfb82ab6e25e\" (\"breg_f_entry_category_0a2a03f0519a4bb7\")"},{"id":"entity.category.rls.enable","kind":"row_security","sql":"ALTER TABLE registry_data.\"breg_e_category_284c16a2a34063e5\" ENABLE ROW LEVEL SECURITY"},{"id":"entity.category.rls.force","kind":"row_security","sql":"ALTER TABLE registry_data.\"breg_e_category_284c16a2a34063e5\" FORCE ROW LEVEL SECURITY"},{"id":"entity.entry.rls.enable","kind":"row_security","sql":"ALTER TABLE registry_data.\"breg_e_entry_c691cfb82ab6e25e\" ENABLE ROW LEVEL SECURITY"},{"id":"entity.entry.rls.force","kind":"row_security","sql":"ALTER TABLE registry_data.\"breg_e_entry_c691cfb82ab6e25e\" FORCE ROW LEVEL SECURITY"},{"id":"entity.entry.policy.registry_rls_insert_c20605ed93691b2b174e27bc","kind":"policy","sql":"CREATE POLICY \"registry_rls_insert_c20605ed93691b2b174e27bc\" ON registry_data.\"breg_e_entry_c691cfb82ab6e25e\" FOR INSERT WITH CHECK ((NULLIF(current_setting('registry.access_profile', true), '') = 'editor' AND NULLIF(current_setting('registry.principal', true), '') IS NOT NULL AND jsonb_typeof(NULLIF(current_setting('registry.row_boundaries', true), '')::jsonb) = 'array' AND jsonb_array_length(NULLIF(current_setting('registry.row_boundaries', true), '')::jsonb) = 0) AND record_lifecycle = 'active');\nCOMMENT ON POLICY \"registry_rls_insert_c20605ed93691b2b174e27bc\" ON registry_data.\"breg_e_entry_c691cfb82ab6e25e\" IS 'breg/policy/v1/aac8da39bc88f49c906e0a58432a7340b49909bce3d0a0caab365c86f4847071'"},{"id":"entity.entry.policy.registry_create_returning_rls_93972995e60731bc7464c338","kind":"policy","sql":"CREATE POLICY \"registry_create_returning_rls_93972995e60731bc7464c338\" ON registry_data.\"breg_e_entry_c691cfb82ab6e25e\" FOR SELECT USING ((NULLIF(current_setting('registry.access_profile', true), '') = 'editor' AND NULLIF(current_setting('registry.principal', true), '') IS NOT NULL AND jsonb_typeof(NULLIF(current_setting('registry.row_boundaries', true), '')::jsonb) = 'array' AND jsonb_array_length(NULLIF(current_setting('registry.row_boundaries', true), '')::jsonb) = 0) AND record_lifecycle = 'active' AND 'entry' = NULLIF(current_setting('registry.created_entity_id', true), '') AND record_id = NULLIF(current_setting('registry.created_record_id', true), '')::uuid);\nCOMMENT ON POLICY \"registry_create_returning_rls_93972995e60731bc7464c338\" ON registry_data.\"breg_e_entry_c691cfb82ab6e25e\" IS 'breg/policy/v1/a7736c35bb0a78bc4f0a557b10ee5d4199921da7e15134436d10f2c4c0ea78d3'"},{"id":"entity.entry.policy.registry_rls_select_a949aa044b11815c56813b65","kind":"policy","sql":"CREATE POLICY \"registry_rls_select_a949aa044b11815c56813b65\" ON registry_data.\"breg_e_entry_c691cfb82ab6e25e\" FOR SELECT USING ((NULLIF(current_setting('registry.access_profile', true), '') = 'reader' AND NULLIF(current_setting('registry.principal', true), '') IS NOT NULL AND jsonb_typeof(NULLIF(current_setting('registry.row_boundaries', true), '')::jsonb) = 'array' AND jsonb_array_length(NULLIF(current_setting('registry.row_boundaries', true), '')::jsonb) = 0) AND (record_lifecycle = 'active'));\nCOMMENT ON POLICY \"registry_rls_select_a949aa044b11815c56813b65\" ON registry_data.\"breg_e_entry_c691cfb82ab6e25e\" IS 'breg/policy/v1/db3a8229a6ca7c86cba13bd0889ac61c2bb486fd1fcb5bc88dfce541bf639627'"},{"id":"entity.category.source-view","kind":"view","sql":"CREATE VIEW registry_source.\"category\"\n WITH (security_invoker=true)\n AS SELECT record_id AS \"id\", \"breg_f_category_name_b74daabde89a5552\" AS \"name\"\n FROM registry_data.\"breg_e_category_284c16a2a34063e5\"\n WHERE record_lifecycle = 'active'"},{"id":"entity.entry.source-view","kind":"view","sql":"CREATE VIEW registry_source.\"entry\"\n WITH (security_invoker=true)\n AS SELECT record_id AS \"id\", \"breg_f_entry_name_b223a4d2b68b84ee\" AS \"name\", \"breg_f_entry_category_0a2a03f0519a4bb7\" AS \"category\"\n FROM registry_data.\"breg_e_entry_c691cfb82ab6e25e\"\n WHERE record_lifecycle = 'active'"}]},"packageId":"reference-rehearsal","schemaFingerprint":"sha256:e412288aa02f5f0aa0acee3e1c10cbcf93429695620b7ff92f6ad853c5bb15ff","sources":{"fixtureJourneys":"tests/journeys.yaml","modules":[],"project":"source/registry.yaml"}}} \ No newline at end of file diff --git a/crates/registry-breg/tests/fixtures/v0.51.0-reference-predecessor/package/schemas/category.schema.json b/crates/registry-breg/tests/fixtures/v0.51.0-reference-predecessor/package/schemas/category.schema.json new file mode 100644 index 0000000000..37855f7d3c --- /dev/null +++ b/crates/registry-breg/tests/fixtures/v0.51.0-reference-predecessor/package/schemas/category.schema.json @@ -0,0 +1 @@ +{"$id":"urn:breg:record-type:category","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"name":{"anyOf":[{"maxLength":64,"minLength":0,"type":"string"},{"type":"null"}]}},"required":[],"type":"object","x-registry-mutationMode":"create-only"} \ No newline at end of file diff --git a/crates/registry-breg/tests/fixtures/v0.51.0-reference-predecessor/package/schemas/entry.schema.json b/crates/registry-breg/tests/fixtures/v0.51.0-reference-predecessor/package/schemas/entry.schema.json new file mode 100644 index 0000000000..3c383183b9 --- /dev/null +++ b/crates/registry-breg/tests/fixtures/v0.51.0-reference-predecessor/package/schemas/entry.schema.json @@ -0,0 +1 @@ +{"$id":"urn:breg:record-type:entry","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"category":{"anyOf":[{"format":"uuid","type":"string"},{"type":"null"}]},"name":{"anyOf":[{"maxLength":64,"minLength":0,"type":"string"},{"type":"null"}]}},"required":[],"type":"object","x-registry-mutationMode":"create-only"} \ No newline at end of file diff --git a/crates/registry-breg/tests/fixtures/v0.51.0-reference-predecessor/package/source/registry.yaml b/crates/registry-breg/tests/fixtures/v0.51.0-reference-predecessor/package/source/registry.yaml new file mode 100644 index 0000000000..6624e83dbd --- /dev/null +++ b/crates/registry-breg/tests/fixtures/v0.51.0-reference-predecessor/package/source/registry.yaml @@ -0,0 +1,57 @@ +{ + "apiVersion": "id.registrystack.org/formats/breg/project/v1alpha1", + "kind": "BRegProject", + "project": { + "id": "reference-rehearsal", + "version": "1", + "defaultLanguage": "en", + "canonicalBaseIri": "https://reference.example.test" + }, + "package": {"sourceRevision": "v0.51.0-reference-rehearsal-fixture"}, + "datasets": {"records": {}}, + "recordTypes": { + "category": { + "primaryDataset": "records", + "route": "categories", + "mutationMode": "create-only", + "fields": [ + {"id": "name", "type": "string", "maximumLength": 64, "classification": "internal"} + ] + }, + "entry": { + "primaryDataset": "records", + "route": "entries", + "mutationMode": "create-only", + "fields": [ + {"id": "name", "type": "string", "maximumLength": 64, "classification": "internal"}, + {"id": "category", "type": "reference", "target": "category", "classification": "internal"} + ] + } + }, + "accessProfiles": { + "editor": { + "principalClaim": "principal", + "requiredScopes": ["records:write"], + "permissions": {"records": [ + { + "recordType": "entry", + "operations": ["create"], + "writableFields": ["category", "name"], + "rowBoundaries": "unrestricted" + } + ]} + }, + "reader": { + "principalClaim": "principal", + "requiredScopes": ["records:read"], + "permissions": {"records": [ + { + "recordType": "entry", + "operations": ["list"], + "readableFields": ["name"], + "rowBoundaries": "unrestricted" + } + ]} + } + } +} diff --git a/crates/registry-breg/tests/fixtures/v0.51.0-reference-predecessor/package/tests/journeys.yaml b/crates/registry-breg/tests/fixtures/v0.51.0-reference-predecessor/package/tests/journeys.yaml new file mode 100644 index 0000000000..2200486f35 --- /dev/null +++ b/crates/registry-breg/tests/fixtures/v0.51.0-reference-predecessor/package/tests/journeys.yaml @@ -0,0 +1,14 @@ +apiVersion: id.registrystack.org/formats/breg/journeys/v1 +kind: BRegJourneys +journeys: + - id: empty-entries + steps: + - id: list-entries + actor: reader + recordType: entry + accessProfile: reader + claims: + principal: synthetic-reader + scopes: [records:read] + request: {type: list} + expect: {outcome: success, status: 200, count: 0} diff --git a/crates/registry-breg/tests/fixtures/v0.51.0-review-ask-files.sql b/crates/registry-breg/tests/fixtures/v0.51.0-review-ask-files.sql new file mode 100644 index 0000000000..19f7004a53 --- /dev/null +++ b/crates/registry-breg/tests/fixtures/v0.51.0-review-ask-files.sql @@ -0,0 +1,186 @@ +-- SPDX-License-Identifier: Apache-2.0 +-- The v0.51.0 ask-files table and its transitive CREATE TABLE dependencies. +-- Taken from the Proposal, attachment, and Review stores at the v0.51.0 tag. +-- The current installer supplies the rest of the managed schema. + +CREATE TABLE IF NOT EXISTS registry_internal.registry_proposal_state ( + action_id text NOT NULL CHECK (action_id <> ''), + proposal_id uuid NOT NULL UNIQUE, + owner_reference text NOT NULL CHECK (owner_reference <> ''), + state text NOT NULL CHECK (state IN + ('draft','submitted','cancelled','applied','rejected')), + submission_version bigint NOT NULL CHECK (submission_version BETWEEN 1 AND 4294967295), + workflow_revision bigint NOT NULL CHECK (workflow_revision > 0), + action_revision text NOT NULL DEFAULT '', + action_title text, + input jsonb CHECK (input IS NULL OR jsonb_typeof(input) = 'object'), + input_targets jsonb NOT NULL DEFAULT '[]' CHECK (jsonb_typeof(input_targets) = 'array'), + blocked_reason text + CONSTRAINT registry_proposal_state_blocked_reason_values + CHECK (blocked_reason IS NULL OR blocked_reason IN + ('package-changed','application-refused','application-rebase')), + detail_erased_at timestamptz, + created_at timestamptz NOT NULL DEFAULT transaction_timestamp(), + updated_at timestamptz NOT NULL DEFAULT transaction_timestamp(), + PRIMARY KEY (action_id, proposal_id), + CONSTRAINT registry_proposal_state_detail_erasure_terminal CHECK ( + detail_erased_at IS NULL OR state IN ('cancelled','applied','rejected') + ) +); + +CREATE TABLE IF NOT EXISTS registry_internal.registry_proposal_submissions ( + action_id text NOT NULL, + proposal_id uuid NOT NULL, + submission_version bigint NOT NULL CHECK (submission_version BETWEEN 1 AND 4294967295), + input_revision bigint NOT NULL CHECK (input_revision > 0), + contract_fingerprint text NOT NULL CHECK (contract_fingerprint ~ '^sha256:[0-9a-f]{64}$'), + effect_digest text NOT NULL CHECK (effect_digest ~ '^sha256:[0-9a-f]{64}$'), + snapshot jsonb, + erased_at timestamptz, + created_at timestamptz NOT NULL DEFAULT transaction_timestamp(), + PRIMARY KEY (action_id, proposal_id, submission_version), + FOREIGN KEY (action_id, proposal_id) + REFERENCES registry_internal.registry_proposal_state, + CHECK ((snapshot IS NULL) = (erased_at IS NOT NULL)), + CHECK (snapshot IS NULL OR jsonb_typeof(snapshot) = 'object') +); + +CREATE TABLE IF NOT EXISTS registry_internal.registry_proposal_additions ( + action_id text NOT NULL, + proposal_id uuid NOT NULL, + submission_version bigint NOT NULL CHECK (submission_version BETWEEN 1 AND 4294967295), + addition_id uuid NOT NULL, + slot_id text NOT NULL, + sha256 text CHECK (sha256 ~ '^[0-9a-f]{64}$'), + content_type text, + byte_size bigint CHECK (byte_size BETWEEN 1 AND 16777216), + added_at timestamptz, + added_by text, + erased_at timestamptz, + PRIMARY KEY (action_id, proposal_id, submission_version, addition_id), + FOREIGN KEY (action_id,proposal_id) REFERENCES registry_internal.registry_proposal_state, + CHECK ((erased_at IS NULL AND sha256 IS NOT NULL AND content_type IS NOT NULL + AND byte_size IS NOT NULL AND added_at IS NOT NULL AND added_by IS NOT NULL) + OR (erased_at IS NOT NULL AND sha256 IS NULL AND content_type IS NULL + AND byte_size IS NULL AND added_at IS NULL AND added_by IS NULL)) +); + +CREATE TABLE IF NOT EXISTS registry_internal.registry_proposal_review_submissions ( + action_id text NOT NULL CHECK (action_id <> ''), + proposal_id uuid NOT NULL, + submission_version bigint NOT NULL CHECK (submission_version BETWEEN 1 AND 4294967295), + proposal_digest text NOT NULL CHECK (proposal_digest ~ '^sha256:[0-9a-f]{64}$'), + job_id uuid NOT NULL UNIQUE, + authority text NOT NULL CHECK (authority <> '' AND octet_length(authority) <= 128), + producer_id text NOT NULL CHECK (producer_id <> '' AND octet_length(producer_id) <= 128), + policy_id text NOT NULL CHECK (policy_id <> '' AND octet_length(policy_id) <= 128), + expected_policy jsonb NOT NULL CHECK (jsonb_typeof(expected_policy) = 'object'), + idempotency_key text NOT NULL UNIQUE CHECK ( + idempotency_key <> '' AND octet_length(idempotency_key) <= 128 + ), + create_request jsonb NOT NULL CHECK ( + jsonb_typeof(create_request) = 'object' + AND octet_length(create_request::text) <= 98304 + ), + expected_submission_digest text NOT NULL + CHECK (expected_submission_digest ~ '^sha256:[0-9a-f]{64}$'), + on_approved_mode text NOT NULL CHECK (on_approved_mode IN ('manual','automatic')), + executor text CHECK (executor IS NULL OR (executor <> '' AND octet_length(executor) <= 128)), + state text NOT NULL CHECK (state IN + ('pending','submitting','accepted','uncertain','cancelling','cancelled','failed')), + accepted_binding jsonb CHECK ( + accepted_binding IS NULL OR ( + jsonb_typeof(accepted_binding) = 'object' + AND octet_length(accepted_binding::text) <= 8192 + ) + ), + attempt_count integer NOT NULL DEFAULT 0 CHECK (attempt_count BETWEEN 0 AND 1000), + withdrawn boolean NOT NULL DEFAULT false, + recovery_deadline timestamptz NOT NULL + DEFAULT (transaction_timestamp()+interval '30 days'), + result_poll_attempts integer NOT NULL DEFAULT 0 + CHECK (result_poll_attempts BETWEEN 0 AND 1000), + next_result_poll_at timestamptz NOT NULL DEFAULT transaction_timestamp(), + next_attempt_at timestamptz NOT NULL DEFAULT transaction_timestamp(), + lease_until timestamptz, + last_error_code text CHECK ( + last_error_code IS NULL OR + (last_error_code <> '' AND octet_length(last_error_code) <= 128) + ), + created_at timestamptz NOT NULL DEFAULT transaction_timestamp(), + updated_at timestamptz NOT NULL DEFAULT transaction_timestamp(), + PRIMARY KEY (action_id, proposal_id, submission_version), + FOREIGN KEY (action_id, proposal_id, submission_version) + REFERENCES registry_internal.registry_proposal_submissions, + CHECK ((on_approved_mode = 'manual' AND executor IS NULL) + OR (on_approved_mode = 'automatic' AND executor IS NOT NULL)), + CHECK ((state IN ('accepted','cancelling') AND accepted_binding IS NOT NULL) + OR state NOT IN ('accepted','cancelling')) +); + +CREATE TABLE IF NOT EXISTS registry_internal.registry_proposal_review_asks ( + authority text NOT NULL, + review_request_id uuid NOT NULL, + ask_id uuid NOT NULL, + action_id text NOT NULL, + proposal_id uuid NOT NULL, + submission_version bigint NOT NULL, + text text CHECK (text IS NULL OR octet_length(text) BETWEEN 1 AND 2000), + wants jsonb NOT NULL CHECK (jsonb_typeof(wants)='array' AND jsonb_array_length(wants)<=8), + asked_at timestamptz NOT NULL, + asked_at_wire text NOT NULL CHECK (octet_length(asked_at_wire)<=64), + due_at timestamptz, + due_at_wire text CHECK (due_at_wire IS NULL OR octet_length(due_at_wire)<=64), + state text NOT NULL CHECK (state IN ('open','answered','expired','closed')), + answered_at timestamptz, + closed_at timestamptz, + detail_erased_at timestamptz, + PRIMARY KEY (authority,review_request_id,ask_id), + UNIQUE (authority,review_request_id,ask_id,action_id,proposal_id,submission_version), + FOREIGN KEY (action_id,proposal_id,submission_version) + REFERENCES registry_internal.registry_proposal_review_submissions +); + +CREATE TABLE IF NOT EXISTS registry_internal.registry_proposal_review_ask_answers ( + authority text NOT NULL, + review_request_id uuid NOT NULL, + ask_id uuid NOT NULL, + action_id text NOT NULL, + proposal_id uuid NOT NULL, + submission_version bigint NOT NULL, + text text CHECK (text IS NULL OR octet_length(text)<=2000), + answered_by text, + answered_at timestamptz NOT NULL, + delivery_key text NOT NULL UNIQUE CHECK (octet_length(delivery_key) BETWEEN 1 AND 128), + delivery_state text NOT NULL CHECK (delivery_state IN ('pending','delivered','refused','superseded')), + attempt_count integer NOT NULL DEFAULT 0 CHECK (attempt_count BETWEEN 0 AND 1000), + next_attempt_at timestamptz NOT NULL DEFAULT transaction_timestamp(), + lease_until timestamptz, + claim_token uuid, + delivery_deadline timestamptz NOT NULL CHECK (delivery_deadline>answered_at), + delivered_at timestamptz, + last_error_code text CHECK (last_error_code IS NULL OR octet_length(last_error_code) BETWEEN 1 AND 128), + detail_erased_at timestamptz, + PRIMARY KEY (authority,review_request_id,ask_id), + UNIQUE (authority,review_request_id,ask_id,action_id,proposal_id,submission_version), + FOREIGN KEY (authority,review_request_id,ask_id,action_id,proposal_id,submission_version) + REFERENCES registry_internal.registry_proposal_review_asks + (authority,review_request_id,ask_id,action_id,proposal_id,submission_version) +); + +CREATE TABLE IF NOT EXISTS registry_internal.registry_proposal_review_ask_files ( + authority text NOT NULL, + review_request_id uuid NOT NULL, + ask_id uuid NOT NULL, + action_id text NOT NULL, + proposal_id uuid NOT NULL, + submission_version bigint NOT NULL, + addition_id uuid NOT NULL, + PRIMARY KEY (action_id,proposal_id,submission_version,addition_id), + FOREIGN KEY (authority,review_request_id,ask_id,action_id,proposal_id,submission_version) + REFERENCES registry_internal.registry_proposal_review_ask_answers + (authority,review_request_id,ask_id,action_id,proposal_id,submission_version), + FOREIGN KEY (action_id,proposal_id,submission_version,addition_id) + REFERENCES registry_internal.registry_proposal_additions + (action_id,proposal_id,submission_version,addition_id) +); diff --git a/crates/registry-breg/tests/generated_identifier_compiler.rs b/crates/registry-breg/tests/generated_identifier_compiler.rs index 0764511d1c..1537935fb3 100644 --- a/crates/registry-breg/tests/generated_identifier_compiler.rs +++ b/crates/registry-breg/tests/generated_identifier_compiler.rs @@ -62,7 +62,7 @@ fn project_value() -> Value { }}, "accessProfiles": {"editor": { "principalClaim": "registry_principal", - "requiredScopes": "unrestricted", + "requiredScopes": ["records:write"], "permissions": {"records": [{ "recordType": "record", "operations": ["create", "get"], @@ -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 = [ @@ -409,7 +469,7 @@ fn fixed_actions_cannot_supply_server_generated_identifiers() { project["accessProfiles"] = json!({"operator": { "default": true, "principalClaim": "registry_principal", - "requiredScopes": "unrestricted", + "requiredScopes": ["records:write"], "permissions": {"actions": [{ "action": "create-record", "operations": ["invoke"], @@ -479,7 +539,7 @@ fn create_effect_bounds_include_server_generated_fields() { project["accessProfiles"] = json!({"operator": { "default": true, "principalClaim": "registry_principal", - "requiredScopes": "unrestricted", + "requiredScopes": ["records:write"], "permissions": {"actions": [{ "action": "create-record", "operations": [operation], diff --git a/crates/registry-breg/tests/golden/membership-access.json b/crates/registry-breg/tests/golden/membership-access.json new file mode 100644 index 0000000000..11ba0cd603 --- /dev/null +++ b/crates/registry-breg/tests/golden/membership-access.json @@ -0,0 +1,113 @@ +{ + "entries": [ + { + "routeId": "records.facility.create", + "recordType": "facility", + "operation": "create", + "profileIds": [ + "steward" + ], + "defaultProfileId": "steward" + }, + { + "routeId": "records.facility.get", + "recordType": "facility", + "operation": "get", + "profileIds": [ + "member", + "steward" + ], + "defaultProfileId": "member" + }, + { + "routeId": "records.facility.lookup", + "recordType": "facility", + "operation": "lookup", + "profileIds": [ + "member" + ], + "defaultProfileId": "member" + }, + { + "routeId": "records.facility.list", + "recordType": "facility", + "operation": "list", + "profileIds": [ + "member" + ], + "defaultProfileId": "member" + }, + { + "routeId": "records.facility.patch", + "recordType": "facility", + "operation": "patch", + "profileIds": [ + "steward" + ], + "defaultProfileId": "steward" + }, + { + "routeId": "records.facility.revisions", + "recordType": "facility", + "operation": "revisions", + "profileIds": [ + "member" + ], + "defaultProfileId": "member" + }, + { + "routeId": "records.facility.snapshot", + "recordType": "facility", + "operation": "snapshot", + "profileIds": [ + "member" + ], + "defaultProfileId": "member" + }, + { + "routeId": "records.membership.create", + "recordType": "membership", + "operation": "create", + "profileIds": [ + "steward" + ], + "defaultProfileId": "steward" + }, + { + "routeId": "records.membership.get", + "recordType": "membership", + "operation": "get", + "profileIds": [ + "steward" + ], + "defaultProfileId": "steward" + }, + { + "routeId": "records.membership.patch", + "recordType": "membership", + "operation": "patch", + "profileIds": [ + "steward" + ], + "defaultProfileId": "steward" + }, + { + "routeId": "records.organization.create", + "recordType": "organization", + "operation": "create", + "profileIds": [ + "steward" + ], + "defaultProfileId": "steward" + }, + { + "routeId": "records.organization.get", + "recordType": "organization", + "operation": "get", + "profileIds": [ + "steward" + ], + "defaultProfileId": "steward" + } + ] +} diff --git a/crates/registry-breg/tests/golden/membership-ddl.json b/crates/registry-breg/tests/golden/membership-ddl.json new file mode 100644 index 0000000000..d4aa0f2e17 --- /dev/null +++ b/crates/registry-breg/tests/golden/membership-ddl.json @@ -0,0 +1,334 @@ +{ + "requiresBtreeGist": false, + "statements": [ + { + "id": "schema.registry_data", + "kind": "schema", + "sql": "CREATE SCHEMA IF NOT EXISTS registry_data" + }, + { + "id": "schema.registry_source", + "kind": "schema", + "sql": "CREATE SCHEMA IF NOT EXISTS registry_source" + }, + { + "id": "schema.registry_derived", + "kind": "schema", + "sql": "CREATE SCHEMA IF NOT EXISTS registry_derived" + }, + { + "id": "schema.registry_context", + "kind": "schema", + "sql": "CREATE SCHEMA IF NOT EXISTS registry_context" + }, + { + "id": "function.registry_context.evaluation_date", + "kind": "function", + "sql": "CREATE OR REPLACE FUNCTION registry_context.evaluation_date()\n RETURNS date\n LANGUAGE sql\n STABLE\n SECURITY INVOKER\n AS $breg_function$\n SELECT NULLIF(current_setting('registry.evaluation_date', true), '')::date\n $breg_function$" + }, + { + "id": "entity.facility.table", + "kind": "table", + "sql": "CREATE TABLE registry_data.\"breg_e_facility_675cdbdae206c49c\" (record_id uuid NOT NULL, record_revision bigint NOT NULL DEFAULT 1 CHECK (record_revision > 0), record_lifecycle text COLLATE pg_catalog.pg_c_utf8 NOT NULL DEFAULT 'active' CHECK (record_lifecycle IN ('active', 'tombstoned')), created_at timestamptz NOT NULL DEFAULT transaction_timestamp(), updated_at timestamptz NOT NULL DEFAULT transaction_timestamp(), active_package_revision text COLLATE pg_catalog.pg_c_utf8 NOT NULL DEFAULT NULLIF(current_setting('registry.active_package_revision', true), '') CHECK (active_package_revision <> ''), PRIMARY KEY (record_id), \"breg_f_facility_label_49700f8f0b0d4a57\" varchar(80) COLLATE pg_catalog.pg_c_utf8 NOT NULL, \"breg_f_facility_organization_c72e96e6196479cc\" uuid NOT NULL)" + }, + { + "id": "entity.membership.table", + "kind": "table", + "sql": "CREATE TABLE registry_data.\"breg_e_membership_a36e7273b8ef4eb1\" (record_id uuid NOT NULL, record_revision bigint NOT NULL DEFAULT 1 CHECK (record_revision > 0), record_lifecycle text COLLATE pg_catalog.pg_c_utf8 NOT NULL DEFAULT 'active' CHECK (record_lifecycle IN ('active', 'tombstoned')), created_at timestamptz NOT NULL DEFAULT transaction_timestamp(), updated_at timestamptz NOT NULL DEFAULT transaction_timestamp(), active_package_revision text COLLATE pg_catalog.pg_c_utf8 NOT NULL DEFAULT NULLIF(current_setting('registry.active_package_revision', true), '') CHECK (active_package_revision <> ''), PRIMARY KEY (record_id), \"breg_f_membership_active_6e662651da1918d2\" boolean NOT NULL, \"breg_f_membership_organization_bfa076d486640343\" uuid NOT NULL, \"breg_f_membership_principal_dbfb37e169be4783\" varchar(80) COLLATE pg_catalog.pg_c_utf8 NOT NULL, \"breg_f_membership_private_note_5a8d02ceb53dd0bd\" varchar(80) COLLATE pg_catalog.pg_c_utf8)" + }, + { + "id": "entity.organization.table", + "kind": "table", + "sql": "CREATE TABLE registry_data.\"breg_e_organization_6ccb51e3b2202a71\" (record_id uuid NOT NULL, record_revision bigint NOT NULL DEFAULT 1 CHECK (record_revision > 0), record_lifecycle text COLLATE pg_catalog.pg_c_utf8 NOT NULL DEFAULT 'active' CHECK (record_lifecycle IN ('active', 'tombstoned')), created_at timestamptz NOT NULL DEFAULT transaction_timestamp(), updated_at timestamptz NOT NULL DEFAULT transaction_timestamp(), active_package_revision text COLLATE pg_catalog.pg_c_utf8 NOT NULL DEFAULT NULLIF(current_setting('registry.active_package_revision', true), '') CHECK (active_package_revision <> ''), PRIMARY KEY (record_id), \"breg_f_organization_name_39e5047e3f964468\" varchar(80) COLLATE pg_catalog.pg_c_utf8)" + }, + { + "id": "entity.facility.reference-lifecycle.column", + "kind": "column", + "sql": "ALTER TABLE registry_data.\"breg_e_facility_675cdbdae206c49c\" ADD COLUMN record_reference_lifecycle text COLLATE pg_catalog.pg_c_utf8\n GENERATED ALWAYS AS (CASE WHEN record_lifecycle = 'active' THEN 'active'::text ELSE NULL::text END) STORED" + }, + { + "id": "entity.membership.reference-lifecycle.column", + "kind": "column", + "sql": "ALTER TABLE registry_data.\"breg_e_membership_a36e7273b8ef4eb1\" ADD COLUMN record_reference_lifecycle text COLLATE pg_catalog.pg_c_utf8\n GENERATED ALWAYS AS (CASE WHEN record_lifecycle = 'active' THEN 'active'::text ELSE NULL::text END) STORED" + }, + { + "id": "entity.organization.reference-lifecycle.key", + "kind": "constraint", + "sql": "ALTER TABLE registry_data.\"breg_e_organization_6ccb51e3b2202a71\" ADD CONSTRAINT \"breg_rk_organization_1a9958900e5456b0\" UNIQUE (record_id, record_lifecycle)" + }, + { + "id": "entity.facility.field.organization.reference", + "kind": "reference", + "sql": "ALTER TABLE registry_data.\"breg_e_facility_675cdbdae206c49c\" ADD CONSTRAINT \"breg_r_facility_organization_d6e2e76fcb68e418\" FOREIGN KEY (\"breg_f_facility_organization_c72e96e6196479cc\") REFERENCES registry_data.\"breg_e_organization_6ccb51e3b2202a71\" (record_id) ON DELETE RESTRICT" + }, + { + "id": "entity.facility.field.organization.active-reference", + "kind": "reference", + "sql": "ALTER TABLE registry_data.\"breg_e_facility_675cdbdae206c49c\" NO FORCE ROW LEVEL SECURITY;\nALTER TABLE registry_data.\"breg_e_organization_6ccb51e3b2202a71\" NO FORCE ROW LEVEL SECURITY;\nALTER TABLE registry_data.\"breg_e_facility_675cdbdae206c49c\" ADD CONSTRAINT \"breg_ar_facility_organization_c2ee3822a6f70011\" FOREIGN KEY (\"breg_f_facility_organization_c72e96e6196479cc\", record_reference_lifecycle) REFERENCES registry_data.\"breg_e_organization_6ccb51e3b2202a71\" (record_id, record_lifecycle) MATCH SIMPLE ON UPDATE NO ACTION ON DELETE RESTRICT;\nALTER TABLE registry_data.\"breg_e_facility_675cdbdae206c49c\" FORCE ROW LEVEL SECURITY;\nALTER TABLE registry_data.\"breg_e_organization_6ccb51e3b2202a71\" FORCE ROW LEVEL SECURITY" + }, + { + "id": "entity.facility.index.reference:organization", + "kind": "index", + "sql": "CREATE INDEX \"breg_ri_facility_organization_a21122438500a54c\" ON registry_data.\"breg_e_facility_675cdbdae206c49c\" (\"breg_f_facility_organization_c72e96e6196479cc\")" + }, + { + "id": "entity.membership.field.organization.reference", + "kind": "reference", + "sql": "ALTER TABLE registry_data.\"breg_e_membership_a36e7273b8ef4eb1\" ADD CONSTRAINT \"breg_r_membership_organization_faa70a2468df1cb1\" FOREIGN KEY (\"breg_f_membership_organization_bfa076d486640343\") REFERENCES registry_data.\"breg_e_organization_6ccb51e3b2202a71\" (record_id) ON DELETE RESTRICT" + }, + { + "id": "entity.membership.field.organization.active-reference", + "kind": "reference", + "sql": "ALTER TABLE registry_data.\"breg_e_membership_a36e7273b8ef4eb1\" NO FORCE ROW LEVEL SECURITY;\nALTER TABLE registry_data.\"breg_e_organization_6ccb51e3b2202a71\" NO FORCE ROW LEVEL SECURITY;\nALTER TABLE registry_data.\"breg_e_membership_a36e7273b8ef4eb1\" ADD CONSTRAINT \"breg_ar_membership_organization_09291f896d3ebb10\" FOREIGN KEY (\"breg_f_membership_organization_bfa076d486640343\", record_reference_lifecycle) REFERENCES registry_data.\"breg_e_organization_6ccb51e3b2202a71\" (record_id, record_lifecycle) MATCH SIMPLE ON UPDATE NO ACTION ON DELETE RESTRICT;\nALTER TABLE registry_data.\"breg_e_membership_a36e7273b8ef4eb1\" FORCE ROW LEVEL SECURITY;\nALTER TABLE registry_data.\"breg_e_organization_6ccb51e3b2202a71\" FORCE ROW LEVEL SECURITY" + }, + { + "id": "entity.membership.index.membership-principal-key", + "kind": "index", + "sql": "CREATE INDEX \"breg_i_membership_membership_principal_key_71354dc018b3a225\" ON registry_data.\"breg_e_membership_a36e7273b8ef4eb1\" (\"breg_f_membership_principal_dbfb37e169be4783\", \"breg_f_membership_organization_bfa076d486640343\", \"breg_f_membership_active_6e662651da1918d2\", record_id)" + }, + { + "id": "entity.membership.index.reference:organization", + "kind": "index", + "sql": "CREATE INDEX \"breg_ri_membership_organization_d0fbd830aaf560b4\" ON registry_data.\"breg_e_membership_a36e7273b8ef4eb1\" (\"breg_f_membership_organization_bfa076d486640343\")" + }, + { + "id": "entity.membership.membership.key-index", + "kind": "index", + "sql": "CREATE UNIQUE INDEX \"breg_membership_key_b9ee6c3037\" ON registry_data.\"breg_e_membership_a36e7273b8ef4eb1\" (\"breg_f_membership_organization_bfa076d486640343\", \"breg_f_membership_principal_dbfb37e169be4783\") WHERE \"breg_f_membership_active_6e662651da1918d2\" IS TRUE AND record_lifecycle = 'active'" + }, + { + "id": "registry_context.membership_7b967b5ec89a5c63ab8056cd", + "kind": "function", + "sql": "CREATE FUNCTION registry_context.\"membership_7b967b5ec89a5c63ab8056cd\"(uuid) RETURNS boolean LANGUAGE plpgsql STABLE STRICT SECURITY INVOKER SET search_path = pg_catalog AS 'DECLARE prior_marker text := current_setting(''registry.membership_probe'', true); authorized boolean; BEGIN PERFORM set_config(''registry.membership_probe'', ''membership_7b967b5ec89a5c63ab8056cd'', true); SELECT EXISTS (SELECT 1 FROM registry_data.\"breg_e_membership_a36e7273b8ef4eb1\" AS membership WHERE membership.record_lifecycle = ''active'' AND membership.\"breg_f_membership_principal_dbfb37e169be4783\" = NULLIF(current_setting(''registry.principal'', true), '''') AND membership.\"breg_f_membership_active_6e662651da1918d2\" IS TRUE AND membership.\"breg_f_membership_organization_bfa076d486640343\" = $1) INTO authorized; PERFORM set_config(''registry.membership_probe'', COALESCE(prior_marker, ''''), true); RETURN authorized; EXCEPTION WHEN OTHERS THEN RAISE; END'" + }, + { + "id": "entity.facility.rls.enable", + "kind": "row_security", + "sql": "ALTER TABLE registry_data.\"breg_e_facility_675cdbdae206c49c\" ENABLE ROW LEVEL SECURITY" + }, + { + "id": "entity.facility.rls.force", + "kind": "row_security", + "sql": "ALTER TABLE registry_data.\"breg_e_facility_675cdbdae206c49c\" FORCE ROW LEVEL SECURITY" + }, + { + "id": "entity.facility.policy.registry_rls_select_b56c984fa34e60b58e32e7d3", + "kind": "policy", + "sql": "CREATE POLICY \"registry_rls_select_b56c984fa34e60b58e32e7d3\" ON registry_data.\"breg_e_facility_675cdbdae206c49c\" FOR SELECT USING ((NULLIF(current_setting('registry.access_profile', true), '') = 'member' AND NULLIF(current_setting('registry.principal', true), '') IS NOT NULL AND jsonb_typeof(NULLIF(current_setting('registry.row_boundaries', true), '')::jsonb) = 'array' AND jsonb_array_length(NULLIF(current_setting('registry.row_boundaries', true), '')::jsonb) = 0 AND registry_context.\"membership_7b967b5ec89a5c63ab8056cd\"(\"breg_f_facility_organization_c72e96e6196479cc\")) AND (record_lifecycle = 'active'));\nCOMMENT ON POLICY \"registry_rls_select_b56c984fa34e60b58e32e7d3\" ON registry_data.\"breg_e_facility_675cdbdae206c49c\" IS 'breg/policy/v1/1ff0fa085876122e11f4c5a802c2e8e4e900a21cbc448d1624bf307fe49fae5f'" + }, + { + "id": "entity.facility.policy.registry_rls_select_bd688fd36cf3a53a01382a56", + "kind": "policy", + "sql": "CREATE POLICY \"registry_rls_select_bd688fd36cf3a53a01382a56\" ON registry_data.\"breg_e_facility_675cdbdae206c49c\" FOR SELECT USING ((NULLIF(current_setting('registry.access_profile', true), '') = 'steward' AND NULLIF(current_setting('registry.principal', true), '') IS NOT NULL AND jsonb_typeof(NULLIF(current_setting('registry.row_boundaries', true), '')::jsonb) = 'array' AND jsonb_array_length(NULLIF(current_setting('registry.row_boundaries', true), '')::jsonb) = 0) AND (record_lifecycle = 'active'));\nCOMMENT ON POLICY \"registry_rls_select_bd688fd36cf3a53a01382a56\" ON registry_data.\"breg_e_facility_675cdbdae206c49c\" IS 'breg/policy/v1/c63db1bfd0fa09289779ea867bf5407db8ce9ae4d09bc56efa120a2aab40c367'" + }, + { + "id": "entity.facility.policy.registry_rls_insert_77687d5ac1f8badf901ee933", + "kind": "policy", + "sql": "CREATE POLICY \"registry_rls_insert_77687d5ac1f8badf901ee933\" ON registry_data.\"breg_e_facility_675cdbdae206c49c\" FOR INSERT WITH CHECK ((NULLIF(current_setting('registry.access_profile', true), '') = 'steward' AND NULLIF(current_setting('registry.principal', true), '') IS NOT NULL AND jsonb_typeof(NULLIF(current_setting('registry.row_boundaries', true), '')::jsonb) = 'array' AND jsonb_array_length(NULLIF(current_setting('registry.row_boundaries', true), '')::jsonb) = 0) AND record_lifecycle = 'active');\nCOMMENT ON POLICY \"registry_rls_insert_77687d5ac1f8badf901ee933\" ON registry_data.\"breg_e_facility_675cdbdae206c49c\" IS 'breg/policy/v1/e16b1d51effd9575d791229c843740a5bdbbb37c5697398cafa369f021e6539e'" + }, + { + "id": "entity.facility.policy.registry_rls_update_f6e327e7ea9457483f3eabeb", + "kind": "policy", + "sql": "CREATE POLICY \"registry_rls_update_f6e327e7ea9457483f3eabeb\" ON registry_data.\"breg_e_facility_675cdbdae206c49c\" FOR UPDATE USING ((NULLIF(current_setting('registry.access_profile', true), '') = 'steward' AND NULLIF(current_setting('registry.principal', true), '') IS NOT NULL AND jsonb_typeof(NULLIF(current_setting('registry.row_boundaries', true), '')::jsonb) = 'array' AND jsonb_array_length(NULLIF(current_setting('registry.row_boundaries', true), '')::jsonb) = 0) AND record_lifecycle = 'active') WITH CHECK ((NULLIF(current_setting('registry.access_profile', true), '') = 'steward' AND NULLIF(current_setting('registry.principal', true), '') IS NOT NULL AND jsonb_typeof(NULLIF(current_setting('registry.row_boundaries', true), '')::jsonb) = 'array' AND jsonb_array_length(NULLIF(current_setting('registry.row_boundaries', true), '')::jsonb) = 0) AND record_lifecycle = 'active');\nCOMMENT ON POLICY \"registry_rls_update_f6e327e7ea9457483f3eabeb\" ON registry_data.\"breg_e_facility_675cdbdae206c49c\" IS 'breg/policy/v1/6202ed55d51b18cee0233559fbbab14f840ad223c4986048cb2e213d8c851643'" + }, + { + "id": "entity.membership.rls.enable", + "kind": "row_security", + "sql": "ALTER TABLE registry_data.\"breg_e_membership_a36e7273b8ef4eb1\" ENABLE ROW LEVEL SECURITY" + }, + { + "id": "entity.membership.rls.force", + "kind": "row_security", + "sql": "ALTER TABLE registry_data.\"breg_e_membership_a36e7273b8ef4eb1\" FORCE ROW LEVEL SECURITY" + }, + { + "id": "entity.membership.policy.registry_rls_select_2c193a25886b5ebec5bba2e5", + "kind": "policy", + "sql": "CREATE POLICY \"registry_rls_select_2c193a25886b5ebec5bba2e5\" ON registry_data.\"breg_e_membership_a36e7273b8ef4eb1\" FOR SELECT USING ((NULLIF(current_setting('registry.access_profile', true), '') = 'steward' AND NULLIF(current_setting('registry.principal', true), '') IS NOT NULL AND jsonb_typeof(NULLIF(current_setting('registry.row_boundaries', true), '')::jsonb) = 'array' AND jsonb_array_length(NULLIF(current_setting('registry.row_boundaries', true), '')::jsonb) = 0) AND (record_lifecycle = 'active'));\nCOMMENT ON POLICY \"registry_rls_select_2c193a25886b5ebec5bba2e5\" ON registry_data.\"breg_e_membership_a36e7273b8ef4eb1\" IS 'breg/policy/v1/97e2451b6e98fd3dbebea85516fc4ad69ffcacddd4fe013feb4ca0f4afbe6e39'" + }, + { + "id": "entity.membership.policy.registry_rls_insert_edd73113291f3d42ac72c32f", + "kind": "policy", + "sql": "CREATE POLICY \"registry_rls_insert_edd73113291f3d42ac72c32f\" ON registry_data.\"breg_e_membership_a36e7273b8ef4eb1\" FOR INSERT WITH CHECK ((NULLIF(current_setting('registry.access_profile', true), '') = 'steward' AND NULLIF(current_setting('registry.principal', true), '') IS NOT NULL AND jsonb_typeof(NULLIF(current_setting('registry.row_boundaries', true), '')::jsonb) = 'array' AND jsonb_array_length(NULLIF(current_setting('registry.row_boundaries', true), '')::jsonb) = 0) AND record_lifecycle = 'active');\nCOMMENT ON POLICY \"registry_rls_insert_edd73113291f3d42ac72c32f\" ON registry_data.\"breg_e_membership_a36e7273b8ef4eb1\" IS 'breg/policy/v1/8a1b6e5748d1e2d6fb068e08a6a3bf0d3d2d00be5f52c15c632e11ae6067410c'" + }, + { + "id": "entity.membership.policy.registry_rls_update_f37197225c94dab6ad410cc1", + "kind": "policy", + "sql": "CREATE POLICY \"registry_rls_update_f37197225c94dab6ad410cc1\" ON registry_data.\"breg_e_membership_a36e7273b8ef4eb1\" FOR UPDATE USING ((NULLIF(current_setting('registry.access_profile', true), '') = 'steward' AND NULLIF(current_setting('registry.principal', true), '') IS NOT NULL AND jsonb_typeof(NULLIF(current_setting('registry.row_boundaries', true), '')::jsonb) = 'array' AND jsonb_array_length(NULLIF(current_setting('registry.row_boundaries', true), '')::jsonb) = 0) AND record_lifecycle = 'active') WITH CHECK ((NULLIF(current_setting('registry.access_profile', true), '') = 'steward' AND NULLIF(current_setting('registry.principal', true), '') IS NOT NULL AND jsonb_typeof(NULLIF(current_setting('registry.row_boundaries', true), '')::jsonb) = 'array' AND jsonb_array_length(NULLIF(current_setting('registry.row_boundaries', true), '')::jsonb) = 0) AND record_lifecycle = 'active');\nCOMMENT ON POLICY \"registry_rls_update_f37197225c94dab6ad410cc1\" ON registry_data.\"breg_e_membership_a36e7273b8ef4eb1\" IS 'breg/policy/v1/82cba119d6cb474654f121cd266efc52f8c8f1d75d40721fc25f8ca0876108ca'" + }, + { + "id": "entity.organization.rls.enable", + "kind": "row_security", + "sql": "ALTER TABLE registry_data.\"breg_e_organization_6ccb51e3b2202a71\" ENABLE ROW LEVEL SECURITY" + }, + { + "id": "entity.organization.rls.force", + "kind": "row_security", + "sql": "ALTER TABLE registry_data.\"breg_e_organization_6ccb51e3b2202a71\" FORCE ROW LEVEL SECURITY" + }, + { + "id": "entity.organization.policy.registry_rls_select_fc68ada80db4374538d917df", + "kind": "policy", + "sql": "CREATE POLICY \"registry_rls_select_fc68ada80db4374538d917df\" ON registry_data.\"breg_e_organization_6ccb51e3b2202a71\" FOR SELECT USING ((NULLIF(current_setting('registry.access_profile', true), '') = 'steward' AND NULLIF(current_setting('registry.principal', true), '') IS NOT NULL AND jsonb_typeof(NULLIF(current_setting('registry.row_boundaries', true), '')::jsonb) = 'array' AND jsonb_array_length(NULLIF(current_setting('registry.row_boundaries', true), '')::jsonb) = 0) AND (record_lifecycle = 'active'));\nCOMMENT ON POLICY \"registry_rls_select_fc68ada80db4374538d917df\" ON registry_data.\"breg_e_organization_6ccb51e3b2202a71\" IS 'breg/policy/v1/ab8ebf2e79f6bd405b4c210d480892f7895ccf717411fb87bec5c0fd031a6e53'" + }, + { + "id": "entity.organization.policy.registry_rls_insert_de59d694cebbb215bd3f6b9b", + "kind": "policy", + "sql": "CREATE POLICY \"registry_rls_insert_de59d694cebbb215bd3f6b9b\" ON registry_data.\"breg_e_organization_6ccb51e3b2202a71\" FOR INSERT WITH CHECK ((NULLIF(current_setting('registry.access_profile', true), '') = 'steward' AND NULLIF(current_setting('registry.principal', true), '') IS NOT NULL AND jsonb_typeof(NULLIF(current_setting('registry.row_boundaries', true), '')::jsonb) = 'array' AND jsonb_array_length(NULLIF(current_setting('registry.row_boundaries', true), '')::jsonb) = 0) AND record_lifecycle = 'active');\nCOMMENT ON POLICY \"registry_rls_insert_de59d694cebbb215bd3f6b9b\" ON registry_data.\"breg_e_organization_6ccb51e3b2202a71\" IS 'breg/policy/v1/62a79ddf5f7342a15d6ac20c38128d9ca52aae7bc7f215733a964bd0f3b7c9be'" + }, + { + "id": "entity.facility.source-view", + "kind": "view", + "sql": "CREATE VIEW registry_source.\"facility\"\n WITH (security_invoker=true)\n AS SELECT record_id AS \"id\", \"breg_f_facility_organization_c72e96e6196479cc\" AS \"organization\", \"breg_f_facility_label_49700f8f0b0d4a57\" AS \"label\"\n FROM registry_data.\"breg_e_facility_675cdbdae206c49c\"\n WHERE record_lifecycle = 'active'" + }, + { + "id": "entity.membership.source-view", + "kind": "view", + "sql": "CREATE VIEW registry_source.\"membership\"\n WITH (security_invoker=true)\n AS SELECT record_id AS \"id\", \"breg_f_membership_organization_bfa076d486640343\" AS \"organization\", \"breg_f_membership_principal_dbfb37e169be4783\" AS \"principal\", \"breg_f_membership_active_6e662651da1918d2\" AS \"active\", \"breg_f_membership_private_note_5a8d02ceb53dd0bd\" AS \"private_note\"\n FROM registry_data.\"breg_e_membership_a36e7273b8ef4eb1\"\n WHERE record_lifecycle = 'active'" + }, + { + "id": "entity.organization.source-view", + "kind": "view", + "sql": "CREATE VIEW registry_source.\"organization\"\n WITH (security_invoker=true)\n AS SELECT record_id AS \"id\", \"breg_f_organization_name_39e5047e3f964468\" AS \"name\"\n FROM registry_data.\"breg_e_organization_6ccb51e3b2202a71\"\n WHERE record_lifecycle = 'active'" + } + ], + "tables": [ + { + "entityId": "facility", + "physicalName": "breg_e_facility_675cdbdae206c49c", + "runtimePrivileges": [ + "select", + "insert", + "update" + ], + "policies": [ + { + "name": "registry_rls_select_b56c984fa34e60b58e32e7d3", + "command": "select", + "accessProfile": "member", + "usingExpression": "(NULLIF(current_setting('registry.access_profile', true), '') = 'member' AND NULLIF(current_setting('registry.principal', true), '') IS NOT NULL AND jsonb_typeof(NULLIF(current_setting('registry.row_boundaries', true), '')::jsonb) = 'array' AND jsonb_array_length(NULLIF(current_setting('registry.row_boundaries', true), '')::jsonb) = 0 AND registry_context.\"membership_7b967b5ec89a5c63ab8056cd\"(\"breg_f_facility_organization_c72e96e6196479cc\")) AND (record_lifecycle = 'active')" + }, + { + "name": "registry_rls_select_bd688fd36cf3a53a01382a56", + "command": "select", + "accessProfile": "steward", + "usingExpression": "(NULLIF(current_setting('registry.access_profile', true), '') = 'steward' AND NULLIF(current_setting('registry.principal', true), '') IS NOT NULL AND jsonb_typeof(NULLIF(current_setting('registry.row_boundaries', true), '')::jsonb) = 'array' AND jsonb_array_length(NULLIF(current_setting('registry.row_boundaries', true), '')::jsonb) = 0) AND (record_lifecycle = 'active')" + }, + { + "name": "registry_rls_insert_77687d5ac1f8badf901ee933", + "command": "insert", + "accessProfile": "steward", + "checkExpression": "(NULLIF(current_setting('registry.access_profile', true), '') = 'steward' AND NULLIF(current_setting('registry.principal', true), '') IS NOT NULL AND jsonb_typeof(NULLIF(current_setting('registry.row_boundaries', true), '')::jsonb) = 'array' AND jsonb_array_length(NULLIF(current_setting('registry.row_boundaries', true), '')::jsonb) = 0) AND record_lifecycle = 'active'" + }, + { + "name": "registry_rls_update_f6e327e7ea9457483f3eabeb", + "command": "update", + "accessProfile": "steward", + "usingExpression": "(NULLIF(current_setting('registry.access_profile', true), '') = 'steward' AND NULLIF(current_setting('registry.principal', true), '') IS NOT NULL AND jsonb_typeof(NULLIF(current_setting('registry.row_boundaries', true), '')::jsonb) = 'array' AND jsonb_array_length(NULLIF(current_setting('registry.row_boundaries', true), '')::jsonb) = 0) AND record_lifecycle = 'active'", + "checkExpression": "(NULLIF(current_setting('registry.access_profile', true), '') = 'steward' AND NULLIF(current_setting('registry.principal', true), '') IS NOT NULL AND jsonb_typeof(NULLIF(current_setting('registry.row_boundaries', true), '')::jsonb) = 'array' AND jsonb_array_length(NULLIF(current_setting('registry.row_boundaries', true), '')::jsonb) = 0) AND record_lifecycle = 'active'" + } + ] + }, + { + "entityId": "membership", + "physicalName": "breg_e_membership_a36e7273b8ef4eb1", + "runtimePrivileges": [ + "select", + "insert", + "update" + ], + "policies": [ + { + "name": "registry_rls_select_2c193a25886b5ebec5bba2e5", + "command": "select", + "accessProfile": "steward", + "usingExpression": "(NULLIF(current_setting('registry.access_profile', true), '') = 'steward' AND NULLIF(current_setting('registry.principal', true), '') IS NOT NULL AND jsonb_typeof(NULLIF(current_setting('registry.row_boundaries', true), '')::jsonb) = 'array' AND jsonb_array_length(NULLIF(current_setting('registry.row_boundaries', true), '')::jsonb) = 0) AND (record_lifecycle = 'active')" + }, + { + "name": "registry_rls_insert_edd73113291f3d42ac72c32f", + "command": "insert", + "accessProfile": "steward", + "checkExpression": "(NULLIF(current_setting('registry.access_profile', true), '') = 'steward' AND NULLIF(current_setting('registry.principal', true), '') IS NOT NULL AND jsonb_typeof(NULLIF(current_setting('registry.row_boundaries', true), '')::jsonb) = 'array' AND jsonb_array_length(NULLIF(current_setting('registry.row_boundaries', true), '')::jsonb) = 0) AND record_lifecycle = 'active'" + }, + { + "name": "registry_rls_update_f37197225c94dab6ad410cc1", + "command": "update", + "accessProfile": "steward", + "usingExpression": "(NULLIF(current_setting('registry.access_profile', true), '') = 'steward' AND NULLIF(current_setting('registry.principal', true), '') IS NOT NULL AND jsonb_typeof(NULLIF(current_setting('registry.row_boundaries', true), '')::jsonb) = 'array' AND jsonb_array_length(NULLIF(current_setting('registry.row_boundaries', true), '')::jsonb) = 0) AND record_lifecycle = 'active'", + "checkExpression": "(NULLIF(current_setting('registry.access_profile', true), '') = 'steward' AND NULLIF(current_setting('registry.principal', true), '') IS NOT NULL AND jsonb_typeof(NULLIF(current_setting('registry.row_boundaries', true), '')::jsonb) = 'array' AND jsonb_array_length(NULLIF(current_setting('registry.row_boundaries', true), '')::jsonb) = 0) AND record_lifecycle = 'active'" + }, + { + "name": "registry_membership_7b967b5ec89a5c63ab8056cd", + "command": "select", + "accessProfile": "member", + "appliesTo": "runtime", + "usingExpression": "(NULLIF(current_setting('registry.membership_probe', true), '') = 'membership_7b967b5ec89a5c63ab8056cd' AND NULLIF(current_setting('registry.access_profile', true), '') = 'member') AND (\"breg_e_membership_a36e7273b8ef4eb1\".record_lifecycle = 'active' AND \"breg_e_membership_a36e7273b8ef4eb1\".\"breg_f_membership_principal_dbfb37e169be4783\" = NULLIF(current_setting('registry.principal', true), '') AND \"breg_e_membership_a36e7273b8ef4eb1\".\"breg_f_membership_active_6e662651da1918d2\" IS TRUE)" + } + ] + }, + { + "entityId": "organization", + "physicalName": "breg_e_organization_6ccb51e3b2202a71", + "runtimePrivileges": [ + "select", + "insert" + ], + "policies": [ + { + "name": "registry_rls_select_fc68ada80db4374538d917df", + "command": "select", + "accessProfile": "steward", + "usingExpression": "(NULLIF(current_setting('registry.access_profile', true), '') = 'steward' AND NULLIF(current_setting('registry.principal', true), '') IS NOT NULL AND jsonb_typeof(NULLIF(current_setting('registry.row_boundaries', true), '')::jsonb) = 'array' AND jsonb_array_length(NULLIF(current_setting('registry.row_boundaries', true), '')::jsonb) = 0) AND (record_lifecycle = 'active')" + }, + { + "name": "registry_rls_insert_de59d694cebbb215bd3f6b9b", + "command": "insert", + "accessProfile": "steward", + "checkExpression": "(NULLIF(current_setting('registry.access_profile', true), '') = 'steward' AND NULLIF(current_setting('registry.principal', true), '') IS NOT NULL AND jsonb_typeof(NULLIF(current_setting('registry.row_boundaries', true), '')::jsonb) = 'array' AND jsonb_array_length(NULLIF(current_setting('registry.row_boundaries', true), '')::jsonb) = 0) AND record_lifecycle = 'active'" + } + ] + } + ], + "views": [ + { + "id": "entity.facility.source", + "schema": "registry_source", + "name": "facility", + "runtimePrivileges": [ + "select" + ] + }, + { + "id": "entity.membership.source", + "schema": "registry_source", + "name": "membership", + "runtimePrivileges": [ + "select" + ] + }, + { + "id": "entity.organization.source", + "schema": "registry_source", + "name": "organization", + "runtimePrivileges": [ + "select" + ] + } + ], + "functions": [ + { + "id": "registry_context.evaluation_date", + "schema": "registry_context", + "name": "evaluation_date", + "arguments": "", + "runtimeExecute": true + }, + { + "id": "registry_context.membership_7b967b5ec89a5c63ab8056cd", + "schema": "registry_context", + "name": "membership_7b967b5ec89a5c63ab8056cd", + "arguments": "uuid", + "runtimeExecute": true + } + ] +} diff --git a/crates/registry-breg/tests/golden/membership-ddl.sha256 b/crates/registry-breg/tests/golden/membership-ddl.sha256 new file mode 100644 index 0000000000..a8869ac11e --- /dev/null +++ b/crates/registry-breg/tests/golden/membership-ddl.sha256 @@ -0,0 +1 @@ +25af323027e0ab299822ff5886642398997c8b5ad4b4bbee6f377ecbb800c735 diff --git a/crates/registry-breg/tests/golden/membership-revision.txt b/crates/registry-breg/tests/golden/membership-revision.txt new file mode 100644 index 0000000000..db58a08a58 --- /dev/null +++ b/crates/registry-breg/tests/golden/membership-revision.txt @@ -0,0 +1 @@ +sha256:4395d39189ea8825194621cdbf291fcf05effc691ca5caff0b35703120edc0a1 diff --git a/crates/registry-breg/tests/golden/membership_refusals.json b/crates/registry-breg/tests/golden/membership_refusals.json new file mode 100644 index 0000000000..818142c647 --- /dev/null +++ b/crates/registry-breg/tests/golden/membership_refusals.json @@ -0,0 +1,336 @@ +{ + "development-availability": { + "body": { + "code": "resource.not-found", + "detail": "The requested resource was not found.", + "failedCheck": "membership", + "status": 404, + "title": "Not Found", + "traceId": "00000000000000000000000000000000", + "type": "https://id.registrystack.org/problems/registry-breg/resource/not-found" + }, + "headers": { + "cache-control": "no-store", + "content-length": "263", + "content-security-policy": "default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:; connect-src 'self'; object-src 'none'; frame-ancestors 'none'", + "content-type": "application/problem+json", + "cross-origin-opener-policy": "same-origin", + "permissions-policy": "camera=(), microphone=(), geolocation=(), payment=(), usb=(), browsing-topics=()", + "referrer-policy": "no-referrer", + "registry-posture": "development", + "strict-transport-security": "max-age=63072000; includeSubDomains", + "x-content-type-options": "nosniff", + "x-frame-options": "DENY" + }, + "status": 404 + }, + "development-availability-claim": { + "body": { + "code": "resource.not-found", + "detail": "The requested resource was not found.", + "failedCheck": "row-boundary", + "status": 404, + "title": "Not Found", + "traceId": "00000000000000000000000000000000", + "type": "https://id.registrystack.org/problems/registry-breg/resource/not-found" + }, + "headers": { + "cache-control": "no-store", + "content-length": "265", + "content-security-policy": "default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:; connect-src 'self'; object-src 'none'; frame-ancestors 'none'", + "content-type": "application/problem+json", + "cross-origin-opener-policy": "same-origin", + "permissions-policy": "camera=(), microphone=(), geolocation=(), payment=(), usb=(), browsing-topics=()", + "referrer-policy": "no-referrer", + "registry-posture": "development", + "strict-transport-security": "max-age=63072000; includeSubDomains", + "x-content-type-options": "nosniff", + "x-frame-options": "DENY" + }, + "status": 404 + }, + "development-availability-missing": { + "body": { + "code": "resource.not-found", + "detail": "The requested resource was not found.", + "failedCheck": "visibility", + "status": 404, + "title": "Not Found", + "traceId": "00000000000000000000000000000000", + "type": "https://id.registrystack.org/problems/registry-breg/resource/not-found" + }, + "headers": { + "cache-control": "no-store", + "content-length": "263", + "content-security-policy": "default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:; connect-src 'self'; object-src 'none'; frame-ancestors 'none'", + "content-type": "application/problem+json", + "cross-origin-opener-policy": "same-origin", + "permissions-policy": "camera=(), microphone=(), geolocation=(), payment=(), usb=(), browsing-topics=()", + "referrer-policy": "no-referrer", + "registry-posture": "development", + "strict-transport-security": "max-age=63072000; includeSubDomains", + "x-content-type-options": "nosniff", + "x-frame-options": "DENY" + }, + "status": 404 + }, + "development-create-claim": { + "body": { + "code": "write.outside-boundary", + "detail": "The write falls outside what the selected access profile may write: its row boundary or a disclosure condition.", + "failedCheck": "row-boundary", + "status": 403, + "title": "Forbidden", + "traceId": "00000000000000000000000000000000", + "type": "https://id.registrystack.org/problems/registry-breg/write/outside-boundary" + }, + "headers": { + "cache-control": "no-store", + "content-length": "347", + "content-security-policy": "default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:; connect-src 'self'; object-src 'none'; frame-ancestors 'none'", + "content-type": "application/problem+json", + "cross-origin-opener-policy": "same-origin", + "permissions-policy": "camera=(), microphone=(), geolocation=(), payment=(), usb=(), browsing-topics=()", + "referrer-policy": "no-referrer", + "registry-posture": "development", + "strict-transport-security": "max-age=63072000; includeSubDomains", + "x-content-type-options": "nosniff", + "x-frame-options": "DENY" + }, + "status": 403 + }, + "development-create-missing": { + "body": { + "code": "write.outside-boundary", + "detail": "The write falls outside what the selected access profile may write: its row boundary or a disclosure condition.", + "failedCheck": "membership", + "status": 403, + "title": "Forbidden", + "traceId": "00000000000000000000000000000000", + "type": "https://id.registrystack.org/problems/registry-breg/write/outside-boundary" + }, + "headers": { + "cache-control": "no-store", + "content-length": "345", + "content-security-policy": "default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:; connect-src 'self'; object-src 'none'; frame-ancestors 'none'", + "content-type": "application/problem+json", + "cross-origin-opener-policy": "same-origin", + "permissions-policy": "camera=(), microphone=(), geolocation=(), payment=(), usb=(), browsing-topics=()", + "referrer-policy": "no-referrer", + "registry-posture": "development", + "strict-transport-security": "max-age=63072000; includeSubDomains", + "x-content-type-options": "nosniff", + "x-frame-options": "DENY" + }, + "status": 403 + }, + "development-generic-precondition": { + "body": { + "code": "precondition.failed", + "detail": "The mutation precondition failed.", + "status": 412, + "title": "Precondition Failed", + "traceId": "00000000000000000000000000000000", + "type": "https://id.registrystack.org/problems/registry-breg/precondition/failed" + }, + "headers": { + "cache-control": "no-store", + "content-length": "244", + "content-security-policy": "default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:; connect-src 'self'; object-src 'none'; frame-ancestors 'none'", + "content-type": "application/problem+json", + "cross-origin-opener-policy": "same-origin", + "permissions-policy": "camera=(), microphone=(), geolocation=(), payment=(), usb=(), browsing-topics=()", + "referrer-policy": "no-referrer", + "registry-posture": "development", + "strict-transport-security": "max-age=63072000; includeSubDomains", + "x-content-type-options": "nosniff", + "x-frame-options": "DENY" + }, + "status": 412 + }, + "development-observed-precondition": { + "body": { + "code": "precondition.failed", + "detail": "The mutation precondition failed.", + "status": 412, + "title": "Precondition Failed", + "traceId": "00000000000000000000000000000000", + "type": "https://id.registrystack.org/problems/registry-breg/precondition/failed" + }, + "headers": { + "cache-control": "no-store", + "content-length": "244", + "content-security-policy": "default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:; connect-src 'self'; object-src 'none'; frame-ancestors 'none'", + "content-type": "application/problem+json", + "cross-origin-opener-policy": "same-origin", + "permissions-policy": "camera=(), microphone=(), geolocation=(), payment=(), usb=(), browsing-topics=()", + "referrer-policy": "no-referrer", + "registry-posture": "development", + "strict-transport-security": "max-age=63072000; includeSubDomains", + "x-content-type-options": "nosniff", + "x-frame-options": "DENY" + }, + "status": 412 + }, + "production-availability": { + "body": { + "code": "resource.not-found", + "detail": "The requested resource was not found.", + "status": 404, + "title": "Not Found", + "traceId": "00000000000000000000000000000000", + "type": "https://id.registrystack.org/problems/registry-breg/resource/not-found" + }, + "headers": { + "cache-control": "no-store", + "content-length": "236", + "content-security-policy": "default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:; connect-src 'self'; object-src 'none'; frame-ancestors 'none'", + "content-type": "application/problem+json", + "cross-origin-opener-policy": "same-origin", + "permissions-policy": "camera=(), microphone=(), geolocation=(), payment=(), usb=(), browsing-topics=()", + "referrer-policy": "no-referrer", + "strict-transport-security": "max-age=63072000; includeSubDomains", + "x-content-type-options": "nosniff", + "x-frame-options": "DENY" + }, + "status": 404 + }, + "production-availability-claim": { + "body": { + "code": "resource.not-found", + "detail": "The requested resource was not found.", + "status": 404, + "title": "Not Found", + "traceId": "00000000000000000000000000000000", + "type": "https://id.registrystack.org/problems/registry-breg/resource/not-found" + }, + "headers": { + "cache-control": "no-store", + "content-length": "236", + "content-security-policy": "default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:; connect-src 'self'; object-src 'none'; frame-ancestors 'none'", + "content-type": "application/problem+json", + "cross-origin-opener-policy": "same-origin", + "permissions-policy": "camera=(), microphone=(), geolocation=(), payment=(), usb=(), browsing-topics=()", + "referrer-policy": "no-referrer", + "strict-transport-security": "max-age=63072000; includeSubDomains", + "x-content-type-options": "nosniff", + "x-frame-options": "DENY" + }, + "status": 404 + }, + "production-availability-missing": { + "body": { + "code": "resource.not-found", + "detail": "The requested resource was not found.", + "status": 404, + "title": "Not Found", + "traceId": "00000000000000000000000000000000", + "type": "https://id.registrystack.org/problems/registry-breg/resource/not-found" + }, + "headers": { + "cache-control": "no-store", + "content-length": "236", + "content-security-policy": "default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:; connect-src 'self'; object-src 'none'; frame-ancestors 'none'", + "content-type": "application/problem+json", + "cross-origin-opener-policy": "same-origin", + "permissions-policy": "camera=(), microphone=(), geolocation=(), payment=(), usb=(), browsing-topics=()", + "referrer-policy": "no-referrer", + "strict-transport-security": "max-age=63072000; includeSubDomains", + "x-content-type-options": "nosniff", + "x-frame-options": "DENY" + }, + "status": 404 + }, + "production-create-claim": { + "body": { + "code": "write.outside-boundary", + "detail": "The write falls outside what the selected access profile may write: its row boundary or a disclosure condition.", + "status": 403, + "title": "Forbidden", + "traceId": "00000000000000000000000000000000", + "type": "https://id.registrystack.org/problems/registry-breg/write/outside-boundary" + }, + "headers": { + "cache-control": "no-store", + "content-length": "318", + "content-security-policy": "default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:; connect-src 'self'; object-src 'none'; frame-ancestors 'none'", + "content-type": "application/problem+json", + "cross-origin-opener-policy": "same-origin", + "permissions-policy": "camera=(), microphone=(), geolocation=(), payment=(), usb=(), browsing-topics=()", + "referrer-policy": "no-referrer", + "strict-transport-security": "max-age=63072000; includeSubDomains", + "x-content-type-options": "nosniff", + "x-frame-options": "DENY" + }, + "status": 403 + }, + "production-create-missing": { + "body": { + "code": "write.outside-boundary", + "detail": "The write falls outside what the selected access profile may write: its row boundary or a disclosure condition.", + "status": 403, + "title": "Forbidden", + "traceId": "00000000000000000000000000000000", + "type": "https://id.registrystack.org/problems/registry-breg/write/outside-boundary" + }, + "headers": { + "cache-control": "no-store", + "content-length": "318", + "content-security-policy": "default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:; connect-src 'self'; object-src 'none'; frame-ancestors 'none'", + "content-type": "application/problem+json", + "cross-origin-opener-policy": "same-origin", + "permissions-policy": "camera=(), microphone=(), geolocation=(), payment=(), usb=(), browsing-topics=()", + "referrer-policy": "no-referrer", + "strict-transport-security": "max-age=63072000; includeSubDomains", + "x-content-type-options": "nosniff", + "x-frame-options": "DENY" + }, + "status": 403 + }, + "production-generic-precondition": { + "body": { + "code": "precondition.failed", + "detail": "The mutation precondition failed.", + "status": 412, + "title": "Precondition Failed", + "traceId": "00000000000000000000000000000000", + "type": "https://id.registrystack.org/problems/registry-breg/precondition/failed" + }, + "headers": { + "cache-control": "no-store", + "content-length": "244", + "content-security-policy": "default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:; connect-src 'self'; object-src 'none'; frame-ancestors 'none'", + "content-type": "application/problem+json", + "cross-origin-opener-policy": "same-origin", + "permissions-policy": "camera=(), microphone=(), geolocation=(), payment=(), usb=(), browsing-topics=()", + "referrer-policy": "no-referrer", + "strict-transport-security": "max-age=63072000; includeSubDomains", + "x-content-type-options": "nosniff", + "x-frame-options": "DENY" + }, + "status": 412 + }, + "production-observed-precondition": { + "body": { + "code": "precondition.failed", + "detail": "The mutation precondition failed.", + "status": 412, + "title": "Precondition Failed", + "traceId": "00000000000000000000000000000000", + "type": "https://id.registrystack.org/problems/registry-breg/precondition/failed" + }, + "headers": { + "cache-control": "no-store", + "content-length": "244", + "content-security-policy": "default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:; connect-src 'self'; object-src 'none'; frame-ancestors 'none'", + "content-type": "application/problem+json", + "cross-origin-opener-policy": "same-origin", + "permissions-policy": "camera=(), microphone=(), geolocation=(), payment=(), usb=(), browsing-topics=()", + "referrer-policy": "no-referrer", + "strict-transport-security": "max-age=63072000; includeSubDomains", + "x-content-type-options": "nosniff", + "x-frame-options": "DENY" + }, + "status": 412 + } +} diff --git a/crates/registry-breg/tests/golden/metrics-scrape-sampled.txt b/crates/registry-breg/tests/golden/metrics-scrape-sampled.txt index b5ffbf23b0..c9173c9b19 100644 --- a/crates/registry-breg/tests/golden/metrics-scrape-sampled.txt +++ b/crates/registry-breg/tests/golden/metrics-scrape-sampled.txt @@ -180,6 +180,7 @@ breg_request_refusals_total{check="task-grant-scope"} 0 breg_request_refusals_total{check="task-grant-lifetime"} 0 breg_request_refusals_total{check="task-grant-status"} 0 breg_request_refusals_total{check="row-boundary"} 0 +breg_request_refusals_total{check="membership"} 0 breg_request_refusals_total{check="ownership"} 0 breg_request_refusals_total{check="visibility"} 0 breg_request_refusals_total{check="action-guard"} 0 diff --git a/crates/registry-breg/tests/golden/metrics-scrape-unsampled.txt b/crates/registry-breg/tests/golden/metrics-scrape-unsampled.txt index f469ffcaa8..52863c3ce5 100644 --- a/crates/registry-breg/tests/golden/metrics-scrape-unsampled.txt +++ b/crates/registry-breg/tests/golden/metrics-scrape-unsampled.txt @@ -151,6 +151,7 @@ breg_request_refusals_total{check="task-grant-scope"} 0 breg_request_refusals_total{check="task-grant-lifetime"} 0 breg_request_refusals_total{check="task-grant-status"} 0 breg_request_refusals_total{check="row-boundary"} 0 +breg_request_refusals_total{check="membership"} 0 breg_request_refusals_total{check="ownership"} 0 breg_request_refusals_total{check="visibility"} 0 breg_request_refusals_total{check="action-guard"} 0 diff --git a/crates/registry-breg/tests/http_auth.rs b/crates/registry-breg/tests/http_auth.rs index ea35c82ec7..76f5cbe083 100644 --- a/crates/registry-breg/tests/http_auth.rs +++ b/crates/registry-breg/tests/http_auth.rs @@ -3569,7 +3569,7 @@ async fn action_and_proposal_only_clients_are_checked_at_construction() { "proposals": [{ "action": "register-child", "operations": ["edit"], - "ownership": "caller", + "party": "owner", "targets": [ {"recordType": "parent", "rowBoundaries": "unrestricted"}, {"recordType": "child", "rowBoundaries": "unrestricted"} diff --git a/crates/registry-breg/tests/http_read_only.rs b/crates/registry-breg/tests/http_read_only.rs index 3121a4e34f..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; @@ -4095,6 +4290,7 @@ fn operation_name(operation: Operation) -> &'static str { Operation::Start => "start", Operation::Snapshot => "snapshot", Operation::Import => "import", + Operation::Reference => "reference", } } @@ -4108,7 +4304,16 @@ async fn runtime_openapi_contract_is_filtered_to_the_selected_acceptance_profile .send( Method::GET, "/openapi.json?accessProfile=site-planner", - Some(registry_principal_claims("site-planning")), + Some( + VerifiedRequestClaims::authenticated( + "registry_principal", + "registry-principal", + BTreeSet::from(["asset:plan".into()]), + Some("site-planning".into()), + BTreeMap::new(), + ) + .unwrap(), + ), ) .await, ) @@ -4726,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"}), @@ -4744,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; @@ -4836,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/immediate_action_compiler.rs b/crates/registry-breg/tests/immediate_action_compiler.rs index 83b2a00891..e6f38b2160 100644 --- a/crates/registry-breg/tests/immediate_action_compiler.rs +++ b/crates/registry-breg/tests/immediate_action_compiler.rs @@ -559,7 +559,7 @@ fn create_effects_may_rely_entirely_on_server_generated_fields() { "accessProfiles": {"operator": { "default": true, "principalClaim": "principal", - "requiredScopes": "unrestricted", + "requiredScopes": ["records:write"], "permissions": {"actions": [{ "action": "register", "operations": [operation], @@ -721,7 +721,7 @@ fn action_effect_graph_rejects_invalid_sources_cycles_and_overlaps() { "set":{"label":{"fromInput":"label"},"alpha":{"fromEffect":"alpha"}} }]} }}, - "accessProfiles":{"operator": {"default":true,"principalClaim":"principal","requiredScopes":"unrestricted","permissions":{"actions":[{ + "accessProfiles":{"operator": {"default":true,"principalClaim":"principal","requiredScopes":["records:write"],"permissions":{"actions":[{ "action":"make-cycle", "operations":["invoke"], "targets":[{"recordType":"alpha","rowBoundaries":"unrestricted"},{"recordType":"beta","rowBoundaries":"unrestricted"}] @@ -749,7 +749,7 @@ fn action_inputs_resolve_project_vocabulary_values_for_type_compatibility() { "inputs":[{"id":"kind","type":"vocabulary-code","vocabulary":"asset-type","required":true,"classification":"internal"}], "plan":{"type":"fixed","effects":[{"id":"asset","target":{"recordType":"asset"},"operation":"create","set":{"kind":{"fromInput":"kind"}}}]} }}, - "accessProfiles":{"operator": {"default":true,"principalClaim":"principal","requiredScopes":"unrestricted","permissions":{"actions":[{ + "accessProfiles":{"operator": {"default":true,"principalClaim":"principal","requiredScopes":["records:write"],"permissions":{"actions":[{ "action":"create-asset", "operations":["invoke"], "targets":[{"recordType":"asset","rowBoundaries":"unrestricted"}], @@ -780,7 +780,7 @@ fn action_inputs_reject_unknown_project_vocabulary_references() { "inputs":[{"id":"kind","type":"vocabulary-code","vocabulary":"asset-type","required":true,"classification":"internal"}], "plan":{"type":"fixed","effects":[{"id":"asset","target":{"recordType":"asset"},"operation":"create","set":{"kind":{"fromInput":"kind"}}}]} }}, - "accessProfiles":{"operator": {"default":true,"principalClaim":"principal","requiredScopes":"unrestricted","permissions":{"actions":[{ + "accessProfiles":{"operator": {"default":true,"principalClaim":"principal","requiredScopes":["records:write"],"permissions":{"actions":[{ "action":"create-asset", "operations":["invoke"], "targets":[{"recordType":"asset","rowBoundaries":"unrestricted"}] @@ -821,7 +821,7 @@ fn action_bounds_apply_before_runtime_target_work() { "recordTypes":{{"record":{{"primaryDataset":"test-dataset","route":"records","mutationMode":"mutable", "fields":[{{"id":"label","type":"string","maximumLength":32,"classification":"internal"}}]}}}}, "actions":{{"bulk-fix":{{"execution":{{"mode":"immediate"}},"inputs":[{}],"plan":{{"type":"fixed","effects":[{}]}}}}}}, - "accessProfiles":{{"operator":{{"default":true,"principalClaim":"principal","requiredScopes":"unrestricted", + "accessProfiles":{{"operator":{{"default":true,"principalClaim":"principal","requiredScopes":["records:write"], "permissions":{{"actions":[{{"action":"bulk-fix","operations":["invoke"],"targets":[{}]}}]}}}}}} }}"#, inputs.join(","), @@ -882,7 +882,7 @@ fn action_field_and_snapshot_ceilings_refuse_otherwise_valid_plans() { "operation": "create", "set": Value::Object(assignments) }]} }}, - "accessProfiles": {"operator": { "default": true, "principalClaim": "principal", "requiredScopes": "unrestricted", + "accessProfiles": {"operator": { "default": true, "principalClaim": "principal", "requiredScopes": ["records:write"], "permissions": {"actions": [{ "action": "create-bounded-record", "operations": ["invoke"], "targets": [{"recordType": "bounded-record", "rowBoundaries": "unrestricted"}] @@ -981,7 +981,7 @@ fn generated_create_fields_count_toward_the_proposal_snapshot_ceiling() { "accessProfiles": {"operator": { "default": true, "principalClaim": "principal", - "requiredScopes": "unrestricted", + "requiredScopes": ["proposals:write"], "permissions": {"actions": [{ "action": "create-bounded-record", "operations": ["start"], diff --git a/crates/registry-breg/tests/immediate_action_handler.rs b/crates/registry-breg/tests/immediate_action_handler.rs index fc4ab532ab..62eebae0d0 100644 --- a/crates/registry-breg/tests/immediate_action_handler.rs +++ b/crates/registry-breg/tests/immediate_action_handler.rs @@ -30,7 +30,7 @@ fn project() -> Value { {"id":"friend","target":{"recordType":"person"},"operation":"create","fields":["name","friend"]}, {"id":"existing","target":{"fromInput":"person"},"operation":"patch","fields":["name","friend"]} ],"refusals":[{"code":"blank-name","label":"A name is required."}]}}}, - "accessProfiles":{"registrar": {"default":true,"principalClaim":"principal","requiredScopes":"unrestricted","permissions":{"actions":[{"action":"register-person","operations":["invoke"],"targets":[{"recordType":"person","rowBoundaries":"unrestricted"}],"results":["person","friend","existing"]}]}}} + "accessProfiles":{"registrar": {"default":true,"principalClaim":"principal","requiredScopes":["records:write"],"permissions":{"actions":[{"action":"register-person","operations":["invoke"],"targets":[{"recordType":"person","rowBoundaries":"unrestricted"}],"results":["person","friend","existing"]}]}}} }) } fn compile(source: Value, script: &str) -> Result { diff --git a/crates/registry-breg/tests/import_grant_admission.rs b/crates/registry-breg/tests/import_grant_admission.rs index 3d084db14d..998271273a 100644 --- a/crates/registry-breg/tests/import_grant_admission.rs +++ b/crates/registry-breg/tests/import_grant_admission.rs @@ -28,7 +28,7 @@ fn project(loader_operations: &[&str]) -> Value { "mutationPolicy":{"patch":"proposal-required"}, "fields":[{"id":"label","type":"string","maximumLength":32,"required":true,"classification":"internal"}] }}, - "accessProfiles":{"loader": {"default":true,"principalClaim":"principal","requiredScopes":"unrestricted", + "accessProfiles":{"loader": {"default":true,"principalClaim":"principal","requiredScopes":["records:write"], "permissions":{"records":[{ "recordType":"enrollment","operations":loader_operations,"readableFields":["label"],"writableFields":["label"], "rowBoundaries":"unrestricted" diff --git a/crates/registry-breg/tests/issuer_portability.rs b/crates/registry-breg/tests/issuer_portability.rs index d02f95344d..91e73c4358 100644 --- a/crates/registry-breg/tests/issuer_portability.rs +++ b/crates/registry-breg/tests/issuer_portability.rs @@ -325,7 +325,7 @@ async fn stock_to_keycloak_preserves_native_proposal_issuer_isolation() { "permissions":{"records":[{"recordType":"record","operations":["create","get"],"readableFields":["label","district"],"writableFields":["label","district"], "rowBoundaries":[{"field":"district","claim":"districts","operator":"equals"}]}], "actions":[{"action":"correct-label","operations":["start"],"targets":[{"recordType":"record","rowBoundaries":[{"field":"district","claim":"districts","operator":"equals"}]}]}], - "proposals":[{"action":"correct-label","operations":["get","submit","apply"],"ownership":"caller","targets":[{"recordType":"record","rowBoundaries":[{"field":"district","claim":"districts","operator":"equals"}]}]}]}}}}); + "proposals":[{"action":"correct-label","operations":["get","submit","apply"],"party":"owner","targets":[{"recordType":"record","rowBoundaries":[{"field":"district","claim":"districts","operator":"equals"}]}]}]}}}}); let project = parse_project_json(&serde_json::to_vec(&source).unwrap()).unwrap(); let registry = compile_project(&project, &[], CompileProfile::Authoring).unwrap(); let stock = authenticator(®istry, root, &journey.stock, &journey.audience); diff --git a/crates/registry-breg/tests/membership_access.rs b/crates/registry-breg/tests/membership_access.rs index d2b0213e1a..787f1ac464 100644 --- a/crates/registry-breg/tests/membership_access.rs +++ b/crates/registry-breg/tests/membership_access.rs @@ -55,37 +55,37 @@ fn membership_reference_uses_one_positioned_spelling() { let decoded = registry_breg::contract::read_project_yaml("registry.yaml", &bytes).unwrap(); let wire = serde_json::to_value(&decoded.value).unwrap(); assert_eq!( - wire.pointer( - "/accessProfiles/member/permissions/records/0/membershipBoundaries/0/membershipRecordType" - ), + wire.pointer("/accessProfiles/member/permissions/records/0/rowBoundaries/0/membership"), Some(&json!("membership")) ); - for value in [json!("membership"), json!(""), serde_json::Value::Null] { - let mut previous = source.clone(); - let boundary = previous - .pointer_mut("/accessProfiles/member/permissions/records/0/membershipBoundaries/0") - .unwrap() - .as_object_mut() - .unwrap(); - boundary.remove("membershipRecordType"); - boundary.insert("membershipEntity".to_owned(), value); - let report = registry_breg::contract::read_project_yaml( - "registry.yaml", - &serde_json::to_vec_pretty(&previous).unwrap(), - ) - .expect_err("previous reference is refused"); - let diagnostic = report - .diagnostics() - .iter() - .find(|diagnostic| diagnostic.code == "config.removed-key") - .expect("migration guidance is present"); - assert_eq!( - diagnostic.path, - "/accessProfiles/member/permissions/records/0/membershipBoundaries/0/membershipEntity" - ); - assert!(diagnostic.suggested_action.contains("membershipRecordType")); - assert!(diagnostic.source.as_ref().unwrap().line.is_some()); - } +} + +#[test] +fn membership_boundaries_is_refused_with_its_replacement_named() { + let mut source = source("facility"); + source["accessProfiles"]["member"]["permissions"]["records"][0]["membershipBoundaries"] = + json!([]); + let report = registry_breg::contract::read_project_yaml( + "registry.yaml", + &serde_json::to_vec_pretty(&source).unwrap(), + ) + .expect_err("removed member is refused"); + let diagnostic = report + .diagnostics() + .iter() + .find(|diagnostic| diagnostic.code == "config.removed-key") + .unwrap(); + assert_eq!( + diagnostic.path, + "/accessProfiles/member/permissions/records/0/membershipBoundaries" + ); + assert!(diagnostic + .suggested_action + .contains("membership: {key, principal, active}")); + assert!(diagnostic + .suggested_action + .contains("rowBoundaries entry {field, membership}")); + assert!(diagnostic.source.as_ref().unwrap().line.is_some()); } #[test] @@ -93,8 +93,8 @@ fn membership_boundaries_refuse_unenforced_authority_paths() { for (path, value, code) in [ ( "/accessProfiles/member/permissions/records/0/operations", - json!(["get", "patch"]), - "breg.access.membership-read-only", + json!(["get", "import"]), + "breg.access.membership-import-unsupported", ), ( "/accessProfiles/member/requiredScopes", @@ -102,23 +102,23 @@ fn membership_boundaries_refuse_unenforced_authority_paths() { "breg.access.requirements-scope-missing", ), ( - "/accessProfiles/member/permissions/records/0/membershipBoundaries/0/field", + "/accessProfiles/member/permissions/records/0/rowBoundaries/0/field", json!("label"), "breg.access.membership-key-type", ), ( - "/accessProfiles/member/permissions/records/0/membershipBoundaries/0/principalField", + "/recordTypes/membership/membership/principal", json!("active"), "breg.access.membership-principal-type", ), ( - "/accessProfiles/member/permissions/records/0/membershipBoundaries/0/activeField", + "/recordTypes/membership/membership/active", json!("principal"), "breg.access.membership-active-type", ), ( - "/accessProfiles/member/permissions/records/0/membershipBoundaries/0/membershipRecordType", - json!("facility"), + "/accessProfiles/member/permissions/records/0/recordType", + json!("membership"), "breg.access.membership-source-recursive", ), ( @@ -156,7 +156,7 @@ fn membership_boundaries_refuse_unenforced_authority_paths() { let mut action = action_requirements::project(); action["accessProfiles"]["registrar"]["permissions"]["actions"][0]["membershipBoundaries"] = source("facility")["accessProfiles"]["member"]["permissions"]["records"][0] - ["membershipBoundaries"] + ["rowBoundaries"] .clone(); let failure = registry_breg::parse_project_yaml(&serde_json::to_vec(&action).unwrap()) .expect_err("an action grant must not silently ignore entity membership rules"); @@ -173,3 +173,76 @@ fn membership_boundaries_refuse_unenforced_authority_paths() { )] ); } + +#[test] +fn module_membership_boundaries_is_refused_with_its_replacement_named() { + for collection in ["recordTypes", "extendRecordTypes"] { + let module = json!({ + "apiVersion":"id.registrystack.org/formats/breg/module/v1alpha1", + "kind":"BRegModule","id":"membership-core","version":"1", + collection: {"facility":{"accessProfiles":{"member":{"membershipBoundaries":[]}}}} + }); + let bytes = serde_json::to_vec_pretty(&module).unwrap(); + let report = registry_breg::contract::read_module_yaml("module.yaml", &bytes).unwrap_err(); + let code = report + .diagnostics() + .iter() + .find(|diagnostic| diagnostic.code == "config.removed-key") + .unwrap(); + assert_eq!( + code.path, + format!("/{collection}/facility/accessProfiles/member/membershipBoundaries") + ); + assert!(code + .suggested_action + .contains("membership: {key, principal, active}")); + assert!(code + .suggested_action + .contains("rowBoundaries entry {field, membership}")); + } +} + +#[test] +fn a_project_record_profile_refuses_membership_boundaries_with_its_replacement_named() { + let mut source = source("facility"); + source["recordTypes"]["facility"]["accessProfiles"] = + json!({"member":{"membershipBoundaries":[]}}); + let report = registry_breg::contract::read_project_yaml( + "registry.yaml", + &serde_json::to_vec_pretty(&source).unwrap(), + ) + .unwrap_err(); + let diagnostic = report + .diagnostics() + .iter() + .find(|diagnostic| diagnostic.code == "config.removed-key") + .unwrap(); + assert_eq!( + diagnostic.path, + "/recordTypes/facility/accessProfiles/member/membershipBoundaries" + ); + assert!(diagnostic + .suggested_action + .contains("membership: {key, principal, active}")); + assert!(diagnostic + .suggested_action + .contains("rowBoundaries entry {field, membership}")); +} + +#[test] +fn an_extension_cannot_declare_membership() { + let module = json!({ + "apiVersion":"id.registrystack.org/formats/breg/module/v1alpha1", + "kind":"BRegModule","id":"membership-core","version":"1", + "extendRecordTypes":{"facility":{"membership":{"key":"organization","principal":"principal","active":"active"}}} + }); + let report = registry_breg::contract::read_module_yaml( + "module.yaml", + &serde_json::to_vec_pretty(&module).unwrap(), + ) + .unwrap_err(); + assert!(report.diagnostics().iter().any(|diagnostic| { + diagnostic.code == "config.unknown-key" + && diagnostic.path == "/extendRecordTypes/facility/membership" + })); +} diff --git a/crates/registry-breg/tests/membership_authoring.rs b/crates/registry-breg/tests/membership_authoring.rs new file mode 100644 index 0000000000..43dc642aad --- /dev/null +++ b/crates/registry-breg/tests/membership_authoring.rs @@ -0,0 +1,627 @@ +// SPDX-License-Identifier: Apache-2.0 + +use registry_breg::compiler::{compile_project, CompileProfile}; +use registry_breg::diagnostics::CompileFailure; +use registry_breg::{parse_project_yaml, CompiledRegistry}; +use serde_json::{json, Value}; + +const PROJECT: &[u8] = + include_bytes!("../../../products/breg/fixtures/organization-membership-access/registry.yaml"); +const ROWS: &str = "/accessProfiles/member/permissions/records/0/rowBoundaries"; +const DECLARATION: &str = "/recordTypes/membership/membership"; + +fn project() -> Value { + serde_json::from_slice(PROJECT).unwrap() +} + +fn compile(project: &Value) -> Result { + let source = parse_project_yaml(&serde_json::to_vec_pretty(project).unwrap())?; + compile_project(&source, &[], CompileProfile::Authoring) +} + +fn compile_production(project: &Value) -> Result { + let mut project = project.clone(); + project["package"] = json!({"sourceRevision":"membership-authoring-test"}); + let source = parse_project_yaml(&serde_json::to_vec_pretty(&project).unwrap())?; + compile_project(&source, &[], CompileProfile::Production) +} + +fn assert_production_refusal(project: &Value, code: &str, path: &str) { + let failure = compile_production(project).expect_err("Production refuses this grant"); + assert!( + failure + .diagnostics() + .iter() + .any(|diagnostic| diagnostic.code == code && diagnostic.path == path), + "wanted {code} at {path}: {failure:?}" + ); +} + +fn assert_refusal(project: &Value, code: &str, path: &str) { + let failure = compile(project).expect_err("project must be refused"); + assert!( + failure + .diagnostics() + .iter() + .any(|diagnostic| diagnostic.code == code && diagnostic.path == path), + "wanted {code} at {path}: {failure:?}" + ); +} + +#[test] +fn a_membership_declaration_compiles_into_the_record_type() { + let project = project(); + let registry = compile(&project).unwrap(); + let entity = serde_json::to_value(®istry.entities()["membership"]).unwrap(); + assert_eq!(entity["membership"], *project.pointer(DECLARATION).unwrap()); +} + +#[test] +fn a_membership_declaration_naming_a_missing_field_is_refused_without_panicking() { + for (field, code) in [ + ("key", "breg.access.membership-key-type"), + ("principal", "breg.access.membership-principal-type"), + ("active", "breg.access.membership-active-type"), + ] { + let mut project = project(); + project.pointer_mut(DECLARATION).unwrap()[field] = json!("missing"); + assert_refusal(&project, code, "recordTypes[id=membership].membership"); + } +} + +#[test] +fn a_record_grant_with_a_membership_entry_compiles_like_the_base_membership_boundary() { + let registry = compile(&project()).unwrap(); + let entry = ®istry.entities()["facility"].membership_boundaries["member"][0]; + assert_eq!(entry.field, "organization"); + assert_eq!(entry.membership_entity, "membership"); + let source = ®istry.entities()["membership"]; + assert_eq!(entry.membership_table, source.physical_table); + assert_eq!( + entry.membership_key_column, + source.fields["organization"].physical_name + ); + assert_eq!( + entry.principal_column, + source.fields["principal"].physical_name + ); + assert_eq!(entry.active_column, source.fields["active"].physical_name); +} + +#[test] +fn claim_and_membership_entries_share_one_row_boundaries_list() { + let mut project = project(); + project + .pointer_mut(ROWS) + .unwrap() + .as_array_mut() + .unwrap() + .push(json!({"field": "label", "claim": "facility-label", "operator": "equals"})); + let registry = compile(&project).unwrap(); + let entity = ®istry.entities()["facility"]; + assert_eq!(entity.access_profiles["member"].row_boundaries.len(), 1); + assert_eq!(entity.membership_boundaries["member"].len(), 1); +} + +#[test] +fn a_membership_only_grant_never_serializes_as_unrestricted() { + let project = project(); + let source = parse_project_yaml(&serde_json::to_vec_pretty(&project).unwrap()).unwrap(); + let serialized = serde_json::to_value(source).unwrap(); + assert_eq!(serialized.pointer(ROWS), project.pointer(ROWS)); +} + +#[test] +fn a_row_boundary_set_with_a_membership_entry_expands_like_the_inline_form() { + let inline = project(); + let mut named = inline.clone(); + named["rowBoundarySets"] = json!({"facility-membership": inline.pointer(ROWS).unwrap()}); + *named.pointer_mut(ROWS).unwrap() = json!({"rowBoundarySet": "facility-membership"}); + let inline = compile(&inline).unwrap(); + let named = compile(&named).unwrap(); + assert_eq!(named.access(), inline.access()); + assert_eq!(named.ddl(), inline.ddl()); +} + +fn shape_is_refused(entry: Value) { + let mut project = project(); + *project.pointer_mut(ROWS).unwrap() = json!([entry]); + let failure = compile(&project).expect_err("invalid boundary shape is refused"); + assert!( + failure.diagnostics().iter().any(|diagnostic| { + diagnostic.message.contains("claim entry") + && diagnostic.message.contains("membership entry") + }), + "{failure:?}" + ); +} + +#[test] +fn an_entry_with_both_claim_and_membership_is_refused() { + shape_is_refused( + json!({"field": "organization", "claim": "sub", "operator": "equals", "membership": "membership"}), + ); +} + +#[test] +fn an_entry_with_neither_is_refused() { + shape_is_refused(json!({"field": "organization"})); +} + +#[test] +fn a_membership_entry_naming_a_type_without_membership_is_refused() { + let mut project = project(); + project.pointer_mut(ROWS).unwrap()[0]["membership"] = json!("organization"); + assert_refusal(&project, "breg.access.membership-record-type-unknown", + "recordTypes[id=facility].accessProfiles[id=member].rowBoundaries[membership=organization:field=organization]"); +} + +#[test] +fn a_membership_entry_in_access_requirements_is_refused() { + for use_set in [false, true] { + let mut project = project(); + let entries = json!([{"field":"organization","membership":"membership"}]); + let rows = if use_set { + project["rowBoundarySets"] = json!({"member": entries}); + json!({"rowBoundarySet":"member"}) + } else { + entries + }; + project["recordTypes"]["facility"]["accessRequirements"] = json!({"rowBoundaries": rows}); + let failure = compile(&project).expect_err("requirements accept claim entries only"); + assert!( + failure + .diagnostics() + .iter() + .any(|diagnostic| diagnostic.code + == "breg.access.membership-access-requirement-unsupported"), + "{failure:?}" + ); + } +} + +const MEMBER_ROW: &str = "recordTypes[id=facility].accessProfiles[id=member].rowBoundaries"; + +#[test] +fn import_grants_refuse_membership_entries() { + let mut project = project(); + project["accessProfiles"]["member"]["permissions"]["records"][0]["operations"] = + json!(["import"]); + assert_production_refusal( + &project, + "breg.access.membership-import-unsupported", + MEMBER_ROW, + ); +} + +#[test] +fn open_record_writes_require_a_principal_boundary() { + let mut project = project(); + project["accessProfiles"]["steward"]["requiredScopes"] = json!("unrestricted"); + assert_refusal( + &project, + "breg.access.open-write-without-principal-boundary", + "recordTypes[id=facility].accessProfiles[id=steward].rowBoundaries", + ); +} + +#[test] +fn a_scopeless_profile_with_requester_clients_cannot_write_membership_records() { + let mut project = project(); + project["accessProfiles"]["steward"]["requiredScopes"] = json!("unrestricted"); + project["accessProfiles"]["steward"]["requesterClients"] = json!(["bounded-client"]); + assert_refusal( + &project, + "breg.access.scopeless-membership-source-write", + "recordTypes[id=membership].accessProfiles[id=steward].rowBoundaries", + ); +} + +#[test] +fn open_profiles_with_membership_must_use_sub() { + let mut project = project(); + project["accessProfiles"]["member"]["requiredScopes"] = json!("unrestricted"); + assert_refusal( + &project, + "breg.access.open-membership-principal-not-sub", + MEMBER_ROW, + ); +} + +#[test] +fn production_admits_and_documents_member_bounded_open_writes() { + let mut project = project(); + project["recordTypes"]["membership"] + .as_object_mut() + .unwrap() + .remove("accessRequirements"); + let member = &mut project["accessProfiles"]["member"]; + member["requiredScopes"] = json!("unrestricted"); + member["principalClaim"] = json!("sub"); + member["permissions"]["records"][0]["operations"] = json!([ + "get", + "list", + "lookup", + "create", + "patch", + "tombstone", + "batch" + ]); + member["permissions"]["records"][0]["writableFields"] = json!(["organization", "label"]); + // A write names an organisation the member can read: one it belongs to. + member["permissions"]["records"] + .as_array_mut() + .unwrap() + .push( + json!({"recordType":"organization","operations":["get"],"readableFields":["name"], + "rowBoundaries":[{"field":"id","membership":"membership"}]}), + ); + project["recordTypes"]["facility"]["tombstone"] = json!(true); + project["recordTypes"]["facility"]["batch"] = json!({"maximumItems":4,"maximumBytes":8192}); + let registry = compile_production(&project).expect("Production admits the bounded writes"); + assert_eq!( + registry.entities()["facility"].membership_boundaries["member"].len(), + 1 + ); + let api: Value = + serde_json::from_slice(®istry.artifacts().entries()["generated/openapi.json"].bytes) + .unwrap(); + for (record_path, method) in [ + ("/v1/records/facilities", "post"), + ("/v1/records/facilities/{record_id}", "patch"), + ("/v1/records/facilities:batch", "post"), + ] { + assert_eq!( + api["paths"][record_path][method]["responses"]["403"]["content"] + ["application/problem+json"]["examples"]["write.outside-boundary"]["value"]["code"], + "write.outside-boundary", + "{method} {record_path}" + ); + } +} + +#[test] +fn membership_entries_are_limited_and_unique_after_set_expansion() { + let mut project = project(); + let entry = project.pointer(ROWS).unwrap()[0].clone(); + project["rowBoundarySets"] = json!({"many": vec![entry; 9]}); + *project.pointer_mut(ROWS).unwrap() = json!({"rowBoundarySet":"many"}); + assert_refusal(&project, "breg.access.membership-limit", MEMBER_ROW); + assert_refusal(&project, "breg.access.membership-duplicate", + "recordTypes[id=facility].accessProfiles[id=member].rowBoundaries[membership=membership:field=organization]"); +} + +#[path = "support/action_requirements.rs"] +mod action_requirements; +#[allow(dead_code)] +#[path = "support/proposal_hooks_model.rs"] +mod proposal_hooks_model; + +fn action_project() -> Value { + let mut project = action_requirements::project(); + let records = project["recordTypes"].as_object_mut().unwrap(); + let membership = self::project()["recordTypes"]["membership"].clone(); + let mut membership = membership; + membership["primaryDataset"] = json!("test-dataset"); + membership["fields"][0]["target"] = json!("parent"); + membership + .as_object_mut() + .unwrap() + .remove("accessRequirements"); + records.insert("membership".into(), membership); + project +} + +#[test] +fn production_admits_a_membership_bound_immediate_action_target() { + let mut project = action_project(); + project["accessProfiles"]["registrar"]["permissions"]["actions"][0]["targets"][1] + ["rowBoundaries"] = json!([{"field":"parent","membership":"membership"}]); + project["recordTypes"]["child"]["hooks"][0]["handler"] = + json!({"type":"url","destinationId":"record-events"}); + let registry = compile_production(&project).expect("Production admits the bounded Invoke"); + assert!(registry.actions().actions[0].permissions[0] + .targets + .iter() + .any(|target| target.entity_id == "child" && target.membership_boundaries.len() == 1)); +} + +#[test] +fn a_hook_cannot_use_an_action_grant_with_membership() { + let mut project = action_project(); + project["recordTypes"]["child"]["hooks"][0]["principal"] = json!("registrar"); + project["accessProfiles"]["registrar"]["permissions"]["actions"][0]["targets"][1] + ["rowBoundaries"] = json!([{"field":"parent","membership":"membership"}]); + assert_refusal(&project, "breg.access.membership-hook-unsupported", + "accessProfiles[id=registrar].permissions.actions[action=register-child].targets[recordType=child].rowBoundaries"); +} + +#[test] +fn a_timer_cannot_use_an_action_grant_with_membership() { + let mut project = action_project(); + project["recordTypes"]["child"]["timers"] = json!([{ + "id":"invoke","at":"label","invoke":"register-child","input":{} + }]); + project["accessProfiles"]["registrar"]["permissions"]["actions"][0]["targets"][1] + ["rowBoundaries"] = json!([{"field":"parent","membership":"membership"}]); + assert_refusal(&project, "breg.access.membership-timer-unsupported", + "accessProfiles[id=registrar].permissions.actions[action=register-child].targets[recordType=child].rowBoundaries"); +} + +#[test] +fn production_admits_membership_on_proposal_start_and_lifecycle_targets() { + let mut project = proposal_hooks_model::source(json!([])); + let fixture = self::project(); + for id in ["membership", "organization"] { + project["recordTypes"][id] = fixture["recordTypes"][id].clone(); + project["recordTypes"][id]["primaryDataset"] = json!("directory"); + } + project["recordTypes"]["membership"] + .as_object_mut() + .unwrap() + .remove("accessRequirements"); + project["recordTypes"]["target"]["fields"].as_array_mut().unwrap().push( + json!({"id":"organization","type":"reference","target":"organization","classification":"internal"}), + ); + for permission in ["actions", "proposals"] { + let mut candidate = project.clone(); + candidate["accessProfiles"]["clerk"]["permissions"][permission][0]["targets"][0] + ["rowBoundaries"] = json!([{"field":"organization","membership":"membership"}]); + let registry = + compile_production(&candidate).expect("Production admits the Proposal target"); + let action = ®istry.actions().actions[0]; + if permission == "actions" { + assert!(action.permissions[0] + .targets + .iter() + .all(|target| target.membership_boundaries.len() == 1)); + } else { + let registry_breg::model::CompiledActionExecution::Proposal { proposal } = + &action.execution + else { + panic!("expected a Proposal"); + }; + assert_eq!( + proposal.permissions[0].targets[0] + .membership_boundaries + .len(), + 1 + ); + } + } + // A source bounded by itself stays refused; one level over a different + // leaf is admitted (see steward_authoring.rs). + project["accessProfiles"]["clerk"]["permissions"]["proposals"][0]["targets"][0] + ["rowBoundaries"] = json!([{"field":"organization","membership":"target"}]); + let target = &mut project["recordTypes"]["target"]; + target["fields"] + .as_array_mut() + .unwrap() + .push(json!({"id":"active","type":"boolean","classification":"internal"})); + target["membership"] = json!({"key":"organization","principal":"name","active":"active"}); + assert_refusal( + &project, + "breg.access.membership-source-recursive", + "recordTypes[id=target].membership", + ); +} + +#[test] +fn an_encrypted_membership_principal_is_refused_at_its_declaration() { + let mut project = project(); + project["recordTypes"]["membership"]["fields"][1]["encrypted"] = json!(true); + assert_refusal( + &project, + "breg.access.membership-principal-encrypted", + "recordTypes[id=membership].membership", + ); +} + +#[test] +fn a_membership_source_with_an_incoming_read_path_is_refused_at_its_declaration() { + let mut project = project(); + project["recordTypes"]["organization"]["readPaths"] = + json!([{"id":"links","through":"membership","to":"facility","route":"links"}]); + assert_refusal( + &project, + "breg.access.membership-source-recursive", + "recordTypes[id=membership].membership", + ); +} + +#[test] +fn a_membership_source_with_a_row_requirement_is_refused_at_its_declaration() { + let mut project = project(); + project["recordTypes"]["membership"]["accessRequirements"]["rowBoundaries"] = + json!([{"field":"principal","claim":"sub","operator":"equals"}]); + assert_refusal( + &project, + "breg.access.membership-source-row-requirement", + "recordTypes[id=membership].membership", + ); +} + +#[test] +fn membership_entries_are_incompatible_with_spatial_queries() { + let mut project = project(); + project["accessProfiles"]["member"]["permissions"]["records"][0]["spatialQueries"] = + json!({"bbox": {"maximumLongitudeSpanDegrees": 5, "maximumLatitudeSpanDegrees": 5}}); + assert_refusal( + &project, + "breg.access.membership-spatial-unsupported", + MEMBER_ROW, + ); +} + +#[test] +fn a_module_defines_membership_and_its_profile_round_trips() { + use registry_breg::compiler::module_digest; + use registry_breg::contract::parse_module_yaml; + + let mut project = project(); + let grant = project["accessProfiles"]["member"]["permissions"]["records"][0].clone(); + let mut profile = grant.as_object().unwrap().clone(); + profile.remove("recordType"); + profile.insert( + "requiredScopes".into(), + json!(["records:read", "membership:use"]), + ); + profile.insert("principalClaim".into(), json!("principal")); + profile.insert("default".into(), json!(true)); + project["accessProfiles"] + .as_object_mut() + .unwrap() + .remove("member"); + let records = project["recordTypes"].as_object_mut().unwrap(); + let mut facility = records.remove("facility").unwrap(); + facility["accessProfiles"] = json!({"member":profile}); + let module = json!({ + "apiVersion":"id.registrystack.org/formats/breg/module/v1alpha1","kind":"BRegModule", + "id":"membership-core","version":"1", + "recordTypes":{"facility":facility,"membership":records.remove("membership").unwrap()} + }); + let module = parse_module_yaml(&serde_json::to_vec(&module).unwrap()).unwrap(); + let serialized = serde_json::to_value(&module).unwrap(); + assert_eq!( + serialized.pointer("/recordTypes/facility/accessProfiles/member/rowBoundaries"), + grant.get("rowBoundaries") + ); + project["modules"] = json!({"membership-core":{"version":"1","digest":module_digest(&module)}}); + let project = parse_project_yaml(&serde_json::to_vec(&project).unwrap()).unwrap(); + let registry = compile_project(&project, &[module], CompileProfile::Authoring).unwrap(); + assert_eq!( + registry.entities()["facility"].membership_boundaries["member"].len(), + 1 + ); + assert!(registry.entities()["membership"].membership.is_some()); +} + +#[test] +fn an_open_membership_target_requires_sub_even_for_immediate_invoke() { + let mut project = action_project(); + let profile = &mut project["accessProfiles"]["registrar"]; + profile["requiredScopes"] = json!("unrestricted"); + profile["principalClaim"] = json!("email"); + profile["permissions"]["actions"][0]["targets"][1]["rowBoundaries"] = + json!([{"field":"parent","membership":"membership"}]); + let failure = compile(&project).unwrap_err(); + assert!( + failure + .diagnostics() + .iter() + .any(|diagnostic| diagnostic.code == "breg.access.open-membership-principal-not-sub"), + "{failure:?}" + ); + assert!( + failure + .diagnostics() + .iter() + .all(|diagnostic| diagnostic.code != "breg.access.membership-read-only"), + "{failure:?}" + ); +} + +#[test] +fn membership_ids_are_checked_without_repeating_invalid_values() { + let canary = "CANARY SECRET VALUE"; + for path in [ + "/recordTypes/membership/membership/key", + "/recordTypes/membership/membership/principal", + "/recordTypes/membership/membership/active", + "/accessProfiles/member/permissions/records/0/rowBoundaries/0/membership", + "/accessProfiles/member/permissions/records/0/rowBoundaries/0/field", + ] { + let mut project = project(); + *project.pointer_mut(path).unwrap() = json!(canary); + let report = registry_breg::contract::read_project_yaml( + "registry.yaml", + &serde_json::to_vec(&project).unwrap(), + ) + .unwrap_err(); + assert!(!format!("{report:?}").contains(canary)); + } +} + +#[test] +fn membership_requirements_do_not_hide_removed_keys() { + let mut project = project(); + project["recordTypes"]["facility"]["accessRequirements"] = + json!({"rowBoundaries":[{"field":"organization","membership":"membership"}]}); + project["accessProfiles"]["member"]["permissions"]["records"][0]["membershipBoundaries"] = + json!([]); + let report = registry_breg::contract::read_project_yaml( + "registry.yaml", + &serde_json::to_vec(&project).unwrap(), + ) + .unwrap_err(); + for code in [ + "breg.access.membership-access-requirement-unsupported", + "config.removed-key", + ] { + assert!( + report + .diagnostics() + .iter() + .any(|diagnostic| diagnostic.code == code), + "{report:?}" + ); + } +} + +#[test] +fn a_membership_source_cannot_bound_its_own_action_target() { + let mut project = action_project(); + let child = &mut project["recordTypes"]["child"]; + child["fields"] + .as_array_mut() + .unwrap() + .push(json!({"id":"active", "type":"boolean", "classification":"internal"})); + child["membership"] = json!({"key":"parent","principal":"label","active":"active"}); + project["accessProfiles"]["registrar"]["permissions"]["actions"][0]["targets"][1] + ["rowBoundaries"] = json!([{"field":"parent","membership":"child"}]); + assert_refusal( + &project, + "breg.access.membership-source-recursive", + "recordTypes[id=child].membership", + ); +} + +#[test] +fn answer_and_cancel_are_proposal_writes_for_admission() { + for operation in ["answer", "cancel"] { + let mut project = proposal_hooks_model::source(json!([])); + project["recordTypes"]["organization"] = + self::project()["recordTypes"]["organization"].clone(); + project["recordTypes"]["organization"]["primaryDataset"] = json!("directory"); + let target = &mut project["recordTypes"]["target"]; + target["fields"].as_array_mut().unwrap().extend([ + json!({"id":"organization","type":"reference","target":"organization","classification":"internal"}), + json!({"id":"active","type":"boolean","classification":"internal"}), + ]); + target["membership"] = json!({"key":"organization","principal":"name","active":"active"}); + project["accessProfiles"]["clerk"]["requiredScopes"] = json!("unrestricted"); + project["accessProfiles"]["clerk"]["permissions"]["proposals"][0]["operations"] = + json!(["get", operation]); + let location = "accessProfiles[id=clerk].permissions.proposals[action=correct-name].targets[recordType=target].rowBoundaries"; + assert_refusal( + &project, + "breg.access.open-write-without-principal-boundary", + location, + ); + assert_refusal( + &project, + "breg.access.scopeless-membership-source-write", + location, + ); + } +} + +#[test] +fn admission_diagnostics_do_not_render_malformed_target_references() { + let mut project = action_project(); + let profile = &mut project["accessProfiles"]["registrar"]; + profile["requiredScopes"] = json!("unrestricted"); + profile["permissions"]["actions"][0]["targets"][1]["recordType"] = json!("CANARY SECRET VALUE"); + let failure = compile(&project).unwrap_err(); + assert!(!format!("{failure:?}").contains("CANARY SECRET VALUE")); +} diff --git a/crates/registry-breg/tests/migration_plan.rs b/crates/registry-breg/tests/migration_plan.rs index 1013211da9..e44c4051e8 100644 --- a/crates/registry-breg/tests/migration_plan.rs +++ b/crates/registry-breg/tests/migration_plan.rs @@ -40,7 +40,7 @@ journeys: - id: list-assets recordType: asset accessProfile: reader - claims: {principal: package-reader} + claims: {principal: package-reader, scopes: [assets:write]} request: {type: list} expect: {outcome: success, status: 200, count: 0} "#; @@ -2691,7 +2691,7 @@ fn module_bytes(variant: Variant) -> Vec { _ => "", }; format!( - r#"{{"apiVersion":"id.registrystack.org/formats/breg/module/v1alpha1","kind":"BRegModule","id":"core","version":"1","recordTypes":{{"asset":{{"primaryDataset":"neutral-registry","route":"assets","mutationMode":"create-only","fields":[{fields}],"accessProfiles":{{"reader":{{"requiredScopes":"unrestricted","rowBoundaries":"unrestricted","principalClaim":"principal","operations":["create","get","list"],"readableFields":["code"],"writableFields":["code"]}}}}}},"site":{{"primaryDataset":"neutral-registry","route":"sites","mutationMode":"create-only","fields":[{{"id":"code","type":"string","maximumLength":8,"classification":"internal"}}{site_secret}],"accessProfiles":{{"reader":{{"requiredScopes":"unrestricted","rowBoundaries":"unrestricted","principalClaim":"principal","operations":["create","get","list"],"readableFields":["code"],"writableFields":["code"]}}}}}}}}}}"# + r#"{{"apiVersion":"id.registrystack.org/formats/breg/module/v1alpha1","kind":"BRegModule","id":"core","version":"1","recordTypes":{{"asset":{{"primaryDataset":"neutral-registry","route":"assets","mutationMode":"create-only","fields":[{fields}],"accessProfiles":{{"reader":{{"requiredScopes":["assets:write"],"rowBoundaries":"unrestricted","principalClaim":"principal","operations":["create","get","list"],"readableFields":["code"],"writableFields":["code"]}}}}}},"site":{{"primaryDataset":"neutral-registry","route":"sites","mutationMode":"create-only","fields":[{{"id":"code","type":"string","maximumLength":8,"classification":"internal"}}{site_secret}],"accessProfiles":{{"reader":{{"requiredScopes":["assets:write"],"rowBoundaries":"unrestricted","principalClaim":"principal","operations":["create","get","list"],"readableFields":["code"],"writableFields":["code"]}}}}}}}}}}"# ) .into_bytes() } diff --git a/crates/registry-breg/tests/migration_review_permission_order.rs b/crates/registry-breg/tests/migration_review_permission_order.rs index c8a4c06fd0..6c7af8147e 100644 --- a/crates/registry-breg/tests/migration_review_permission_order.rs +++ b/crates/registry-breg/tests/migration_review_permission_order.rs @@ -15,7 +15,7 @@ fn proposal_grant(operations: Value, client: &str) -> Value { "requesterClients":[client], "permissions":{"records":[ {"recordType":"case","operations":["get","list"],"readableFields":["label"],"rowBoundaries":"unrestricted"}], - "proposals":[{"action":"correct-case","operations":operations,"ownership":"caller", + "proposals":[{"action":"correct-case","operations":operations,"party":"owner", "targets":[{"recordType":"case","rowBoundaries":"unrestricted"}]}]} }) } diff --git a/crates/registry-breg/tests/native_inspection_inventory.rs b/crates/registry-breg/tests/native_inspection_inventory.rs index 9d1f18f02a..98202d6bda 100644 --- a/crates/registry-breg/tests/native_inspection_inventory.rs +++ b/crates/registry-breg/tests/native_inspection_inventory.rs @@ -620,7 +620,8 @@ fn event_inspection_uses_owner_hooks_for_phase_and_transitions() { "review-returned", "added", "asked", - "answered" + "answered", + "messaged" ]) ); let model = inspect_registry(®istry); diff --git a/crates/registry-breg/tests/native_plan_security.rs b/crates/registry-breg/tests/native_plan_security.rs index fac5d30fa6..1571bd2ff4 100644 --- a/crates/registry-breg/tests/native_plan_security.rs +++ b/crates/registry-breg/tests/native_plan_security.rs @@ -19,7 +19,7 @@ fn source() -> Value { {"id":"unbound","type":"string","maximumLength":64,"classification":"restricted"}], "plan":{"type":"scripted","actionPlan":"calculate","inputs":["label"], "writes":[{"id":"item","target":{"recordType":"item"},"operation":"create","fields":["label"]}]}}}, - "accessProfiles":{"registrar": {"default":true,"principalClaim":"registry_principal","requiredScopes":"unrestricted", + "accessProfiles":{"registrar": {"default":true,"principalClaim":"registry_principal","requiredScopes":["records:write"], "permissions":{"actions":[{"action":"register-item","operations":["invoke"],"targets":[{"recordType":"item","rowBoundaries":"unrestricted"}],"results":["item"]}]}}}}) } fn compile(script: &str) -> Result { diff --git a/crates/registry-breg/tests/native_source_conventions.rs b/crates/registry-breg/tests/native_source_conventions.rs index 8057fd8d4d..ec66b91022 100644 --- a/crates/registry-breg/tests/native_source_conventions.rs +++ b/crates/registry-breg/tests/native_source_conventions.rs @@ -901,7 +901,7 @@ fn duplicate_presentation_text_warns_in_each_breg_namespace() { "/manifestProjection/distributions/1/title", ), ( - "breg.manifest-entity.duplicate-title", + "breg.manifest-record-type.duplicate-title", "/manifestProjection/entities/1/title", ), ( diff --git a/crates/registry-breg/tests/odrl_export.rs b/crates/registry-breg/tests/odrl_export.rs index e4788c9d97..b1af7928ef 100644 --- a/crates/registry-breg/tests/odrl_export.rs +++ b/crates/registry-breg/tests/odrl_export.rs @@ -338,28 +338,6 @@ fn row_membership_and_consent_restrictions_omit_the_complete_read_grant() { json!([]) ); - let membership = compile_project( - &parse_project_yaml(MEMBERSHIP).unwrap(), - &[], - CompileProfile::Authoring, - ) - .unwrap(); - let membership_export = export_odrl(&membership, Some("member")).unwrap(); - let membership_reads = membership_export.coverage["grants"] - .as_array() - .unwrap() - .iter() - .filter(|grant| grant["operation"] == "get" || grant["operation"] == "list") - .collect::>(); - assert_eq!(membership_reads.len(), 2); - assert!(membership_reads.iter().all(|grant| { - grant["status"] == "omitted" - && grant["reasons"] - .as_array() - .unwrap() - .contains(&json!("membership-boundaries")) - })); - let consent = compile_with_modules(CONSENT, &[CONSENT_PERSON, CONSENT_CORE]); let consent_export = export_odrl(&consent, Some("food-targeting")).unwrap(); assert!(consent_export.coverage["grants"] @@ -691,3 +669,32 @@ fn profile_declares_every_emitted_extension_and_adopts_read() { "one collection and thirteen term definitions" ); } + +#[test] +fn a_membership_only_read_grant_is_omitted_from_the_odrl_export() { + let membership = compile_project( + &parse_project_yaml(MEMBERSHIP).unwrap(), + &[], + CompileProfile::Authoring, + ) + .unwrap(); + let membership_export = export_odrl(&membership, Some("member")).unwrap(); + let membership_reads = membership_export.coverage["grants"] + .as_array() + .unwrap() + .iter() + .filter(|grant| grant["operation"] == "get" || grant["operation"] == "list") + .collect::>(); + assert_eq!(membership_reads.len(), 2); + assert!(membership_reads.iter().all(|grant| { + grant["status"] == "omitted" + && grant["reasons"] + .as_array() + .unwrap() + .contains(&json!("membership-boundaries")) + })); + assert_eq!( + document(&membership_export, "generated/odrl/policies.jsonld")["@graph"], + json!([]) + ); +} diff --git a/crates/registry-breg/tests/ordered_plan_contract.rs b/crates/registry-breg/tests/ordered_plan_contract.rs index d834cd4936..5330ae499c 100644 --- a/crates/registry-breg/tests/ordered_plan_contract.rs +++ b/crates/registry-breg/tests/ordered_plan_contract.rs @@ -16,7 +16,7 @@ fn project() -> Value { {"id":"parent","type":"reference","target":"entry","classification":"internal"}]}}, "actions":{"create-pair": {"execution":{"mode":"immediate"},"inputs":[{"id":"name","type":"string","maximumLength":32,"required":true,"classification":"internal"}], "plan":{"type":"fixed","effects":[{"id":"z-result","target":{"recordType":"entry"},"operation":"create","set":{"name":{"fromInput":"name"}}},{"id":"a-result","target":{"recordType":"entry"},"operation":"create","set":{"name":{"fromInput":"name"}}}]}}}, - "accessProfiles":{"creator": {"default":true,"principalClaim":"principal","requiredScopes":"unrestricted","permissions":{"actions":[{"action":"create-pair","operations":["invoke"],"targets":[{"recordType":"entry","rowBoundaries":"unrestricted"}],"results":["z-result","a-result"]}]}}} + "accessProfiles":{"creator": {"default":true,"principalClaim":"principal","requiredScopes":["records:write"],"permissions":{"actions":[{"action":"create-pair","operations":["invoke"],"targets":[{"recordType":"entry","rowBoundaries":"unrestricted"}],"results":["z-result","a-result"]}]}}} }) } fn compile( diff --git a/crates/registry-breg/tests/package_change_plan.rs b/crates/registry-breg/tests/package_change_plan.rs index 2be5fc3237..354faf057d 100644 --- a/crates/registry-breg/tests/package_change_plan.rs +++ b/crates/registry-breg/tests/package_change_plan.rs @@ -1025,10 +1025,10 @@ fn metadata_only_access_or_disclosure_changes_create_empty_applicable_plans() { fn complete_extension_surface_modules_are_order_independent() { let field_module = parse_module_yaml(br#"{"apiVersion":"id.registrystack.org/formats/breg/module/v1alpha1","kind":"BRegModule","id":"field-extension","version":"1","extendRecordTypes":{"asset": {"fields":[{"id":"status","type":"string","maximumLength":16,"classification":"internal"}],"constraints":[{"type":"unique","id":"status-unique","fields":["status"]}],"indexes":[{"id":"status-idx","fields":["status"]}]}}}"#) .expect("field extension parses"); - let event_module = parse_module_yaml(br#"{"apiVersion":"id.registrystack.org/formats/breg/module/v1alpha1","kind":"BRegModule","id":"event-extension","version":"1","extendRecordTypes":{"asset": {"accessProfiles":{"auditor": {"principalClaim":"principal","operations":["get","list"],"readableFields":["code","status"],"writableFields":[], "requiredScopes":"unrestricted","rowBoundaries":"unrestricted"}},"hooks":[{"phase":"after","id":"asset-created","trigger":"created","projection":["code","status"],"handler":{"type":"url","destinationId":"package-change-events"}}]}},"recordTypes":{"site": {"primaryDataset":"neutral-registry","route":"sites","mutationMode":"create-only","fields":[{"id":"code","type":"string","maximumLength":8,"classification":"internal"}],"accessProfiles":{"reader": {"principalClaim":"principal","operations":["create","get","list"],"readableFields":["code"],"writableFields":["code"], "requiredScopes":"unrestricted","rowBoundaries":"unrestricted"}}}}}"#) + let event_module = parse_module_yaml(br#"{"apiVersion":"id.registrystack.org/formats/breg/module/v1alpha1","kind":"BRegModule","id":"event-extension","version":"1","extendRecordTypes":{"asset": {"accessProfiles":{"auditor": {"principalClaim":"principal","operations":["get","list"],"readableFields":["code","status"],"writableFields":[], "requiredScopes":"unrestricted","rowBoundaries":"unrestricted"}},"hooks":[{"phase":"after","id":"asset-created","trigger":"created","projection":["code","status"],"handler":{"type":"url","destinationId":"package-change-events"}}]}},"recordTypes":{"site": {"primaryDataset":"neutral-registry","route":"sites","mutationMode":"create-only","fields":[{"id":"code","type":"string","maximumLength":8,"classification":"internal"},{"id":"owner","type":"string","maximumLength":255,"classification":"internal"}],"accessProfiles":{"reader": {"principalClaim":"principal","operations":["create","get","list"],"readableFields":["code"],"writableFields":["code","owner"], "requiredScopes":"unrestricted","rowBoundaries":[{"field":"owner","claim":"principal","operator":"equals"}]}}}}}"#) .expect("event extension parses"); let project_bytes = format!( - r#"{{"datasets":{{"neutral-registry": {{}}}},"apiVersion":"id.registrystack.org/formats/breg/project/v1alpha1","kind":"BRegProject","project":{{"id":"neutral-registry","version":"1","defaultLanguage":"en","canonicalBaseIri":"https://package.example.test"}},"package":{{"sourceRevision":"{SOURCE_REVISION}"}},"manifestProjection":{{"accessProfile":"reader","classificationCeiling":"internal","catalog":{{"baseUrl":"https://package.example.test","title":"Neutral Registry Catalog","publisher":{{"id":"neutral-registry-authority","name":"Package Test Publisher"}}}},"authorities":[{{"id":"neutral-registry-authority","name":"Package Test Publisher"}}],"publicServices":[{{"id":"neutral-registry-service","title":"Neutral Registry Catalog","competentAuthority":"neutral-registry-authority"}}],"datasets":[{{"id":"neutral-registry","title":"Neutral Registry Dataset","owner":"Package Test Publisher","status":"active"}}],"dataServices":[{{"id":"neutral-registry-data-service","title":"Neutral Registry Catalog","endpointUrl":"https://package.example.test","servesDatasets":["neutral-registry"]}}]}},"recordTypes":{{"asset":{{"primaryDataset":"neutral-registry","route":"assets","mutationMode":"create-only","fields":[{{"id":"code","type":"string","maximumLength":8,"classification":"internal"}}]}}}},"accessProfiles":{{"reader":{{"default":true,"principalClaim":"principal","requiredScopes":"unrestricted","permissions":{{"records":[{{"rowBoundaries": "unrestricted", "recordType":"asset","operations":["create","get","list"],"readableFields":["code"],"writableFields":["code"]}}]}}}}}},"modules":{{"field-extension":{{"version":"1","digest":"{}"}},"event-extension":{{"version":"1","digest":"{}"}}}}}}"#, + r#"{{"datasets":{{"neutral-registry": {{}}}},"apiVersion":"id.registrystack.org/formats/breg/project/v1alpha1","kind":"BRegProject","project":{{"id":"neutral-registry","version":"1","defaultLanguage":"en","canonicalBaseIri":"https://package.example.test"}},"package":{{"sourceRevision":"{SOURCE_REVISION}"}},"manifestProjection":{{"accessProfile":"reader","classificationCeiling":"internal","catalog":{{"baseUrl":"https://package.example.test","title":"Neutral Registry Catalog","publisher":{{"id":"neutral-registry-authority","name":"Package Test Publisher"}}}},"authorities":[{{"id":"neutral-registry-authority","name":"Package Test Publisher"}}],"publicServices":[{{"id":"neutral-registry-service","title":"Neutral Registry Catalog","competentAuthority":"neutral-registry-authority"}}],"datasets":[{{"id":"neutral-registry","title":"Neutral Registry Dataset","owner":"Package Test Publisher","status":"active"}}],"dataServices":[{{"id":"neutral-registry-data-service","title":"Neutral Registry Catalog","endpointUrl":"https://package.example.test","servesDatasets":["neutral-registry"]}}]}},"recordTypes":{{"asset":{{"primaryDataset":"neutral-registry","route":"assets","mutationMode":"create-only","fields":[{{"id":"code","type":"string","maximumLength":8,"classification":"internal"}},{{"id":"owner","type":"string","maximumLength":255,"classification":"internal"}}]}}}},"accessProfiles":{{"reader":{{"default":true,"principalClaim":"principal","requiredScopes":"unrestricted","permissions":{{"records":[{{"rowBoundaries": [{{"field":"owner","claim":"principal","operator":"equals"}}], "recordType":"asset","operations":["create","get","list"],"readableFields":["code"],"writableFields":["code","owner"]}}]}}}}}},"modules":{{"field-extension":{{"version":"1","digest":"{}"}},"event-extension":{{"version":"1","digest":"{}"}}}}}}"#, module_digest(&field_module), module_digest(&event_module) ); @@ -2242,7 +2242,8 @@ fn vocabulary_registry(vocabulary: &str, values: &[&str]) -> CompiledRegistry { "vocabulary": vocabulary, "required": true, "classification": "internal" - } + }, + {"id": "owner", "type": "string", "maximumLength": 255, "classification": "internal"} ] }}, "accessProfiles": {"writer": { @@ -2253,8 +2254,8 @@ fn vocabulary_registry(vocabulary: &str, values: &[&str]) -> CompiledRegistry { "recordType": "entry", "operations": ["create", "get", "list", "patch"], "readableFields": ["status"], - "writableFields": ["status"], - "rowBoundaries": "unrestricted" + "writableFields": ["status", "owner"], + "rowBoundaries": [{"field": "owner", "claim": "registry_principal", "operator": "equals"}] }]} }} }); @@ -2311,7 +2312,7 @@ fn field_registry(field: serde_json::Value) -> CompiledRegistry { "primaryDataset": "test-dataset", "route": "entries", "mutationMode": "mutable", - "fields": [field] + "fields": [field, {"id": "owner", "type": "string", "maximumLength": 255, "classification": "internal"}] }}, "accessProfiles": {"writer": { "default": true, @@ -2321,8 +2322,8 @@ fn field_registry(field: serde_json::Value) -> CompiledRegistry { "recordType": "entry", "operations": ["create", "get", "list", "patch"], "readableFields": ["note"], - "writableFields": ["note"], - "rowBoundaries": "unrestricted" + "writableFields": ["note", "owner"], + "rowBoundaries": [{"field": "owner", "claim": "registry_principal", "operator": "equals"}] }]} }} }); @@ -2417,6 +2418,7 @@ fn geojson_source(binding: Option<&str>) -> SourceFixture { serde_json::from_slice(&module_bytes(Variant::Base)).unwrap(); let entity = &mut module["recordTypes"]["asset"]; let fields = entity["fields"].as_array_mut().unwrap(); + fields.retain(|field| field["id"] != "owner"); for id in ["location", "alternate"] { fields.push(serde_json::json!({ "id": id, "type": "crs84-point", "precision": 9, "classification": "internal" @@ -2424,6 +2426,7 @@ fn geojson_source(binding: Option<&str>) -> SourceFixture { } entity["accessProfiles"]["reader"]["operations"] = serde_json::json!(["get"]); entity["accessProfiles"]["reader"]["writableFields"] = serde_json::json!([]); + entity["accessProfiles"]["reader"]["rowBoundaries"] = serde_json::json!("unrestricted"); entity["accessProfiles"]["reader"]["readableFields"] = serde_json::json!(["code", "location", "alternate"]); if let Some(binding) = binding { @@ -2526,7 +2529,7 @@ fn module_bytes(variant: Variant) -> Vec { Variant::OptionalField => asset_entity( r#"{"id":"code","type":"string","maximumLength":8,"classification":"internal"},{"id":"rank","type":"int64","classification":"internal"},{"id":"color","type":"string","maximumLength":16,"classification":"internal"}"#, r#""route":"assets""#, - r#""requiredScopes":"unrestricted","principalClaim":"principal","operations":["create","get","list"],"readableFields":["code"],"writableFields":["code"]"#, + r#""requiredScopes":"unrestricted","principalClaim":"principal","rowBoundaries":[{"field":"owner","claim":"principal","operator":"equals"}],"operations":["create","get","list"],"readableFields":["code"],"writableFields":["code","owner"]"#, "", "", "", @@ -2534,7 +2537,7 @@ fn module_bytes(variant: Variant) -> Vec { Variant::RequiredField => asset_entity( r#"{"id":"code","type":"string","maximumLength":8,"classification":"internal"},{"id":"rank","type":"int64","classification":"internal"},{"id":"batch","type":"string","maximumLength":16,"required":true,"classification":"internal"}"#, r#""route":"assets""#, - r#""requiredScopes":"unrestricted","principalClaim":"principal","operations":["create","get","list"],"readableFields":["code"],"writableFields":["code"]"#, + r#""requiredScopes":"unrestricted","principalClaim":"principal","rowBoundaries":[{"field":"owner","claim":"principal","operator":"equals"}],"operations":["create","get","list"],"readableFields":["code"],"writableFields":["code","owner"]"#, "", "", "", @@ -2542,7 +2545,7 @@ fn module_bytes(variant: Variant) -> Vec { Variant::RequiredAndOptionalFields => asset_entity( r#"{"id":"code","type":"string","maximumLength":8,"classification":"internal"},{"id":"rank","type":"int64","classification":"internal"},{"id":"batch","type":"string","maximumLength":16,"required":true,"classification":"internal"},{"id":"color","type":"string","maximumLength":16,"classification":"internal"}"#, r#""route":"assets""#, - r#""requiredScopes":"unrestricted","principalClaim":"principal","operations":["create","get","list"],"readableFields":["code"],"writableFields":["code"]"#, + r#""requiredScopes":"unrestricted","principalClaim":"principal","rowBoundaries":[{"field":"owner","claim":"principal","operator":"equals"}],"operations":["create","get","list"],"readableFields":["code"],"writableFields":["code","owner"]"#, "", "", "", @@ -2550,7 +2553,7 @@ fn module_bytes(variant: Variant) -> Vec { Variant::ReferenceConstraintIndex => asset_entity( r#"{"id":"code","type":"string","maximumLength":8,"classification":"internal"},{"id":"rank","type":"int64","classification":"internal"},{"id":"site","type":"reference","target":"site","classification":"internal"}"#, r#""route":"assets""#, - r#""requiredScopes":"unrestricted","principalClaim":"principal","operations":["create","get","list"],"readableFields":["code"],"writableFields":["code"]"#, + r#""requiredScopes":"unrestricted","principalClaim":"principal","rowBoundaries":[{"field":"owner","claim":"principal","operator":"equals"}],"operations":["create","get","list"],"readableFields":["code"],"writableFields":["code","owner"]"#, r#","constraints":[{"type":"unique","id":"code-unique","fields":["code"]}]"#, r#","indexes":[{"id":"code-idx","fields":["code"]}]"#, "", @@ -2558,7 +2561,7 @@ fn module_bytes(variant: Variant) -> Vec { Variant::ReferenceConstraintIndexReordered => asset_entity( r#"{"id":"site","type":"reference","target":"site","classification":"internal"},{"id":"rank","type":"int64","classification":"internal"},{"id":"code","type":"string","maximumLength":8,"classification":"internal"}"#, r#""route":"assets""#, - r#""requiredScopes":"unrestricted","principalClaim":"principal","operations":["list","get","create"],"writableFields":["code"],"readableFields":["code"]"#, + r#""requiredScopes":"unrestricted","principalClaim":"principal","rowBoundaries":[{"field":"owner","claim":"principal","operator":"equals"}],"operations":["list","get","create"],"writableFields":["code","owner"],"readableFields":["code"]"#, r#","constraints":[{"fields":["code"],"id":"code-unique","type":"unique"}]"#, r#","indexes":[{"fields":["code"],"id":"code-idx"}]"#, "", @@ -2566,7 +2569,7 @@ fn module_bytes(variant: Variant) -> Vec { Variant::FieldRemoved => asset_entity( r#"{"id":"code","type":"string","maximumLength":8,"classification":"internal"}"#, r#""route":"assets""#, - r#""requiredScopes":"unrestricted","principalClaim":"principal","operations":["create","get","list"],"readableFields":["code"],"writableFields":["code"]"#, + r#""requiredScopes":"unrestricted","principalClaim":"principal","rowBoundaries":[{"field":"owner","claim":"principal","operator":"equals"}],"operations":["create","get","list"],"readableFields":["code"],"writableFields":["code","owner"]"#, "", "", "", @@ -2574,7 +2577,7 @@ fn module_bytes(variant: Variant) -> Vec { Variant::TypeChanged => asset_entity( r#"{"id":"code","type":"string","maximumLength":8,"classification":"internal"},{"id":"rank","type":"string","maximumLength":8,"classification":"internal"}"#, r#""route":"assets""#, - r#""requiredScopes":"unrestricted","principalClaim":"principal","operations":["create","get","list"],"readableFields":["code"],"writableFields":["code"]"#, + r#""requiredScopes":"unrestricted","principalClaim":"principal","rowBoundaries":[{"field":"owner","claim":"principal","operator":"equals"}],"operations":["create","get","list"],"readableFields":["code"],"writableFields":["code","owner"]"#, "", "", "", @@ -2582,7 +2585,7 @@ fn module_bytes(variant: Variant) -> Vec { Variant::PlaintextSecret => asset_entity( r#"{"id":"code","type":"string","maximumLength":8,"classification":"internal"},{"id":"secret","type":"string","maximumLength":64,"classification":"restricted"}"#, r#""route":"assets""#, - r#""requiredScopes":"unrestricted","principalClaim":"principal","operations":["create","get","list"],"readableFields":["code"],"writableFields":["code"]"#, + r#""requiredScopes":"unrestricted","principalClaim":"principal","rowBoundaries":[{"field":"owner","claim":"principal","operator":"equals"}],"operations":["create","get","list"],"readableFields":["code"],"writableFields":["code","owner"]"#, "", "", "", @@ -2590,7 +2593,7 @@ fn module_bytes(variant: Variant) -> Vec { Variant::EncryptedStructuredSecret => asset_entity( r#"{"id":"code","type":"string","maximumLength":8,"classification":"internal"},{"id":"secret","type":"structured","maximumBytes":1024,"schema":{"type":"object","additionalProperties":false},"classification":"restricted","encrypted":true}"#, r#""route":"assets""#, - r#""requiredScopes":"unrestricted","principalClaim":"principal","operations":["create","get","list"],"readableFields":["code"],"writableFields":["code"]"#, + r#""requiredScopes":"unrestricted","principalClaim":"principal","rowBoundaries":[{"field":"owner","claim":"principal","operator":"equals"}],"operations":["create","get","list"],"readableFields":["code"],"writableFields":["code","owner"]"#, "", "", "", @@ -2598,7 +2601,7 @@ fn module_bytes(variant: Variant) -> Vec { Variant::RouteChanged => asset_entity( base_asset_fields(), r#""route":"equipment""#, - r#""requiredScopes":"unrestricted","principalClaim":"principal","operations":["create","get","list"],"readableFields":["code"],"writableFields":["code"]"#, + r#""requiredScopes":"unrestricted","principalClaim":"principal","rowBoundaries":[{"field":"owner","claim":"principal","operator":"equals"}],"operations":["create","get","list"],"readableFields":["code"],"writableFields":["code","owner"]"#, "", "", "", @@ -2606,7 +2609,7 @@ fn module_bytes(variant: Variant) -> Vec { Variant::EntityClassificationChanged => asset_entity( base_asset_fields(), r#""route":"assets","classification":"restricted""#, - r#""requiredScopes":"unrestricted","principalClaim":"principal","operations":["create","get","list"],"readableFields":["code"],"writableFields":["code"]"#, + r#""requiredScopes":"unrestricted","principalClaim":"principal","rowBoundaries":[{"field":"owner","claim":"principal","operator":"equals"}],"operations":["create","get","list"],"readableFields":["code"],"writableFields":["code","owner"]"#, "", "", "", @@ -2614,7 +2617,7 @@ fn module_bytes(variant: Variant) -> Vec { Variant::ClassificationChanged => asset_entity( r#"{"id":"code","type":"string","maximumLength":8,"classification":"internal"},{"id":"rank","type":"int64","classification":"restricted"}"#, r#""route":"assets""#, - r#""requiredScopes":"unrestricted","principalClaim":"principal","operations":["create","get","list"],"readableFields":["code"],"writableFields":["code"]"#, + r#""requiredScopes":"unrestricted","principalClaim":"principal","rowBoundaries":[{"field":"owner","claim":"principal","operator":"equals"}],"operations":["create","get","list"],"readableFields":["code"],"writableFields":["code","owner"]"#, "", "", "", @@ -2622,7 +2625,7 @@ fn module_bytes(variant: Variant) -> Vec { Variant::AuthorizationChanged => asset_entity( base_asset_fields(), r#""route":"assets""#, - r#""requiredScopes":"unrestricted","principalClaim":"subject","operations":["create","get","list"],"readableFields":["code"],"writableFields":["code"]"#, + r#""requiredScopes":"unrestricted","principalClaim":"subject","rowBoundaries":[{"field":"owner","claim":"subject","operator":"equals"}],"operations":["create","get","list"],"readableFields":["code"],"writableFields":["code","owner"]"#, "", "", "", @@ -2631,7 +2634,7 @@ fn module_bytes(variant: Variant) -> Vec { base_asset_fields(), r#""route":"assets""#, "mutable", - r#""requiredScopes":"unrestricted","principalClaim":"principal","operations":["create","get","list"],"readableFields":["code"],"writableFields":["code"]"#, + r#""requiredScopes":"unrestricted","principalClaim":"principal","rowBoundaries":[{"field":"owner","claim":"principal","operator":"equals"}],"operations":["create","get","list"],"readableFields":["code"],"writableFields":["code","owner"]"#, "", "", "", @@ -2639,7 +2642,7 @@ fn module_bytes(variant: Variant) -> Vec { Variant::TemporalChanged => asset_entity( r#"{"id":"code","type":"string","maximumLength":8,"required":true,"classification":"internal"},{"id":"rank","type":"int64","classification":"internal"},{"id":"valid-from","type":"date","required":true,"classification":"internal"},{"id":"valid-to","type":"date","classification":"internal"}"#, r#""route":"assets""#, - r#""requiredScopes":"unrestricted","principalClaim":"principal","operations":["create","get","list"],"readableFields":["code","valid-from","valid-to"],"writableFields":["code","valid-from","valid-to"]"#, + r#""requiredScopes":"unrestricted","principalClaim":"principal","rowBoundaries":[{"field":"owner","claim":"principal","operator":"equals"}],"operations":["create","get","list"],"readableFields":["code","valid-from","valid-to"],"writableFields":["code","valid-from","valid-to","owner"]"#, r#","constraints":[{"type":"temporal-non-overlap","id":"code-time","scopeFields":["code"],"startField":"valid-from","endField":"valid-to"}]"#, "", r#","temporal":{"startField":"valid-from","endField":"valid-to"}"#, @@ -2647,7 +2650,7 @@ fn module_bytes(variant: Variant) -> Vec { Variant::TemporalRoleBase => asset_entity( r#"{"id":"code","type":"string","maximumLength":8,"classification":"internal"},{"id":"rank","type":"int64","classification":"internal"},{"id":"valid-from","type":"date","required":true,"classification":"internal"},{"id":"valid-to","type":"date","classification":"internal"}"#, r#""route":"assets""#, - r#""requiredScopes":"unrestricted","principalClaim":"principal","operations":["create","get","list"],"readableFields":["code","valid-from","valid-to"],"writableFields":["code","valid-from","valid-to"]"#, + r#""requiredScopes":"unrestricted","principalClaim":"principal","rowBoundaries":[{"field":"owner","claim":"principal","operator":"equals"}],"operations":["create","get","list"],"readableFields":["code","valid-from","valid-to"],"writableFields":["code","valid-from","valid-to","owner"]"#, "", "", "", @@ -2655,7 +2658,7 @@ fn module_bytes(variant: Variant) -> Vec { Variant::TemporalRoleChanged => asset_entity( r#"{"id":"code","type":"string","maximumLength":8,"classification":"internal"},{"id":"rank","type":"int64","classification":"internal"},{"id":"valid-from","type":"date","required":true,"classification":"internal","validTimeRole":"valid-from"},{"id":"valid-to","type":"date","classification":"internal"}"#, r#""route":"assets""#, - r#""requiredScopes":"unrestricted","principalClaim":"principal","operations":["create","get","list"],"readableFields":["code","valid-from","valid-to"],"writableFields":["code","valid-from","valid-to"]"#, + r#""requiredScopes":"unrestricted","principalClaim":"principal","rowBoundaries":[{"field":"owner","claim":"principal","operator":"equals"}],"operations":["create","get","list"],"readableFields":["code","valid-from","valid-to"],"writableFields":["code","valid-from","valid-to","owner"]"#, "", "", "", @@ -2663,7 +2666,7 @@ fn module_bytes(variant: Variant) -> Vec { Variant::RankRequired => asset_entity( r#"{"id":"code","type":"string","maximumLength":8,"classification":"internal"},{"id":"rank","type":"int64","required":true,"classification":"internal"}"#, r#""route":"assets""#, - r#""requiredScopes":"unrestricted","principalClaim":"principal","operations":["create","get","list"],"readableFields":["code"],"writableFields":["code"]"#, + r#""requiredScopes":"unrestricted","principalClaim":"principal","rowBoundaries":[{"field":"owner","claim":"principal","operator":"equals"}],"operations":["create","get","list"],"readableFields":["code"],"writableFields":["code","owner"]"#, "", "", "", @@ -2671,7 +2674,7 @@ fn module_bytes(variant: Variant) -> Vec { Variant::ReferenceTargetBase => asset_entity( r#"{"id":"code","type":"string","maximumLength":8,"classification":"internal"},{"id":"rank","type":"int64","classification":"internal"},{"id":"home-site","type":"reference","target":"site","classification":"internal"}"#, r#""route":"assets""#, - r#""requiredScopes":"unrestricted","principalClaim":"principal","operations":["create","get","list"],"readableFields":["code"],"writableFields":["code"]"#, + r#""requiredScopes":"unrestricted","principalClaim":"principal","rowBoundaries":[{"field":"owner","claim":"principal","operator":"equals"}],"operations":["create","get","list"],"readableFields":["code"],"writableFields":["code","owner"]"#, "", "", "", @@ -2679,7 +2682,7 @@ fn module_bytes(variant: Variant) -> Vec { Variant::ReferenceTargetChanged => asset_entity( r#"{"id":"code","type":"string","maximumLength":8,"classification":"internal"},{"id":"rank","type":"int64","classification":"internal"},{"id":"home-site","type":"reference","target":"location","classification":"internal"}"#, r#""route":"assets""#, - r#""requiredScopes":"unrestricted","principalClaim":"principal","operations":["create","get","list"],"readableFields":["code"],"writableFields":["code"]"#, + r#""requiredScopes":"unrestricted","principalClaim":"principal","rowBoundaries":[{"field":"owner","claim":"principal","operator":"equals"}],"operations":["create","get","list"],"readableFields":["code"],"writableFields":["code","owner"]"#, "", "", "", @@ -2687,7 +2690,7 @@ fn module_bytes(variant: Variant) -> Vec { Variant::MetadataOnlyBase => asset_entity( r#"{"id":"code","type":"string","maximumLength":8,"classification":"internal"},{"id":"rank","type":"int64","classification":"internal"},{"id":"valid-from","type":"date","required":true,"classification":"internal"},{"id":"valid-to","type":"date","classification":"internal"}"#, r#""route":"assets""#, - r#""requiredScopes":"unrestricted","principalClaim":"principal","operations":["create","get","list"],"readableFields":["code","valid-from","valid-to"],"writableFields":["code","valid-from","valid-to"]"#, + r#""requiredScopes":"unrestricted","principalClaim":"principal","rowBoundaries":[{"field":"owner","claim":"principal","operator":"equals"}],"operations":["create","get","list"],"readableFields":["code","valid-from","valid-to"],"writableFields":["code","valid-from","valid-to","owner"]"#, "", "", r#","hooks":[{"phase":"after","id":"asset-created","trigger":"created","projection":["code"],"handler":{"type":"url","destinationId":"package-change-events"}}]"#, @@ -2696,7 +2699,7 @@ fn module_bytes(variant: Variant) -> Vec { r#"{"id":"code","type":"string","maximumLength":8,"classification":"internal"},{"id":"rank","type":"int64","classification":"restricted"},{"id":"valid-from","type":"date","required":true,"classification":"internal","validTimeRole":"valid-from"},{"id":"valid-to","type":"date","classification":"internal"}"#, r#""route":"equipment","classification":"restricted","accessRequirements":{"requiredScopes":["asset:read"]}"#, "mutable", - r#""principalClaim":"subject","requiredScopes":["asset:read"],"operations":["create","get","list"],"readableFields":["code","valid-from","valid-to"],"writableFields":["code","valid-from","valid-to"]"#, + r#""principalClaim":"subject","rowBoundaries":[{"field":"owner","claim":"subject","operator":"equals"}],"requiredScopes":["asset:read"],"operations":["create","get","list"],"readableFields":["code","valid-from","valid-to"],"writableFields":["code","valid-from","valid-to","owner"]"#, "", "", r#","hooks":[{"phase":"after","id":"asset-created","trigger":"created","projection":["code","rank"],"handler":{"type":"url","destinationId":"package-change-events"}}]"#, @@ -2704,7 +2707,7 @@ fn module_bytes(variant: Variant) -> Vec { Variant::Base | Variant::NewEntity => asset_entity( base_asset_fields(), r#""route":"assets""#, - r#""requiredScopes":"unrestricted","principalClaim":"principal","operations":["create","get","list"],"readableFields":["code"],"writableFields":["code"]"#, + r#""requiredScopes":"unrestricted","principalClaim":"principal","rowBoundaries":[{"field":"owner","claim":"principal","operator":"equals"}],"operations":["create","get","list"],"readableFields":["code"],"writableFields":["code","owner"]"#, "", "", "", @@ -2763,20 +2766,20 @@ fn asset_entity_with_mode( temporal: &str, ) -> String { format!( - r#""asset":{{"primaryDataset":"neutral-registry",{route},"mutationMode":"{mutation_mode}","fields":[{fields}]{constraints}{indexes},"accessProfiles":{{"reader":{{"rowBoundaries":"unrestricted",{access}}}}}{temporal}}}"# + r#""asset":{{"primaryDataset":"neutral-registry",{route},"mutationMode":"{mutation_mode}","fields":[{fields},{{"id":"owner","type":"string","maximumLength":255,"classification":"internal"}}]{constraints}{indexes},"accessProfiles":{{"reader":{{{access}}}}}{temporal}}}"# ) } fn site_entity() -> &'static str { - r#""site":{"primaryDataset":"neutral-registry","route":"sites","mutationMode":"create-only","fields":[{"id":"code","type":"string","maximumLength":8,"classification":"internal"}],"accessProfiles":{"reader": {"principalClaim":"principal","operations":["create","get","list"],"readableFields":["code"],"writableFields":["code"], "requiredScopes":"unrestricted","rowBoundaries":"unrestricted"}}}"# + r#""site":{"primaryDataset":"neutral-registry","route":"sites","mutationMode":"create-only","fields":[{"id":"code","type":"string","maximumLength":8,"classification":"internal"},{"id":"owner","type":"string","maximumLength":255,"classification":"internal"}],"accessProfiles":{"reader": {"principalClaim":"principal","rowBoundaries":[{"field":"owner","claim":"principal","operator":"equals"}],"operations":["create","get","list"],"readableFields":["code"],"writableFields":["code","owner"], "requiredScopes":"unrestricted"}}}"# } fn location_entity() -> &'static str { - r#""location":{"primaryDataset":"neutral-registry","route":"locations","mutationMode":"create-only","fields":[{"id":"code","type":"string","maximumLength":8,"classification":"internal"}],"accessProfiles":{"reader": {"principalClaim":"principal","operations":["create","get","list"],"readableFields":["code"],"writableFields":["code"], "requiredScopes":"unrestricted","rowBoundaries":"unrestricted"}}}"# + r#""location":{"primaryDataset":"neutral-registry","route":"locations","mutationMode":"create-only","fields":[{"id":"code","type":"string","maximumLength":8,"classification":"internal"},{"id":"owner","type":"string","maximumLength":255,"classification":"internal"}],"accessProfiles":{"reader": {"principalClaim":"principal","rowBoundaries":[{"field":"owner","claim":"principal","operator":"equals"}],"operations":["create","get","list"],"readableFields":["code"],"writableFields":["code","owner"], "requiredScopes":"unrestricted"}}}"# } fn placement_entity() -> &'static str { - r#""placement":{"primaryDataset":"neutral-registry","route":"placements","mutationMode":"create-only","fields":[{"id":"asset","type":"reference","target":"asset","required":true,"classification":"internal"},{"id":"site","type":"reference","target":"site","required":true,"classification":"internal"}],"accessProfiles":{"reader": {"principalClaim":"principal","operations":["create","get","list"],"readableFields":["asset","site"],"writableFields":["asset","site"], "requiredScopes":"unrestricted","rowBoundaries":"unrestricted"}}}"# + r#""placement":{"primaryDataset":"neutral-registry","route":"placements","mutationMode":"create-only","fields":[{"id":"asset","type":"reference","target":"asset","required":true,"classification":"internal"},{"id":"site","type":"reference","target":"site","required":true,"classification":"internal"},{"id":"owner","type":"string","maximumLength":255,"classification":"internal"}],"accessProfiles":{"reader": {"principalClaim":"principal","rowBoundaries":[{"field":"owner","claim":"principal","operator":"equals"}],"operations":["create","get","list"],"readableFields":["asset","site"],"writableFields":["asset","site","owner"], "requiredScopes":"unrestricted"}}}"# } fn build_request( diff --git a/crates/registry-breg/tests/postgres_access_log.rs b/crates/registry-breg/tests/postgres_access_log.rs index 526e842389..df5b6e5065 100644 --- a/crates/registry-breg/tests/postgres_access_log.rs +++ b/crates/registry-breg/tests/postgres_access_log.rs @@ -354,6 +354,10 @@ fn token(idp: &MockIdp, client: &str, subject: &str) -> String { idp.mint_token(json!({"aud":AUDIENCE,"sub":subject,"client_id":client,"scope":"registry.read","registry_actor_kind":"service","registry_purpose":PURPOSE})) } +fn writer_token(idp: &MockIdp, client: &str, subject: &str) -> String { + idp.mint_token(json!({"aud":AUDIENCE,"sub":subject,"client_id":client,"scope":"registry.read records:write","registry_actor_kind":"service","registry_purpose":PURPOSE})) +} + async fn send( app: &Router, token: &str, @@ -490,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 ) @@ -547,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 ) @@ -973,7 +977,7 @@ fn compiled_with_history() -> CompiledRegistry { "revisionAccess":true,"rowBoundaries":"unrestricted"} ] }}, - "steward": {"principalClaim":"sub","requiredScopes":"unrestricted","requiredPurposes":[PURPOSE],"permissions":{ + "steward": {"principalClaim":"sub","requiredScopes":["records:write"],"requiredPurposes":[PURPOSE],"permissions":{ "records":[ {"recordType":"entry","operations":["create"],"readableFields":["subject","label"], "writableFields":["subject","label"],"rowBoundaries":"unrestricted"} @@ -1136,7 +1140,7 @@ async fn logged_operations(db: &TestDatabase, record: &str) -> Vec { #[tokio::test] async fn snapshot_and_revision_reads_write_subject_access_log_entries() { let (db, app, idp, registry) = setup_with_history().await; - let steward = token(&idp, "agency", "steward"); + let steward = writer_token(&idp, "agency", "steward"); let reader = token(&idp, "agency", "officer"); let request = Request::builder() .method(Method::POST) @@ -1261,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; } @@ -1311,7 +1315,7 @@ async fn head_on_subject_access_log_reads_is_refused_without_a_journaled_read() #[tokio::test] async fn head_on_history_reads_is_refused_without_a_journaled_read() { let (db, app, idp, _) = setup_with_history().await; - let steward = token(&idp, "agency", "steward"); + let steward = writer_token(&idp, "agency", "steward"); let reader = token(&idp, "agency", "officer"); let request = Request::builder() .method(Method::POST) @@ -1401,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, ) @@ -1425,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; @@ -1617,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)), ) @@ -1670,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); @@ -1729,7 +1773,7 @@ fn compiled_with_writes() -> CompiledRegistry { }; let entry_writes = json!(["get", "create", "patch", "batch", "tombstone"]); let profile = |reason: bool, records: Value| { - json!({"principalClaim":"sub","requiredScopes":"unrestricted", + json!({"principalClaim":"sub","requiredScopes":["records:write"], "requiredPurposes":[PURPOSE],"requireAccessReason":reason, "permissions":{"records":records}}) }; @@ -1854,7 +1898,7 @@ async fn logged_entries(db: &TestDatabase) -> Vec<(String, String, String, Optio #[tokio::test] async fn each_direct_write_under_a_reasoned_profile_logs_one_write_entry_with_its_reason() { let (db, app, idp, registry) = setup_with_mutations(compiled_with_writes(), None).await; - let clerk = token(&idp, "agency", "clerk"); + let clerk = writer_token(&idp, "agency", "clerk"); let (first, etag) = create_entry(&app, &clerk, "clerk", Some("create reason")).await; let (status, body, etag) = write_as( @@ -1959,7 +2003,7 @@ async fn each_direct_write_under_a_reasoned_profile_logs_one_write_entry_with_it #[tokio::test] async fn a_write_under_a_profile_without_the_flag_logs_no_write_entry() { let (db, app, idp, _) = setup_with_mutations(compiled_with_writes(), None).await; - let steward = token(&idp, "agency", "steward"); + let steward = writer_token(&idp, "agency", "steward"); let (record, etag) = create_entry(&app, &steward, "steward", None).await; let (status, body, _) = write_as( &app, @@ -1985,7 +2029,7 @@ async fn a_write_under_a_profile_without_the_flag_logs_no_write_entry() { #[tokio::test] async fn a_type_without_an_access_log_requires_the_reason_and_stores_nothing() { let (db, app, idp, _) = setup_with_mutations(compiled_with_writes(), None).await; - let clerk = token(&idp, "agency", "clerk"); + let clerk = writer_token(&idp, "agency", "clerk"); let note = || { Some(( "application/json", @@ -2030,7 +2074,7 @@ async fn a_rolled_back_write_leaves_no_write_entry() { Some(MutationFaultPoint::BeforeCommit), ) .await; - let clerk = token(&idp, "agency", "clerk"); + let clerk = writer_token(&idp, "agency", "clerk"); let (status, body, _) = write_as( &app, &clerk, @@ -2055,7 +2099,7 @@ async fn a_rolled_back_write_leaves_no_write_entry() { #[tokio::test] async fn a_write_entry_raises_no_read_alert() { let (db, app, idp, _) = setup_with_mutations(compiled_with_writes(), None).await; - let clerk = token(&idp, "agency", "clerk"); + let clerk = writer_token(&idp, "agency", "clerk"); let (record, _) = create_entry(&app, &clerk, "clerk", Some("create reason")).await; assert_eq!(logged_entries(&db).await.len(), 1); assert_eq!(read_alerts(&db).await, []); @@ -2079,8 +2123,8 @@ async fn a_write_entry_raises_no_read_alert() { #[tokio::test] async fn write_entries_keep_the_retention_and_exemption_delay_of_read_entries() { let (db, app, idp, _) = setup_with_mutations(compiled_with_writes(), None).await; - let clerk = token(&idp, "agency", "clerk"); - let investigator = token(&idp, "agency", "investigator"); + let clerk = writer_token(&idp, "agency", "clerk"); + let investigator = writer_token(&idp, "agency", "investigator"); let (prompt, _) = create_entry(&app, &clerk, "clerk", Some("create reason")).await; let (delayed, _) = create_entry(&app, &investigator, "investigator", Some("investigation")).await; diff --git a/crates/registry-breg/tests/postgres_action_handlers.rs b/crates/registry-breg/tests/postgres_action_handlers.rs index 5422bf3d99..c139d5bbf2 100644 --- a/crates/registry-breg/tests/postgres_action_handlers.rs +++ b/crates/registry-breg/tests/postgres_action_handlers.rs @@ -1072,7 +1072,7 @@ async fn absent_optional_copy_has_the_same_safe_failure_at_invoke_and_submit() { proposal["execution"] = json!({"mode":"proposal","proposal":{"review":{"type":"none"},"application":{"mode":"manual"},"retention":{"mode":"operator-erase"}}}); source["actions"]["invalid-proposal"] = proposal; source["accessProfiles"]["author"]["permissions"]["actions"].as_array_mut().unwrap().push(json!({"action":"invalid-proposal","operations":["start"],"targets":[{"recordType":"entry","rowBoundaries":"unrestricted"}]})); - source["accessProfiles"]["author"]["permissions"]["proposals"] = json!([{"action":"invalid-proposal","operations":["get","edit","submit","cancel"],"ownership":"caller","readableInputs":["note","private-data"],"writableInputs":["note","private-data"],"targets":[{"recordType":"entry","rowBoundaries":"unrestricted"}]}]); + source["accessProfiles"]["author"]["permissions"]["proposals"] = json!([{"action":"invalid-proposal","operations":["get","edit","submit","cancel"],"party":"owner","readableInputs":["note","private-data"],"writableInputs":["note","private-data"],"targets":[{"recordType":"entry","rowBoundaries":"unrestricted"}]}]); let project = registry_breg::contract::parse_project_json(&serde_json::to_vec(&source).unwrap()).unwrap(); let assets = [ @@ -1106,7 +1106,7 @@ async fn absent_optional_copy_has_the_same_safe_failure_at_invoke_and_submit() { let claims = VerifiedRequestClaims::authenticated_with_actor_kind( "sub", "author", - BTreeSet::new(), + BTreeSet::from(["entries:write".to_owned()]), None, BTreeMap::new(), registry_platform_oidc::ActorKind::Human, diff --git a/crates/registry-breg/tests/postgres_batch.rs b/crates/registry-breg/tests/postgres_batch.rs index 40b4d1b2ad..6e092b3eb3 100644 --- a/crates/registry-breg/tests/postgres_batch.rs +++ b/crates/registry-breg/tests/postgres_batch.rs @@ -957,7 +957,7 @@ fn compiled_timer_batch_registry() -> registry_breg::CompiledRegistry { .remove("service-editor") .expect("the future-activation example has a service-editor profile"); source["accessProfiles"]["operator"] = renamed; - source["accessProfiles"]["operator"]["requiredScopes"] = json!("unrestricted"); + source["accessProfiles"]["operator"]["requiredScopes"] = json!(["records:write"]); source["accessProfiles"]["operator"]["permissions"]["records"][0]["operations"] = json!(["create", "get", "list", "patch", "tombstone", "batch"]); let bytes = serde_json::to_vec(&source).expect("timer batch fixture serializes"); @@ -1074,7 +1074,7 @@ fn compiled_registry_with_create_policy( {"phase":"after","id":"widget-patched","trigger":"patched","projection":["label","quantity"]} ] }}, - "accessProfiles":{"operator": {"default":true,"principalClaim":"registry_principal","requiredScopes":"unrestricted", + "accessProfiles":{"operator": {"default":true,"principalClaim":"registry_principal","requiredScopes":["records:write"], "requiredPurposes":["case-management","case-review"], "permissions":{"records":[{ "recordType":"widget","operations":["create","get","patch","batch"], @@ -1082,7 +1082,7 @@ fn compiled_registry_with_create_policy( "writableFields":["jurisdiction","label","secret","quantity"], "rowBoundaries":[{"field":"jurisdiction","claim":"jurisdiction","operator":"equals"}] }]} - },"batch-creator": {"principalClaim":"registry_principal","requiredScopes":"unrestricted", + },"batch-creator": {"principalClaim":"registry_principal","requiredScopes":["records:write"], "requiredPurposes":["case-management"], "permissions":{"records":[{ "recordType":"widget","operations":["create","batch"], @@ -1090,7 +1090,7 @@ fn compiled_registry_with_create_policy( "writableFields":["jurisdiction","label","secret","quantity"], "rowBoundaries":[{"field":"jurisdiction","claim":"jurisdiction","operator":"equals"}] }]} - },"operator-minimal": {"principalClaim":"registry_principal","requiredScopes":"unrestricted", + },"operator-minimal": {"principalClaim":"registry_principal","requiredScopes":["records:write"], "requiredPurposes":["case-management"], "permissions":{"records":[{ "recordType":"widget","operations":["create","patch","batch"], @@ -1173,7 +1173,7 @@ fn claims(principal: &str, purpose: &str, jurisdiction: &str) -> VerifiedRequest VerifiedRequestClaims::authenticated( "registry_principal", principal, - BTreeSet::new(), + BTreeSet::from(["records:write".to_owned()]), Some(purpose.to_owned()), BTreeMap::from([( "jurisdiction".to_owned(), diff --git a/crates/registry-breg/tests/postgres_client_capabilities.rs b/crates/registry-breg/tests/postgres_client_capabilities.rs index b2e39d203f..b41184770f 100644 --- a/crates/registry-breg/tests/postgres_client_capabilities.rs +++ b/crates/registry-breg/tests/postgres_client_capabilities.rs @@ -44,7 +44,7 @@ fn registry() -> registry_breg::CompiledRegistry { "temporal":{"startField":"valid-from","endField":"valid-to"}, "constraints":[{"type":"temporal-non-overlap","scopeFields":["code"],"startField":"valid-from","endField":"valid-to"}] }}, - "accessProfiles":{"operator": {"default":true,"principalClaim":"registry_principal","requiredScopes":"unrestricted", + "accessProfiles":{"operator": {"default":true,"principalClaim":"registry_principal","requiredScopes":["records:write"], "requiredPurposes":["case-management"], "permissions":{"records":[{"recordType":"entry","operations":["create","get","list","patch","batch","tombstone","revisions","snapshot"], "readableFields":["code","label","valid-from","valid-to"],"writableFields":["code","label","valid-from","valid-to"], @@ -61,7 +61,7 @@ fn claims() -> VerifiedRequestClaims { VerifiedRequestClaims::authenticated( "registry_principal", "sdk-fixture-operator", - BTreeSet::new(), + BTreeSet::from(["records:write".to_owned()]), Some("case-management".into()), BTreeMap::new(), ) diff --git a/crates/registry-breg/tests/postgres_client_relationships.rs b/crates/registry-breg/tests/postgres_client_relationships.rs index bb815543e8..02aadff3ee 100644 --- a/crates/registry-breg/tests/postgres_client_relationships.rs +++ b/crates/registry-breg/tests/postgres_client_relationships.rs @@ -12,8 +12,8 @@ mod postgres_harness; use std::collections::{BTreeMap, BTreeSet}; use registry_breg::api::VerifiedRequestClaims; -use registry_breg::compiler::{compile_project, CompileProfile}; -use registry_breg::contract::parse_project_json; +use registry_breg::compiler::{compile_project, compile_project_with_assets, CompileProfile}; +use registry_breg::contract::{parse_project_json, ModuleAssetSource}; use registry_breg_client::{ BRegCreateRequest, BRegDirectWrite, BRegIdempotencyKey, BRegListRequest, BRegProblemCode, BRegRecordFormat, BRegRecordOptions, BRegRelationshipListRequest, @@ -259,7 +259,7 @@ async fn read_path_answers_when_the_profile_has_no_entry_for_its_target_entity() .unwrap(); client .create_record( - &create_binding(&operator.value, "records.membership.create", "operator"), + &create_binding(&writer.value, "records.membership.create", "writer"), &create(json!({ "household": household.value.data.record_id, "person": person.value.data.record_id @@ -374,8 +374,7 @@ const UNGRANTED_TARGET_PROJECT: &str = r#"{"datasets":{"test-dataset": {}}, "recordType":"household","rowBoundaries":"unrestricted","operations":["create","get","list"], "readableFields":["household-code"],"writableFields":["household-code"], "readPaths":[{"path":"people","readableFields":["person-code"]}] - }, - {"recordType":"membership","rowBoundaries":"unrestricted","operations":["create"],"readableFields":["household","person"],"writableFields":["household","person"]} + } ] } }, @@ -383,7 +382,9 @@ const UNGRANTED_TARGET_PROJECT: &str = r#"{"datasets":{"test-dataset": {}}, "requiredScopes":["registry.read"],"requiredPurposes":["case-management"], "permissions":{ "records":[ - {"recordType":"person","rowBoundaries":"unrestricted","operations":["create","get","list"],"readableFields":["person-code"],"writableFields":["person-code"]} + {"recordType":"person","rowBoundaries":"unrestricted","operations":["create","get","list"],"readableFields":["person-code"],"writableFields":["person-code"]}, + {"recordType":"household","rowBoundaries":"unrestricted","operations":["get"],"readableFields":[]}, + {"recordType":"membership","rowBoundaries":"unrestricted","operations":["create"],"readableFields":["household","person"],"writableFields":["household","person"]} ] } }, @@ -452,6 +453,7 @@ fn compiled_registry() -> registry_breg::CompiledRegistry { ] }, "person": {"primaryDataset":"test-dataset","route":"people","mutationMode":"mutable","classification":"restricted", + "derived":[{"id":"population","sql":"population.sql","key":"id","execution":"live","fields":[{"id":"population","type":"int64","classification":"restricted"}]}], "fields":[ {"id":"person-code","type":"string","required":true,"maximumLength":64,"classification":"internal"}, {"id":"sensitive-note","type":"string","required":true,"maximumLength":64,"classification":"restricted"} @@ -478,6 +480,13 @@ fn compiled_registry() -> registry_breg::CompiledRegistry { }"#, ) .expect("relationship SDK project parses"); - compile_project(&project, &[], CompileProfile::Authoring) + // The relationship projection, ordering, and count only need stored + // columns. An unrelated derived relation must not run its cardinality check. + let assets = [ModuleAssetSource { + module: None, + path: "population.sql".to_owned(), + bytes: b"SELECT p.id AS id, 1::bigint AS population FROM registry_source.person p CROSS JOIN registry_source.person AS other".to_vec(), + }]; + compile_project_with_assets(&project, &[], &assets, CompileProfile::Authoring) .expect("relationship SDK project compiles") } diff --git a/crates/registry-breg/tests/postgres_compiled_schema.rs b/crates/registry-breg/tests/postgres_compiled_schema.rs index 605d6d50c9..20573b4e05 100644 --- a/crates/registry-breg/tests/postgres_compiled_schema.rs +++ b/crates/registry-breg/tests/postgres_compiled_schema.rs @@ -2213,7 +2213,7 @@ fn additive_catalog_registry(variant: AdditiveCatalogVariant) -> registry_breg:: "accessProfiles": {"writer": { "default": true, "principalClaim": "registry_principal", - "requiredScopes": "unrestricted", + "requiredScopes": ["records:write"], "permissions": {"records": [{ "recordType": "entry", "operations": ["create", "get", "list", "patch"], @@ -2253,7 +2253,7 @@ fn length_catalog_registry(max_length: u32) -> registry_breg::CompiledRegistry { "accessProfiles": {"writer": { "default": true, "principalClaim": "registry_principal", - "requiredScopes": "unrestricted", + "requiredScopes": ["records:write"], "permissions": {"records": [{ "recordType": "entry", "operations": ["create", "get", "list", "patch"], @@ -2290,7 +2290,7 @@ fn string_length_catalog_registry(min_length: u32) -> registry_breg::CompiledReg "accessProfiles": {"writer": { "default": true, "principalClaim": "registry_principal", - "requiredScopes": "unrestricted", + "requiredScopes": ["records:write"], "permissions": {"records": [{ "recordType": "entry", "operations": ["create", "get", "list", "patch"], @@ -2339,7 +2339,7 @@ fn vocabulary_catalog_registry_with_constraints( "accessProfiles": {"writer": { "default": true, "principalClaim": "registry_principal", - "requiredScopes": "unrestricted", + "requiredScopes": ["records:write"], "permissions": {"records": [{ "recordType": "entry", "operations": ["create", "get", "list", "patch"], @@ -2377,7 +2377,7 @@ fn compiled_registry() -> registry_breg::CompiledRegistry { } }, "accessProfiles":{ - "writer": {"default":true,"principalClaim":"registry_principal","requiredScopes":"unrestricted", + "writer": {"default":true,"principalClaim":"registry_principal","requiredScopes":["records:write"], "requiredPurposes":["operations"], "permissions":{ "records":[ @@ -2471,7 +2471,7 @@ fn compiled_action_registry() -> registry_breg::CompiledRegistry { "accessProfiles": {"operator": { "default": true, "principalClaim": "registry_principal", - "requiredScopes": "unrestricted", + "requiredScopes": ["records:write"], "permissions": { "actions": [{ "action": "relabel-entry", @@ -2507,7 +2507,7 @@ fn derived_registry() -> registry_breg::CompiledRegistry { ] }] }}, - "accessProfiles":{"operator": {"default":true,"principalClaim":"registry_principal","requiredScopes":"unrestricted","permissions":{"records":[{ + "accessProfiles":{"operator": {"default":true,"principalClaim":"registry_principal","requiredScopes":["records:write"],"permissions":{"records":[{ "recordType":"household","operations":["create","get","list"], "readableFields":["tenant","size","child-count","observed-on"], "writableFields":["tenant","size"], diff --git a/crates/registry-breg/tests/postgres_consent_access.rs b/crates/registry-breg/tests/postgres_consent_access.rs index 47721fe357..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 { @@ -1639,7 +1639,7 @@ async fn frozen_review_changes_require_current_consent_for_each_snapshot_subject "action":"reassign-enrolment","operations":["start"],"targets":targets })); steward["permissions"]["proposals"] = json!([{ - "action":"reassign-enrolment","operations":["get","submit"],"ownership":"caller","targets":targets + "action":"reassign-enrolment","operations":["get","submit"],"party":"owner","targets":targets }]); let reviewer = &mut source["accessProfiles"][SCOPE]; reviewer["permissions"]["proposals"] = json!([{ diff --git a/crates/registry-breg/tests/postgres_consent_examples.rs b/crates/registry-breg/tests/postgres_consent_examples.rs index 6934c7b9e7..c160b75311 100644 --- a/crates/registry-breg/tests/postgres_consent_examples.rs +++ b/crates/registry-breg/tests/postgres_consent_examples.rs @@ -152,6 +152,71 @@ async fn in_production_an_unknown_and_an_uncovered_subject_get_the_same_refusal_ ); } +/// The link steward names the subject of each link it writes, so its grant +/// on persons lets a write name any active person. That grant serves no +/// read: a GET of an existing person answers as a GET of an unknown one. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn the_link_steward_names_subjects_it_cannot_read() { + let fixture = RunningFixture::start("consent-person-registry", &[]).await; + let app = fixture.prepared.app(); + let operator = fixture.token(json!({ + "registry_principal": "synthetic-registry-operator", + "registry_actor_kind": "human", + "azp": "person-registry-console", + "scope": "registry:person:operate", + })); + let link_steward = fixture.token(json!({ + "registry_principal": "synthetic-link-steward", + "scope": "consent:person:link", + })); + let person = create( + &app, + "persons", + "person-registry-operator", + &operator, + json!({"personCode": "P-LINKED", "legalName": "Linked Person", "district": "north"}), + ) + .await; + create( + &app, + "person-consent-links", + "person-consent-link-steward", + &link_steward, + json!({"subject": person, "principal": "linked-self", "active": true}), + ) + .await; + let unknown = "7f3c9a52-4f0e-4d8b-9a61-2b5e8c1d0f47"; + let (status, body) = send( + app.clone(), + Method::POST, + "/v1/records/person-consent-links?accessProfile=person-consent-link-steward".to_owned(), + json!({"data": {"subject": unknown, "principal": "unknown-self", "active": true}}), + Some("link-unknown-subject".to_owned()), + link_steward.clone(), + ) + .await; + assert_eq!(status, StatusCode::CONFLICT, "{body}"); + let read = |id: &str| { + send( + app.clone(), + Method::GET, + format!("/v1/records/persons/{id}?accessProfile=person-consent-link-steward"), + Value::Null, + None, + link_steward.clone(), + ) + }; + let (unknown_status, unknown_body) = read(unknown).await; + let (status, body) = read(&person).await; + assert_ne!(status, StatusCode::OK, "{body}"); + assert_eq!( + status, unknown_status, + "linked: {body} unknown: {unknown_body}" + ); + assert_eq!(without_trace(body), without_trace(unknown_body)); + fixture.finish().await; +} + /// Under `posture`, the bodies of a self action for an unknown subject and /// for an existing subject the caller's link does not cover, both 412, after /// checking that the subject the link covers succeeds. diff --git a/crates/registry-breg/tests/postgres_constraint_races.rs b/crates/registry-breg/tests/postgres_constraint_races.rs index 19a0463c6c..3a33386b3f 100644 --- a/crates/registry-breg/tests/postgres_constraint_races.rs +++ b/crates/registry-breg/tests/postgres_constraint_races.rs @@ -491,7 +491,7 @@ fn compiled_registry() -> registry_breg::CompiledRegistry { "startField":"valid-from","endField":"valid-to" }] }}, - "accessProfiles":{"operator": {"default":true,"principalClaim":"principal","requiredScopes":"unrestricted","requiredPurposes":["operations"], + "accessProfiles":{"operator": {"default":true,"principalClaim":"principal","requiredScopes":["records:write"],"requiredPurposes":["operations"], "permissions":{"records":[{ "recordType":"parent","operations":["create","get"],"readableFields":["name"],"writableFields":["name"], "rowBoundaries": "unrestricted" diff --git a/crates/registry-breg/tests/postgres_data_export.rs b/crates/registry-breg/tests/postgres_data_export.rs index c1c09023a8..2ebf791d9f 100644 --- a/crates/registry-breg/tests/postgres_data_export.rs +++ b/crates/registry-breg/tests/postgres_data_export.rs @@ -74,6 +74,7 @@ async fn real_postgres_export_is_authenticated_projected_audited_and_resumable() "aud":AUDIENCE, "registry_actor_kind":"service", "registry_principal":PRINCIPAL_CANARY, + "scope":"records:write", "purpose":"data-export", "jurisdictions":["north"] })); @@ -81,6 +82,7 @@ async fn real_postgres_export_is_authenticated_projected_audited_and_resumable() "aud":AUDIENCE, "registry_actor_kind":"service", "registry_principal":PRINCIPAL_CANARY, + "scope":"records:write", "purpose":"other-purpose", "jurisdictions":["north"] })); @@ -380,7 +382,7 @@ fn compiled_registry() -> registry_breg::CompiledRegistry { "constraints":[{"type":"unique","fields":["code"]}], "hooks":[{"phase":"after","id":"entry-created","trigger":"created","projection":["code"]}] }}, - "accessProfiles":{PROFILE: { "principalClaim":"registry_principal","requiredScopes":"unrestricted", + "accessProfiles":{PROFILE: { "principalClaim":"registry_principal","requiredScopes":["records:write"], "requiredPurposes":["data-export"], "permissions":{"records":[{ "recordType":"entry", diff --git a/crates/registry-breg/tests/postgres_data_facility.rs b/crates/registry-breg/tests/postgres_data_facility.rs index fdd03075c6..4f47b82343 100644 --- a/crates/registry-breg/tests/postgres_data_facility.rs +++ b/crates/registry-breg/tests/postgres_data_facility.rs @@ -21,13 +21,15 @@ const PROFILE: &str = "facility-operator"; #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn real_postgres_facility_import_is_authenticated_chunked_resumable_and_race_safe() { let harness = PilotHarness::start("facility").await; - let north_token = harness.token( + let north_token = harness.token_with_scopes( "facility-registry", &[("administrative_boundaries", json!(["north-district"]))], + &["registry:facility:operate"], ); - let south_token = harness.token( + let south_token = harness.token_with_scopes( "facility-registry", &[("administrative_boundaries", json!(["south-district"]))], + &["registry:facility:operate"], ); let facility_id = create( &harness, diff --git a/crates/registry-breg/tests/postgres_derived_values.rs b/crates/registry-breg/tests/postgres_derived_values.rs index c9af919b93..f132f784ea 100644 --- a/crates/registry-breg/tests/postgres_derived_values.rs +++ b/crates/registry-breg/tests/postgres_derived_values.rs @@ -291,7 +291,7 @@ async fn real_postgres_derived_values_enforce_declared_contracts() { VerifiedRequestClaims::authenticated( "registry_principal", "test-principal", - BTreeSet::new(), + BTreeSet::from(["records:write".to_owned()]), None, BTreeMap::new(), ) @@ -343,7 +343,7 @@ fn compiled_registry() -> registry_breg::CompiledRegistry { ] }] }}, - "accessProfiles":{"reader": {"default":true,"principalClaim":"registry_principal","requiredScopes":"unrestricted", + "accessProfiles":{"reader": {"default":true,"principalClaim":"registry_principal","requiredScopes":["records:write"], "permissions":{"records":[{ "recordType":"entry","operations":["create","get","list"], "readableFields":["scenario","short-code","description","amount","count","state"], diff --git a/crates/registry-breg/tests/postgres_event_record_examples.rs b/crates/registry-breg/tests/postgres_event_record_examples.rs index ce4822e954..7504d44615 100644 --- a/crates/registry-breg/tests/postgres_event_record_examples.rs +++ b/crates/registry-breg/tests/postgres_event_record_examples.rs @@ -277,7 +277,7 @@ fn claims() -> VerifiedRequestClaims { VerifiedRequestClaims::authenticated( "registry_principal", "registrar-principal", - BTreeSet::new(), + BTreeSet::from(["records:write".to_owned()]), None, BTreeMap::::new(), ) diff --git a/crates/registry-breg/tests/postgres_event_record_reader.rs b/crates/registry-breg/tests/postgres_event_record_reader.rs index 2c92ba18cb..507846ea0f 100644 --- a/crates/registry-breg/tests/postgres_event_record_reader.rs +++ b/crates/registry-breg/tests/postgres_event_record_reader.rs @@ -92,7 +92,7 @@ fn record_permissions() -> String { fn compile_reader(declarations: &str, other_permissions: &str) -> registry_breg::CompiledRegistry { let project = format!( "{declarations}\naccessProfiles:\n reader:\n default: true\n \ - principalClaim: registry_principal\n requiredScopes: unrestricted\n \ + principalClaim: registry_principal\n requiredScopes: [records:write]\n \ permissions:\n{other_permissions} records:\n{}", record_permissions() ); @@ -128,7 +128,7 @@ fn claims() -> VerifiedRequestClaims { VerifiedRequestClaims::authenticated( "registry_principal", "event-record-reader-fixture", - BTreeSet::new(), + BTreeSet::from(["records:write".to_owned()]), None, BTreeMap::new(), ) diff --git a/crates/registry-breg/tests/postgres_field_encryption.rs b/crates/registry-breg/tests/postgres_field_encryption.rs index f9a058f48c..9f0d11e452 100644 --- a/crates/registry-breg/tests/postgres_field_encryption.rs +++ b/crates/registry-breg/tests/postgres_field_encryption.rs @@ -139,7 +139,7 @@ accessProfiles: operator: default: true principalClaim: registry_principal - requiredScopes: unrestricted + requiredScopes: [registry:field-encryption:operate] requiredPurposes: [case-management] permissions: records: diff --git a/crates/registry-breg/tests/postgres_fixture_journeys.rs b/crates/registry-breg/tests/postgres_fixture_journeys.rs index c3d038eced..ffd4736646 100644 --- a/crates/registry-breg/tests/postgres_fixture_journeys.rs +++ b/crates/registry-breg/tests/postgres_fixture_journeys.rs @@ -89,6 +89,7 @@ journeys: accessProfile: operator claims: principal: fixture-operator + scopes: [fixture:write] purpose: case-management directClaims: {jurisdiction: zone-a} request: @@ -101,6 +102,7 @@ journeys: accessProfile: operator claims: principal: fixture-operator + scopes: [fixture:write] purpose: case-management directClaims: {jurisdiction: zone-a} request: {type: list} @@ -112,6 +114,7 @@ journeys: accessProfile: operator claims: principal: fixture-operator + scopes: [fixture:write] purpose: case-management directClaims: {jurisdiction: zone-a} request: @@ -131,6 +134,7 @@ journeys: accessProfile: operator claims: principal: fixture-operator + scopes: [fixture:write] purpose: case-management directClaims: {jurisdiction: zone-a} request: @@ -142,6 +146,7 @@ journeys: accessProfile: operator claims: principal: fixture-operator + scopes: [fixture:write] purpose: case-management directClaims: {jurisdiction: zone-a} request: @@ -154,6 +159,7 @@ journeys: accessProfile: write-only-end claims: principal: fixture-operator + scopes: [fixture:write] purpose: case-management directClaims: {jurisdiction: zone-a} request: @@ -244,6 +250,331 @@ async fn fixture_import_uses_real_ingestion_and_leaves_no_open_authority() { database.cleanup().await; } +const AUTOMATIC_PROJECT_SOURCE: &[u8] = + include_bytes!("fixtures/automatic-application/project.yaml"); +const AUTOMATIC_JOURNEY_SOURCE: &[u8] = + include_bytes!("fixtures/automatic-application/journeys.yaml"); +const NEVER_APPLIED_JOURNEY_SOURCE: &[u8] = + include_bytes!("fixtures/automatic-application/never-applied.yaml"); + +fn clerk_token(idp: &MockIdp) -> String { + idp.mint_token(json!({ + "aud": AUDIENCE, + "registry_actor_kind": "service", + "registry_principal": "synthetic-clerk", + "scope": "notes:file", + "purpose": "note-handling", + })) +} + +/// Run one journeys document over the automatic-application project with +/// the clerk's credential on every step. +async fn run_automatic_application_journeys( + journeys: &[u8], + steps: [(&'static str, &'static str); 3], + read_step: Option<(&'static str, &'static str)>, + block_application: bool, +) -> ( + Result, + i64, +) { + let _runtime_guard = WASM_RUNTIME_TEST_LOCK.lock().await; + let compiled = compile_project( + &parse_project_yaml(AUTOMATIC_PROJECT_SOURCE).expect("automatic project parses"), + &[], + CompileProfile::Authoring, + ) + .expect("automatic project compiles"); + let schema_fingerprint = measure_compiled_schema_fingerprint(&compiled).await; + let package = package_fixture_with_modules( + AUTOMATIC_PROJECT_SOURCE, + &schema_fingerprint, + journeys, + Vec::new(), + ); + let suite = validate_fixture_journeys(journeys, &compiled).expect("journeys preflight"); + let mut database = TestDatabase::create(8).await; + let idp = MockIdp::start().await; + let config_path = package.write_runtime_config(&database, &idp); + let config = + load_runtime_config(&config_path, DEVELOPMENT_POSTURE).expect("runtime config loads"); + let prepared_database = prepare_schema_test_database_with_connection_configs_for_test( + &config, + &package.prepared, + &database.migration_config, + &database.runtime_config, + ) + .await + .expect("database prepares"); + let bindings = steps + .into_iter() + .chain(read_step) + .map(|(journey, step)| { + SchemaTestCredentialBinding::bearer(journey, step, Zeroizing::new(clerk_token(&idp))) + }) + .collect(); + let credentials = + SchemaTestCredentialBindings::new(&suite, bindings).expect("credentials bind"); + let execution = execute_schema_test( + prepared_database, + &config, + &package.prepared, + &suite, + credentials, + ); + let result = if block_application { + let table = format!( + "registry_data.{}", + quote_identifier(&compiled.entities()["note"].physical_table) + ); + let barrier = database.admin.transaction().await.expect("barrier begins"); + barrier + .batch_execute(&format!("LOCK TABLE {table} IN SHARE MODE")) + .await + .expect("the barrier holds the application's insert"); + tokio::pin!(execution); + let observe_blocked_insert = async { + loop { + let blocked: bool = barrier + .query_one( + "SELECT EXISTS (SELECT 1 FROM pg_locks + WHERE relation=$1::text::regclass AND mode='RowExclusiveLock' + AND NOT granted AND pg_backend_pid()=ANY(pg_blocking_pids(pid)))", + &[&table], + ) + .await + .expect("application lock status reads") + .get(0); + if blocked { + break; + } + tokio::time::sleep(Duration::from_millis(10)).await; + } + }; + tokio::select! { + result = &mut execution => panic!("journey finished before Apply reached the barrier: {result:?}"), + observed = tokio::time::timeout(Duration::from_secs(10), observe_blocked_insert) => { + observed.expect("Apply reaches the PostgreSQL barrier"); + } + } + // The wait started before this insert. Hold it beyond the one-second + // journey deadline, then let the same leased attempt finish normally. + let timed = tokio::time::timeout(Duration::from_millis(1250), &mut execution).await; + assert!( + timed.is_err(), + "the test must join the leased attempt during cleanup" + ); + barrier + .commit() + .await + .expect("application barrier releases"); + let result = execution.await; + tokio::time::timeout(Duration::from_secs(5), async { + loop { + let job = database + .admin + .query_one( + "SELECT state, attempt_count FROM registry_internal.registry_proposal_application_jobs", + &[], + ) + .await + .expect("application job reads"); + assert_eq!(job.get::<_, i32>(1), 1); + match job.get::<_, String>(0).as_str() { + "applied" => break, + "applying" => tokio::time::sleep(Duration::from_millis(10)).await, + state => panic!("the leased attempt ended in {state}"), + } + } + }) + .await + .expect("the in-flight attempt commits after the barrier releases"); + result + } else { + execution.await + }; + let notes: i64 = database + .admin + .query_one( + "SELECT count(*) FROM registry_internal.registry_proposal_results", + &[], + ) + .await + .expect("results read") + .get(0); + idp.stop().await; + drop(package); + database.cleanup().await; + (result, notes) +} + +/// A journey waits on a Get step while the built-in executor applies a +/// review-free automatic Proposal, then reads the record it created. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn fixture_journey_waits_for_automatic_application_and_reads_the_result() { + let (result, results) = run_automatic_application_journeys( + AUTOMATIC_JOURNEY_SOURCE, + [ + ("applied", "start-note"), + ("applied", "submit-note"), + ("applied", "await-application"), + ], + Some(("applied", "read-note")), + false, + ) + .await; + let receipt = result.expect("the waiting journey completes"); + assert_eq!(receipt.successful_journey_ids(), ["applied"]); + assert_eq!(results, 1); +} + +/// A wait that never sees its expectation stops at its bound with a named +/// refusal instead of hanging or reporting an ordinary mismatch. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn fixture_journey_wait_times_out_with_a_named_failure() { + let started = std::time::Instant::now(); + let (result, results) = run_automatic_application_journeys( + NEVER_APPLIED_JOURNEY_SOURCE, + [ + ("held", "start-note"), + ("held", "submit-note"), + ("held", "await-application"), + ], + None, + false, + ) + .await; + assert_named_application_wait_timeout(result); + assert_eq!(results, 0); + assert!(started.elapsed() < Duration::from_secs(60)); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn fixture_journey_wait_times_out_during_an_in_flight_application() { + let journeys = std::str::from_utf8(AUTOMATIC_JOURNEY_SOURCE) + .expect("journeys are UTF-8") + .replace("waitSeconds: 10", "waitSeconds: 1"); + let (result, results) = run_automatic_application_journeys( + journeys.as_bytes(), + [ + ("applied", "start-note"), + ("applied", "submit-note"), + ("applied", "await-application"), + ], + Some(("applied", "read-note")), + true, + ) + .await; + assert_named_application_wait_timeout(result); + assert_eq!(results, 1); +} + +fn assert_named_application_wait_timeout( + result: Result, +) { + let Err(FixtureError::StepFailed { + journey_index: 0, + step_index: 2, + error, + }) = result + else { + panic!("the wait must fail on its own step: {result:?}"); + }; + assert!(matches!( + *error, + FixtureError::ProposalWaitTimedOut { wait_seconds: 1 } + )); + assert!(error + .to_string() + .starts_with("fixture.proposal.wait-timed-out")); +} + +const MESSAGE_PROJECT_SOURCE: &[u8] = include_bytes!("fixtures/message-journeys/project.yaml"); +const MESSAGE_JOURNEY_SOURCE: &[u8] = include_bytes!("fixtures/message-journeys/journeys.yaml"); + +fn person_token(idp: &MockIdp, principal: &str, scope: &str) -> String { + idp.mint_token(json!({ + "aud": AUDIENCE, + "registry_actor_kind": "human", + "registry_principal": principal, + "scope": scope, + "purpose": "note-handling", + })) +} + +/// The `message` and `read-messages` journey steps drive the real thread +/// routes: the office writes, the applicant sees it is their turn, and +/// reading the thread hands the turn back without moving the status. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn fixture_message_journey_writes_reads_and_moves_the_turn() { + let _runtime_guard = WASM_RUNTIME_TEST_LOCK.lock().await; + let compiled = compile_project( + &parse_project_yaml(MESSAGE_PROJECT_SOURCE).expect("message project parses"), + &[], + CompileProfile::Authoring, + ) + .expect("message project compiles"); + let schema_fingerprint = measure_compiled_schema_fingerprint(&compiled).await; + let package = package_fixture_with_modules( + MESSAGE_PROJECT_SOURCE, + &schema_fingerprint, + MESSAGE_JOURNEY_SOURCE, + Vec::new(), + ); + let suite = validate_fixture_journeys(MESSAGE_JOURNEY_SOURCE, &compiled) + .expect("message journey preflights"); + let database = TestDatabase::create(8).await; + let idp = MockIdp::start().await; + let config_path = package.write_runtime_config_for_actor_kind(&database, &idp, "human"); + let config = + load_runtime_config(&config_path, DEVELOPMENT_POSTURE).expect("runtime config loads"); + let prepared_database = prepare_schema_test_database_with_connection_configs_for_test( + &config, + &package.prepared, + &database.migration_config, + &database.runtime_config, + ) + .await + .expect("database prepares"); + let applicant = || person_token(&idp, "synthetic-applicant", "notes:file"); + let officer = || person_token(&idp, "synthetic-officer", "notes:office"); + let credentials = credential_bindings_for_tokens( + &suite, + [ + ("thread", "start-note", applicant()), + ("thread", "submit-note", applicant()), + ("thread", "office-view", officer()), + ("thread", "office-writes", officer()), + ("thread", "applicant-view", applicant()), + ("thread", "applicant-reads", applicant()), + ], + ); + let receipt = execute_schema_test( + prepared_database, + &config, + &package.prepared, + &suite, + credentials, + ) + .await + .expect("message journey completes"); + assert_eq!(receipt.successful_journey_ids(), ["thread"]); + let messages: i64 = database + .admin + .query_one( + "SELECT count(*) FROM registry_internal.registry_proposal_messages WHERE side='official'", + &[], + ) + .await + .expect("thread reads") + .get(0); + assert_eq!(messages, 1); + + idp.stop().await; + drop(package); + database.cleanup().await; +} + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn fixture_test_runs_strict_journeys_through_the_real_postgres_router() { let _runtime_guard = WASM_RUNTIME_TEST_LOCK.lock().await; @@ -1220,6 +1551,16 @@ fn spatial_package_fixture(project: &[u8], schema_fingerprint: &str) -> PackageF impl PackageFixture { fn write_runtime_config(&self, database: &TestDatabase, idp: &MockIdp) -> PathBuf { + self.write_runtime_config_for_actor_kind(database, idp, "service") + } + + /// The issuer asserts one actor kind for every token it signs. + fn write_runtime_config_for_actor_kind( + &self, + database: &TestDatabase, + idp: &MockIdp, + actor_kind: &str, + ) -> PathBuf { let secrets = self.directory.join("secrets"); fs::create_dir_all(&secrets).expect("fixture secret root creates"); write_private(&secrets.join("database-url"), b"unused-by-test-startup"); @@ -1276,7 +1617,7 @@ authentication: accessTokenType: JWT scopeClaim: scope scopeSeparator: " " - actorKind: service + actorKind: {actor_kind} allowedClients: unrestricted maximumTokenLifetimeSeconds: 3600 leewayMilliseconds: 60000 @@ -1301,7 +1642,7 @@ cursor: maximumAgeSeconds: 300 operationalTimeouts: httpRequestMilliseconds: 5000 - shutdownGraceMilliseconds: 1000 + shutdownGraceMilliseconds: 3000 recordLockMilliseconds: 2000 migrationLockMilliseconds: 2000 migrationStatementMilliseconds: 5000 @@ -1638,6 +1979,7 @@ fn operator_token(idp: &MockIdp, purpose: bool) -> String { "registry_actor_kind": "service", "registry_principal": "fixture-operator", "jurisdiction": "zone-a", + "scope": "fixture:write", }); if purpose { claims["purpose"] = json!("case-management"); @@ -1847,7 +2189,7 @@ fn compiled_compare_constraint_fixture() -> (registry_breg::CompiledRegistry, Ve 1, ); let write_only_end = format!( - " write-only-end:\n principalClaim: registry_principal\n requiredScopes: unrestricted\n requiredPurposes: [case-management]\n permissions:\n records:\n - recordType: widget\n operations: [create]\n readableFields: [{fields}, valid-from]\n writableFields: [{fields}, valid-from, valid-to]\n rowBoundaries:\n - {{field: jurisdiction, claim: jurisdiction, operator: equals}}\n" + " write-only-end:\n principalClaim: registry_principal\n requiredScopes: [fixture:write]\n requiredPurposes: [case-management]\n permissions:\n records:\n - recordType: widget\n operations: [create]\n readableFields: [{fields}, valid-from]\n writableFields: [{fields}, valid-from, valid-to]\n rowBoundaries:\n - {{field: jurisdiction, claim: jurisdiction, operator: equals}}\n" ); assert!( project_source.contains("right: valid-to}") diff --git a/crates/registry-breg/tests/postgres_generated_identifier_batch_import.rs b/crates/registry-breg/tests/postgres_generated_identifier_batch_import.rs index e2f7de7a34..03a5f7510f 100644 --- a/crates/registry-breg/tests/postgres_generated_identifier_batch_import.rs +++ b/crates/registry-breg/tests/postgres_generated_identifier_batch_import.rs @@ -156,7 +156,7 @@ fn compiled_registry() -> registry_breg::CompiledRegistry { "generate":{"type":"sequence","prefix":"REG-","minimumDigits":4,"scope":["jurisdiction"]}} ] }}, - "accessProfiles":{"writer": {"default":true,"principalClaim":"registry_principal","requiredScopes":"unrestricted", + "accessProfiles":{"writer": {"default":true,"principalClaim":"registry_principal","requiredScopes":["records:write"], "requiredPurposes":["case-management"], "permissions":{"records":[{ "recordType":"entry","operations":["create","get","batch"], @@ -232,7 +232,7 @@ fn writer_claims() -> VerifiedRequestClaims { VerifiedRequestClaims::authenticated( "registry_principal", "generated-identifier-writer", - BTreeSet::new(), + BTreeSet::from(["records:write".to_owned()]), Some("case-management".to_owned()), BTreeMap::from([( "jurisdiction".to_owned(), diff --git a/crates/registry-breg/tests/postgres_generated_identifiers.rs b/crates/registry-breg/tests/postgres_generated_identifiers.rs index 04919a98db..867b8714b7 100644 --- a/crates/registry-breg/tests/postgres_generated_identifiers.rs +++ b/crates/registry-breg/tests/postgres_generated_identifiers.rs @@ -49,7 +49,7 @@ fn registry_with_limits( "generate":{"type":"random","prefix":"R-","length":12}} ] }}, - "accessProfiles":{"writer": {"default":true,"principalClaim":"sub","requiredScopes":"unrestricted", + "accessProfiles":{"writer": {"default":true,"principalClaim":"sub","requiredScopes":["records:write"], "permissions":{"records":[{ "recordType":"entry","operations":["create","get"], "readableFields":["jurisdiction","issued-at","public-id","daily-id","receipt-code"], 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_history_commit.rs b/crates/registry-breg/tests/postgres_history_commit.rs index 7202ae41ba..26d05fabb5 100644 --- a/crates/registry-breg/tests/postgres_history_commit.rs +++ b/crates/registry-breg/tests/postgres_history_commit.rs @@ -710,7 +710,7 @@ fn compiled_registry() -> registry_breg::CompiledRegistry { "accessProfiles":{"writer": { "default":true, "principalClaim":"registry_principal", - "requiredScopes":"unrestricted", + "requiredScopes":["records:write"], "requiredPurposes":["operations"], "permissions":{"records":[{ "recordType":"membership", diff --git a/crates/registry-breg/tests/postgres_history_erasure.rs b/crates/registry-breg/tests/postgres_history_erasure.rs index 3b5498ea4e..c49d39c078 100644 --- a/crates/registry-breg/tests/postgres_history_erasure.rs +++ b/crates/registry-breg/tests/postgres_history_erasure.rs @@ -21,9 +21,15 @@ mod history_schema { mod model { pub use registry_breg::model::*; } +mod mutation { + pub use registry_breg::mutation::MutationError; +} mod plan { pub use registry_breg::plan::MAX_PLAN_FIELD_MUTATIONS; } +mod problem_location { + pub use registry_breg::problem_location::RequestLocation; +} #[path = "../src/history_store.rs"] #[allow(dead_code)] mod history_store; @@ -103,6 +109,9 @@ mod idempotency; #[path = "support/postgres_harness.rs"] #[allow(dead_code)] mod postgres_harness; +#[path = "../src/proposal_messages.rs"] +#[allow(dead_code)] +mod proposal_messages; #[path = "../src/stored_bytes.rs"] #[allow(dead_code)] mod stored_bytes; @@ -2652,7 +2661,7 @@ async fn snapshot_client_http( let claims = registry_breg::api::VerifiedRequestClaims::authenticated( "registry_principal", "history-erasure-sdk-reader", - BTreeSet::new(), + BTreeSet::from(["records:write".to_owned()]), Some("operations".to_owned()), BTreeMap::new(), ) @@ -2692,7 +2701,7 @@ fn compiled_registry() -> registry_breg::CompiledRegistry { "accessProfiles":{"writer": { "default":true, "principalClaim":"registry_principal", - "requiredScopes":"unrestricted", + "requiredScopes":["records:write"], "requiredPurposes":["operations"], "permissions":{"records":[{ "recordType":"membership", diff --git a/crates/registry-breg/tests/postgres_history_migration.rs b/crates/registry-breg/tests/postgres_history_migration.rs index 2540a504f8..bb6c483b0b 100644 --- a/crates/registry-breg/tests/postgres_history_migration.rs +++ b/crates/registry-breg/tests/postgres_history_migration.rs @@ -987,7 +987,7 @@ fn module_bytes(variant: Variant) -> Vec { Variant::StatusRestricted => "restricted", }; format!( - r#"{{"apiVersion":"id.registrystack.org/formats/breg/module/v1alpha1","kind":"BRegModule","id":"core","version":"1","recordTypes":{{"asset":{{"primaryDataset":"history-migration-registry","route":"assets","mutationMode":"create-only","fields":[{{"id":"code","type":"string","required":true,"maximumLength":8,"classification":"internal"}},{{"id":"status","type":"string","required":true,"maximumLength":16,"classification":"{status_classification}"}}],"accessProfiles":{{"reader":{{"requiredScopes":"unrestricted","rowBoundaries":"unrestricted","principalClaim":"principal","operations":["create","get","list","revisions"],"revisionAccess":true,"readableFields":["code"],"writableFields":["code","status"]}}}}}}}}}}"# + r#"{{"apiVersion":"id.registrystack.org/formats/breg/module/v1alpha1","kind":"BRegModule","id":"core","version":"1","recordTypes":{{"asset":{{"primaryDataset":"history-migration-registry","route":"assets","mutationMode":"create-only","fields":[{{"id":"code","type":"string","required":true,"maximumLength":8,"classification":"internal"}},{{"id":"status","type":"string","required":true,"maximumLength":16,"classification":"{status_classification}"}}],"accessProfiles":{{"reader":{{"requiredScopes":["records:write"],"rowBoundaries":"unrestricted","principalClaim":"principal","operations":["create","get","list","revisions"],"revisionAccess":true,"readableFields":["code"],"writableFields":["code","status"]}}}}}}}}}}"# ) .into_bytes() } @@ -1209,7 +1209,7 @@ fn history_claims() -> VerifiedRequestClaims { VerifiedRequestClaims::authenticated( "principal", "package-reader", - BTreeSet::new(), + BTreeSet::from(["records:write".to_owned()]), Some("case-review".to_owned()), BTreeMap::new(), ) diff --git a/crates/registry-breg/tests/postgres_history_rebaseline.rs b/crates/registry-breg/tests/postgres_history_rebaseline.rs index d8383e9089..0e6898302b 100644 --- a/crates/registry-breg/tests/postgres_history_rebaseline.rs +++ b/crates/registry-breg/tests/postgres_history_rebaseline.rs @@ -1339,7 +1339,7 @@ fn compiled_registry() -> registry_breg::CompiledRegistry { "accessProfiles":{"writer": { "default":true, "principalClaim":"registry_principal", - "requiredScopes":"unrestricted", + "requiredScopes":["records:write"], "requiredPurposes":["operations"], "permissions":{"records":[{ "recordType":"membership", diff --git a/crates/registry-breg/tests/postgres_hook_changes.rs b/crates/registry-breg/tests/postgres_hook_changes.rs index 3c8e4a11c4..6767e97bab 100644 --- a/crates/registry-breg/tests/postgres_hook_changes.rs +++ b/crates/registry-breg/tests/postgres_hook_changes.rs @@ -175,7 +175,7 @@ fn hook_project_json( }} }}}}, "accessProfiles":{{"operator":{{ - "default":true,"principalClaim":"registry_principal","requiredScopes":"unrestricted", + "default":true,"principalClaim":"registry_principal","requiredScopes":["records:write"], "requiredPurposes":["case-management"], "permissions":{{"records":[{{ "recordType":"case","operations":["create","get","list"], @@ -184,7 +184,7 @@ fn hook_project_json( "rowBoundaries":[{{"field":"jurisdiction","claim":"jurisdiction","operator":"equals"}}] }}]}} }},"case-hook":{{ - "principalClaim":"registry_principal","requiredScopes":"unrestricted", + "principalClaim":"registry_principal","requiredScopes":["records:write"], "permissions":{{"actions":[{{ "action":"open-followup","operations":["invoke"], "targets":[{{"recordType":"followup","rowBoundaries":"unrestricted"}}], @@ -718,18 +718,30 @@ fn registry_state_test_identity() -> RegistryStateTestIdentity<'static> { } fn mutation_claims(registry: &CompiledRegistry) -> ClaimContext { - ClaimContext::for_compiled( - registry, - "case", - Some("operator-principal".to_owned()), - "operator", - Some("case-management".to_owned()), - vec![RowBoundaryContext::Equals { - field: "jurisdiction".to_owned(), - value: "zone-a".to_owned(), - }], - ) - .expect("compiled authority context is valid") + let context = |entity_id: &str| { + ClaimContext::for_compiled( + registry, + entity_id, + Some("operator-principal".to_owned()), + "operator", + Some("case-management".to_owned()), + vec![RowBoundaryContext::Equals { + field: "jurisdiction".to_owned(), + value: "zone-a".to_owned(), + }], + ) + .expect("compiled authority context is valid") + }; + let claims = context("case"); + // A case write names a tally only if the operator reads it, under the + // same jurisdiction. + if registry.entities().contains_key("tally") { + claims + .with_reference_context(&context("tally")) + .expect("same caller") + } else { + claims + } } /// One committed case create and the delivery rows it captured. @@ -2466,6 +2478,90 @@ async fn real_postgres_a_hook_without_a_principal_compiles_and_delivers() { receiver.stop().await; } +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn real_postgres_hook_proposal_refuses_a_claim_bounded_action_target() { + let receiver = HttpsReceiver::start().await; + let hooks = format!( + "[{}]", + hook_json("case-created", true, PROPOSING_RHAI_HANDLER) + ); + let mut project_json: Value = serde_json::from_str(&hook_project_json( + &hooks, + "[]", + r#""results":["followup"]"#, + "", + )) + .expect("hook proposal fixture is JSON"); + + for bounded in [false, true] { + let target = &mut project_json["accessProfiles"]["case-hook"]["permissions"]["actions"][0] + ["targets"][0]; + assert_eq!(target["rowBoundaries"], json!("unrestricted")); + if bounded { + target["rowBoundaries"] = + json!([{"field":"jurisdiction","claim":"jurisdiction","operator":"equals"}]); + } + let project = parse_project_json( + &serde_json::to_vec(&project_json).expect("hook proposal fixture serializes"), + ) + .expect("hook proposal fixture parses"); + let registry = compile_project_with_assets( + &project, + &[], + &[ + rhai_asset("scripts/open-followup.rhai", ACTION_HANDLER_SCRIPT), + rhai_asset("hooks/propose.rhai", PROPOSAL_HOOK_SCRIPT), + ], + CompileProfile::Authoring, + ) + .expect("hook proposal fixture compiles"); + + let setup = setup(registry, &receiver, false).await; + let mut mutation_client = setup + .pool + .get_for_test() + .await + .expect("runtime mutation connection is available"); + let event = create_case(&setup, &mut mutation_client, "boundary-control").await; + let delivery_id = single_delivery(&event).to_owned(); + drop(mutation_client); + + assert_eq!( + setup.service.deliver_once().await, + Ok(HookWorkOutcome::Delivered) + ); + let row = delivery_row(&setup, event.event_id, &delivery_id).await; + assert_eq!(row.state, "delivered"); + assert_eq!(row.attempt, 1); + assert_eq!( + row.message_digest.as_deref(), + Some(proposal_message_digest().as_slice()) + ); + if bounded { + assert_eq!(row.disposition.as_deref(), Some("refused")); + assert_eq!( + row.code.as_deref(), + Some("hook.proposal.boundaries-unsatisfiable") + ); + assert_eq!( + row.summary.as_deref(), + Some( + "The declared principal's grant carries row boundaries a hook holds no claims to satisfy." + ) + ); + assert_eq!(row.resulting_revision, None); + assert_eq!(record_count(&setup, "followup").await, 0); + } else { + assert_eq!(row.disposition.as_deref(), Some("applied")); + assert_eq!(row.code, None); + assert_eq!(row.resulting_revision, Some(1)); + assert_eq!(record_count(&setup, "followup").await, 1); + } + setup.teardown().await; + } + receiver.stop().await; +} + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn real_postgres_a_proposal_without_a_declared_principal_is_dead_lettered_readable() { let receiver = HttpsReceiver::start().await; diff --git a/crates/registry-breg/tests/postgres_immediate_actions.rs b/crates/registry-breg/tests/postgres_immediate_actions.rs index a0192c43a6..1cf907b3e4 100644 --- a/crates/registry-breg/tests/postgres_immediate_actions.rs +++ b/crates/registry-breg/tests/postgres_immediate_actions.rs @@ -3764,7 +3764,7 @@ const ACTION_PROJECT: &[u8] = br#"{ }, "household-seed-writer": { "principalClaim": "registry_principal", - "requiredScopes": "unrestricted", + "requiredScopes": ["records:write"], "permissions": { "records": [ { diff --git a/crates/registry-breg/tests/postgres_import_authority.rs b/crates/registry-breg/tests/postgres_import_authority.rs index 01c92288cf..8252b6010f 100644 --- a/crates/registry-breg/tests/postgres_import_authority.rs +++ b/crates/registry-breg/tests/postgres_import_authority.rs @@ -84,7 +84,7 @@ const FIXTURE: &str = r#"{ {"id":"label","type":"string","maximumLength":128,"required":true,"classification":"public"} ] }}, - "accessProfiles":{"loader": {"default":true,"principalClaim":"registry_principal","requiredScopes":"unrestricted", + "accessProfiles":{"loader": {"default":true,"principalClaim":"registry_principal","requiredScopes":["records:write"], "permissions":{"records":[{ "recordType":"widget","operations":["import"], "readableFields":["jurisdiction","label"],"writableFields":["jurisdiction","label"], @@ -98,7 +98,7 @@ const FIXTURE: &str = r#"{ "readableFields":["jurisdiction","label"],"writableFields":["jurisdiction","label"], "rowBoundaries":[{"field":"jurisdiction","claim":"jurisdiction","operator":"equals"}] }]} - },"second-loader": {"principalClaim":"registry_principal","requiredScopes":"unrestricted", + },"second-loader": {"principalClaim":"registry_principal","requiredScopes":["records:write"], "permissions":{"records":[{ "recordType":"widget","operations":["import"], "readableFields":["jurisdiction","label"],"writableFields":["jurisdiction","label"], @@ -824,7 +824,7 @@ fn claims_for(principal: &str, jurisdiction: &str) -> VerifiedRequestClaims { VerifiedRequestClaims::authenticated( "registry_principal", principal, - BTreeSet::new(), + BTreeSet::from(["records:write".to_owned()]), None, BTreeMap::from([( "jurisdiction".to_owned(), diff --git a/crates/registry-breg/tests/postgres_ingestion_contract.rs b/crates/registry-breg/tests/postgres_ingestion_contract.rs index fec00a774c..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 @@ -520,7 +723,7 @@ fn claims_with( VerifiedRequestClaims::authenticated( "registry_principal", principal, - BTreeSet::new(), + BTreeSet::from(["records:write".to_owned()]), Some("case-management".to_owned()), claims, ) @@ -550,12 +753,17 @@ fn fixture_registry(batch_maximum_bytes: u32) -> Arc VerifiedRequestClaims VerifiedRequestClaims::authenticated( "registry_principal", principal, - BTreeSet::new(), + BTreeSet::from(["records:write".to_owned()]), Some("case-management".to_owned()), BTreeMap::from([( "jurisdiction".to_owned(), diff --git a/crates/registry-breg/tests/postgres_ingestion_runs.rs b/crates/registry-breg/tests/postgres_ingestion_runs.rs index ece016f939..38e120448c 100644 --- a/crates/registry-breg/tests/postgres_ingestion_runs.rs +++ b/crates/registry-breg/tests/postgres_ingestion_runs.rs @@ -15,7 +15,7 @@ use std::time::Duration; use axum::body::{to_bytes, Body}; use axum::http::{HeaderName, HeaderValue, Method, Request, StatusCode}; -use base64::engine::general_purpose::STANDARD as BASE64; +use base64::engine::general_purpose::{STANDARD as BASE64, URL_SAFE_NO_PAD}; use base64::Engine as _; use client_http::ClientHttp; use postgres_harness::TestDatabase; @@ -25,7 +25,7 @@ use registry_breg::api::{ }; use registry_breg::audit::RegistryAudit; use registry_breg::compiler::{compile_project, CompileProfile}; -use registry_breg::contract::parse_project_json; +use registry_breg::contract::{parse_module_json, parse_project_json}; use registry_breg::cursor::CursorCodec; use registry_breg::field_encryption::{FieldEncryptionProvider, FieldEncryptionService}; use registry_breg::import_authority::{ @@ -39,7 +39,8 @@ use registry_breg::postgres::{ RegistryStateTestIdentity, }; use registry_breg_client::{ - BRegBatchOperation, BRegIngestionChunk, BRegIngestionRunRequest, BRegIngestionRunStatus, + BRegAccessReason, BRegBatchBuilder, BRegBatchOperation, BRegCreateRequest, BRegIdempotencyKey, + BRegIngestionChunk, BRegIngestionRunRequest, BRegIngestionRunStatus, BaseRegistryClientError, BREG_INGESTION_CHUNK_ALGORITHM_VERSION, }; use registry_platform_audit::AuditProfile; @@ -2287,6 +2288,10 @@ async fn chunk_receipt_recovery_correlates_a_request_and_a_response_entry() { ) .await; assert_eq!(committed.status(), StatusCode::OK); + let submitted = body_json(committed).await; + assert_eq!(submitted.as_object().unwrap().len(), 2); + assert_eq!(submitted["run"]["runId"], run_id); + assert_eq!(submitted["receipt"]["chunkIndex"], 0); let before_recovery = harness.database.audit_entries().len(); let recovered = harness @@ -2297,6 +2302,13 @@ async fn chunk_receipt_recovery_correlates_a_request_and_a_response_entry() { .await; assert_eq!(recovered.status(), StatusCode::OK); + let recovered = body_json(recovered).await; + assert_eq!(recovered["chunkIndex"], 0); + assert_eq!(recovered["batch"], submitted["receipt"]["batch"]); + assert!(recovered["batch"].is_object()); + assert!(recovered.get("receipt").is_none()); + assert!(recovered.get("run").is_none()); + let entries = harness.database.audit_entries(); let ingestion_entries = entries[before_recovery..] .iter() @@ -3021,7 +3033,7 @@ fn timer_ingestion_registry_with_operations( .remove("service-editor") .expect("the future-activation example has a service-editor profile"); source["accessProfiles"]["operator"] = renamed; - source["accessProfiles"]["operator"]["requiredScopes"] = json!("unrestricted"); + source["accessProfiles"]["operator"]["requiredScopes"] = json!(["records:write"]); source["accessProfiles"]["operator"]["requiredPurposes"] = json!(["case-management"]); source["accessProfiles"]["operator"]["permissions"]["records"][0]["operations"] = json!(operations); @@ -4294,6 +4306,500 @@ async fn an_outside_boundary_ingestion_item_remains_a_value_free_precondition_re assert_eq!(durable_widget_count(&harness).await, 0); } +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn an_unavailable_ingestion_reference_is_a_value_free_precondition_refusal() { + let mut source = widget_project_with_ledger_reference(); + source["accessProfiles"]["operator"]["permissions"]["records"] + .as_array_mut() + .unwrap() + .push(json!({ + "recordType":"ledger","operations":["reference"], + "rowBoundaries":[{"field":"jurisdiction","claim":"jurisdiction","operator":"equals"}] + })); + 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 outside = harness.seed_ledger("zone-b", "ledger-canary").await; + let inside = harness.seed_ledger("zone-a", "in-reach").await; + + let chunk_plan = |target: &str| { + let items = [json!({"operation":"create","data":{ + "jurisdiction":"zone-a","label":"reference-canary","quantity":1,"ledger":target + }})]; + plan_chunks(&items, 3) + }; + for target in [Uuid::new_v4().to_string(), outside] { + let chunks = chunk_plan(&target); + let run_id = harness.create_run(&claims, &chunks).await; + let refused = harness + .post_json( + &format!("/v1/records/widgets/ingestion-runs/{run_id}/chunks"), + &claims, + chunk_body(&chunks, 0), + ) + .await; + assert_eq!(refused.status(), StatusCode::PRECONDITION_FAILED); + let problem = body_json(refused).await; + assert_eq!( + problem + .as_object() + .unwrap() + .keys() + .map(String::as_str) + .collect::>(), + BTreeSet::from(["type", "title", "status", "detail", "code", "traceId"]) + ); + assert_eq!(problem["code"], "precondition.failed"); + assert_eq!(problem["detail"], "The mutation precondition failed."); + for concealed in [target.as_str(), "reference-canary", "ledger-canary"] { + assert!(!problem.to_string().contains(concealed), "{problem}"); + } + let run = harness.read_run(&claims, &run_id).await; + assert_eq!(run["status"], "open"); + assert_eq!(run["nextChunkIndex"], 0); + assert_eq!(run["committedItems"], 0); + assert_eq!(run["lastAttempt"]["outcome"], "refused"); + assert_eq!(durable_widget_count(&harness).await, 0); + } + let chunks = chunk_plan(&inside); + let run_id = harness.create_run(&claims, &chunks).await; + let committed = harness + .post_json( + &format!("/v1/records/widgets/ingestion-runs/{run_id}/chunks"), + &claims, + chunk_body(&chunks, 0), + ) + .await; + assert_eq!(committed.status(), StatusCode::OK); + let committed = body_json(committed).await; + assert_eq!(committed["run"]["committedItems"], 1); + assert_eq!(durable_widget_count(&harness).await, 1); + harness.database.cleanup().await; +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn direct_batch_requires_the_reference_targets_reason_atomically() { + let (harness, items) = reason_required_reference_batch().await; + let claims = operator_claims(PRINCIPAL, "zone-a"); + let mut headers = vec![ + ("content-type", "application/json"), + ("idempotency-key", "direct-reason-batch"), + ]; + let body = serde_json::to_vec(&json!({"items":items})).unwrap(); + let response = send( + &harness.app, + Method::POST, + "/v1/records/widgets:batch", + Some(claims.clone()), + &headers, + body.clone(), + ) + .await; + let status = response.status(); + let problem = body_json(response).await; + assert_eq!(status, StatusCode::CONFLICT, "{problem}"); + assert_eq!(problem["code"], "mutation.conflict"); + assert_no_reference_batch_commit(&harness).await; + + let reason = URL_SAFE_NO_PAD.encode("Link the authorized ledger"); + headers.push(("registry-access-reason", &reason)); + let response = send( + &harness.app, + Method::POST, + "/v1/records/widgets:batch", + Some(claims), + &headers, + body, + ) + .await; + let status = response.status(); + let committed = body_json(response).await; + assert_eq!(status, StatusCode::OK, "{committed}"); + assert_eq!(committed["results"].as_array().unwrap().len(), 2); + assert_eq!(durable_widget_count(&harness).await, 2); + harness.database.cleanup().await; +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn ingestion_batch_requires_the_reference_targets_reason_atomically() { + let (harness, items) = reason_required_reference_batch().await; + let claims = operator_claims(PRINCIPAL, "zone-a"); + let chunks = plan_chunks(&items, 3); + let run_id = harness.create_run(&claims, &chunks).await; + let path = format!("/v1/records/widgets/ingestion-runs/{run_id}/chunks"); + let chunk = chunk_body(&chunks, 0); + let response = harness.post_json(&path, &claims, chunk.clone()).await; + let status = response.status(); + let problem = body_json(response).await; + assert_eq!(status, StatusCode::PRECONDITION_FAILED, "{problem}"); + assert_eq!(problem["code"], "precondition.failed"); + assert_eq!(problem["detail"], "The mutation precondition failed."); + let run = harness.read_run(&claims, &run_id).await; + assert_eq!(run["status"], "open"); + assert_eq!(run["nextChunkIndex"], 0); + assert_eq!(run["committedItems"], 0); + assert_eq!(run["lastAttempt"]["outcome"], "refused"); + assert_no_reference_batch_commit(&harness).await; + + let reason = URL_SAFE_NO_PAD.encode("Link the authorized ledger"); + let response = send( + &harness.app, + Method::POST, + &path, + Some(claims), + &[ + ("content-type", "application/json"), + ("registry-access-reason", &reason), + ], + serde_json::to_vec(&chunk).unwrap(), + ) + .await; + let status = response.status(); + let committed = body_json(response).await; + assert_eq!(status, StatusCode::OK, "{committed}"); + assert_eq!(committed["run"]["status"], "complete"); + assert_eq!(committed["run"]["nextChunkIndex"], 1); + assert_eq!(committed["run"]["committedItems"], 2); + assert_eq!(committed["receipt"]["replayed"], false); + assert_eq!(durable_widget_count(&harness).await, 2); + harness.database.cleanup().await; +} + +/// Exercise a source Batch profile whose own reason requirement gates every +/// ingestion operation, independently of any reference-target grant. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn source_batch_requires_a_reason_on_each_ingestion_exchange() { + async fn exchange( + app: &axum::Router, + claims: &VerifiedRequestClaims, + method: Method, + uri: &str, + body: Option, + status: StatusCode, + ) -> Value { + let mut headers = Vec::new(); + let body = body.map_or_else(Vec::new, |value| { + headers.push(("content-type", "application/json")); + serde_json::to_vec(&value).unwrap() + }); + let refused = send( + app, + method.clone(), + uri, + Some(claims.clone()), + &headers, + body.clone(), + ) + .await; + assert_eq!(refused.status(), StatusCode::BAD_REQUEST, "{method} {uri}"); + assert_eq!( + body_json(refused).await["code"], + "request.access-reason-required" + ); + + let reason = URL_SAFE_NO_PAD.encode("Verify the announced input 🧭"); + headers.push(("registry-access-reason", reason.as_str())); + let allowed = send( + app, + method.clone(), + uri, + Some(claims.clone()), + &headers, + body, + ) + .await; + assert_eq!(allowed.status(), status, "{method} {uri}"); + body_json(allowed).await + } + + let mut source: Value = serde_json::from_str(&format!("{FIXTURE_HEAD}{FIXTURE_TAIL}")).unwrap(); + source["accessProfiles"]["operator"]["requireAccessReason"] = json!(true); + let project = parse_project_json(&serde_json::to_vec(&source).unwrap()).unwrap(); + let registry = compile_project(&project, &[], CompileProfile::Authoring).unwrap(); + let harness = IngestionHarness::from_registry(Arc::new(registry)).await; + let claims = operator_claims(PRINCIPAL, "zone-a"); + let runs = "/v1/records/widgets/ingestion-runs"; + let chunks = plan_chunks(&announce_items("source-reason", 5), 3); + let created = exchange( + &harness.app, + &claims, + Method::POST, + runs, + Some(run_body( + "create", + &harness.identity.schema_fingerprint, + &chunks, + )), + StatusCode::CREATED, + ) + .await; + let run_id = created["run"]["runId"].as_str().unwrap(); + let listed = exchange( + &harness.app, + &claims, + Method::GET, + runs, + None, + StatusCode::OK, + ) + .await; + assert_eq!(listed["runs"][0]["runId"], run_id); + let run = format!("{runs}/{run_id}"); + let read = exchange( + &harness.app, + &claims, + Method::GET, + &run, + None, + StatusCode::OK, + ) + .await; + assert_eq!(read["run"]["nextChunkIndex"], 0); + let chunk = format!("{run}/chunks"); + let submitted = exchange( + &harness.app, + &claims, + Method::POST, + &chunk, + Some(chunk_body(&chunks, 0)), + StatusCode::OK, + ) + .await; + assert_eq!(submitted["run"]["nextChunkIndex"], 1); + + // 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()) + .expect("reference fixture parses"); + // The target's module grant owns the reason requirement. The widget's + // Batch grant has no reason precondition of its own. + let ledger = parse_module_json( + &serde_json::to_vec(&json!({ + "apiVersion":"id.registrystack.org/formats/breg/module/v1alpha1", + "kind":"BRegModule","id":"ledger-authority","version":"1", + "extendRecordTypes":{"ledger":{"accessProfiles":{"operator":{ + "principalClaim":"registry_principal","requiredScopes":["records:write"], + "requiredPurposes":["case-management","case-review"], + "operations":["reference"],"requireAccessReason":true, + "rowBoundaries":[{"field":"jurisdiction","claim":"jurisdiction","operator":"equals"}] + }}}} + })) + .unwrap(), + ) + .expect("ledger module parses"); + let registry = compile_project(&project, &[ledger], CompileProfile::Authoring) + .expect("reason-required reference fixture compiles"); + let harness = IngestionHarness::from_registry(Arc::new(registry)).await; + let target = harness.seed_ledger("zone-a", "in-reach").await; + let mut items = announce_items("reason-batch", 2); + // A reference-free first item must roll back if the second is refused. + items[1]["data"]["ledger"] = json!(target); + (harness, items) +} + +async fn assert_no_reference_batch_commit(harness: &IngestionHarness) { + assert_eq!(durable_widget_count(harness).await, 0); + let durable = harness + .database + .admin + .query_one( + "SELECT + (SELECT count(*) FROM registry_internal.registry_revisions WHERE entity_id = 'widget'), + (SELECT count(*) FROM registry_internal.registry_idempotency), + (SELECT count(*) FROM registry_internal.registry_ingestion_run_chunks)", + &[], + ) + .await + .expect("durable mutation state is inspectable"); + assert_eq!(durable.get::<_, i64>(0), 0, "no widget revision"); + assert_eq!(durable.get::<_, i64>(1), 0, "no idempotency receipt"); + assert_eq!(durable.get::<_, i64>(2), 0, "no chunk receipt"); +} + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn listing_runs_filters_by_status_and_input_digest() { let harness = IngestionHarness::create().await; @@ -4574,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( @@ -4850,6 +5357,26 @@ impl IngestionHarness { Self::from_registry(Arc::new(compiled_registry())).await } + async fn seed_ledger(&self, jurisdiction: &str, memo: &str) -> String { + let target = Uuid::new_v4(); + let ledger = &self.registry.entities()["ledger"]; + self.database + .admin + .execute( + &format!( + "INSERT INTO registry_data.\"{}\" (record_id, active_package_revision, \"{}\", \"{}\") + VALUES ($1, $2, $3, $4)", + ledger.physical_table, + ledger.fields["jurisdiction"].physical_name, + ledger.fields["memo"].physical_name, + ), + &[&target, &self.identity.activation_id, &jurisdiction, &memo], + ) + .await + .expect("seed an active synthetic ledger"); + target.to_string() + } + /// Build the same harness around one caller-chosen compiled registry, so a /// test can pin authored shapes the shared fixture does not carry. async fn from_registry(registry: Arc) -> Self { @@ -5327,7 +5854,7 @@ fn operator_claims(principal: &str, jurisdiction: &str) -> VerifiedRequestClaims VerifiedRequestClaims::authenticated( "registry_principal", principal, - BTreeSet::new(), + BTreeSet::from(["records:write".to_owned()]), Some("case-management".to_owned()), BTreeMap::from([( "jurisdiction".to_owned(), @@ -5373,7 +5900,7 @@ const FIXTURE_HEAD: &str = r#"{ }},"#; const FIXTURE_TAIL: &str = r#" - "accessProfiles":{"operator": {"default":true,"principalClaim":"registry_principal","requiredScopes":"unrestricted", + "accessProfiles":{"operator": {"default":true,"principalClaim":"registry_principal","requiredScopes":["records:write"], "requiredPurposes":["case-management","case-review"], "permissions":{"records":[{ "recordType":"widget","operations":["create","get","patch","batch"], @@ -5381,7 +5908,7 @@ const FIXTURE_TAIL: &str = r#" "writableFields":["jurisdiction","label","quantity"], "rowBoundaries":[{"field":"jurisdiction","claim":"jurisdiction","operator":"equals"}] }]} - },"operator-minimal": {"principalClaim":"registry_principal","requiredScopes":"unrestricted", + },"operator-minimal": {"principalClaim":"registry_principal","requiredScopes":["records:write"], "requiredPurposes":["case-management"], "permissions":{"records":[{ "recordType":"widget","operations":["create","patch","batch"], @@ -5406,6 +5933,22 @@ fn compiled_registry() -> registry_breg::CompiledRegistry { .expect("ingestion fixture compiles to trusted inventories") } +fn widget_project_with_ledger_reference() -> Value { + let mut project: Value = + serde_json::from_str(&format!("{FIXTURE_HEAD}{FIXTURE_TAIL}")).unwrap(); + project["recordTypes"]["widget"]["fields"] + .as_array_mut() + .unwrap() + .push( + json!({"id":"ledger","type":"reference","target":"ledger","classification":"public"}), + ); + project["accessProfiles"]["operator"]["permissions"]["records"][0]["writableFields"] + .as_array_mut() + .unwrap() + .push(json!("ledger")); + project +} + fn compiled_registry_with_created_webhook() -> registry_breg::CompiledRegistry { let fixture = format!("{FIXTURE_HEAD}{FIXTURE_TAIL}").replacen( r#"{"phase":"after","id":"widget-created","trigger":"created","projection":["label"]}"#, @@ -5473,7 +6016,7 @@ fn patch_only_registry() -> Arc { {"id":"label","type":"string","maximumLength":128,"required":true,"classification":"public"} ] }}, - "accessProfiles":{"patcher": {"default":true,"principalClaim":"registry_principal","requiredScopes":"unrestricted", + "accessProfiles":{"patcher": {"default":true,"principalClaim":"registry_principal","requiredScopes":["records:write"], "requiredPurposes":["case-management"], "permissions":{ "records":[ diff --git a/crates/registry-breg/tests/postgres_kernel.rs b/crates/registry-breg/tests/postgres_kernel.rs index fa28daf96f..48fe5db34b 100644 --- a/crates/registry-breg/tests/postgres_kernel.rs +++ b/crates/registry-breg/tests/postgres_kernel.rs @@ -790,7 +790,7 @@ fn compiled_registry() -> registry_breg::CompiledRegistry { "constraints":[{"type":"temporal-non-overlap","scopeFields":["authority"]}] }}, "accessProfiles":{"operator": {"default":true,"principalClaim":"principal", - "requiredScopes":"unrestricted","requiredPurposes":["registry-administration"], + "requiredScopes":["records:write"],"requiredPurposes":["registry-administration"], "permissions":{"records":[{"recordType":"entry","operations":["create","get","list","patch"], "readableFields":["authority","payload","valid-from","valid-to"], "writableFields":["authority","payload","valid-from","valid-to"], 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 90dbadc100..84be848426 100644 --- a/crates/registry-breg/tests/postgres_membership_access.rs +++ b/crates/registry-breg/tests/postgres_membership_access.rs @@ -7,6 +7,27 @@ mod membership_fixture; #[allow(dead_code)] mod postgres_harness; +#[cfg(feature = "tooling")] +use registry_breg as breg_fixture_crate; +#[cfg(feature = "tooling")] +#[path = "support/membership_targets.rs"] +mod membership_targets; +#[cfg(feature = "tooling")] +#[path = "support/membership_write_journeys.rs"] +mod membership_write_journeys; +#[cfg(feature = "tooling")] +#[path = "support/membership_write_project.rs"] +mod membership_write_project; +#[cfg(feature = "tooling")] +#[path = "support/postgres_membership_writes.rs"] +mod postgres_membership_writes; +#[cfg(feature = "tooling")] +use registry_breg as breg; +#[cfg(feature = "tooling")] +#[path = "support/action_evidence_provider.rs"] +#[allow(dead_code)] +mod action_evidence_provider; + use axum::body::{to_bytes, Body}; use axum::http::{Method, Request, StatusCode}; use registry_breg::api::{ @@ -200,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, @@ -211,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, @@ -332,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}"); @@ -494,8 +513,12 @@ async fn real_postgres_membership_successors_match_fresh_install_when_added_chan managed_schema_fingerprint, reconcile_compiled_runtime_acl_for_test, }; let mut base = membership_fixture::source("facility"); - base["accessProfiles"]["member"]["permissions"]["records"][0]["membershipBoundaries"] = - json!([]); + base["accessProfiles"]["member"]["permissions"]["records"][0]["rowBoundaries"] = + json!("unrestricted"); + base["recordTypes"]["membership"] + .as_object_mut() + .unwrap() + .remove("membership"); let mut previous = membership_fixture::compile(&base).unwrap(); let upgraded = postgres_harness::TestDatabase::create(1).await; let (migration, task) = upgraded.connect_migration().await; @@ -504,17 +527,25 @@ async fn real_postgres_membership_successors_match_fresh_install_when_added_chan .unwrap(); let guarded = membership_fixture::source("facility"); let mut changed = guarded.clone(); - changed["accessProfiles"]["member"]["permissions"]["records"][0]["membershipBoundaries"][0] - ["principalField"] = json!("private-note"); + changed["recordTypes"]["membership"]["membership"]["principal"] = json!("private-note"); for (stage, source) in [("added", guarded), ("changed", changed), ("removed", base)] { let candidate = membership_fixture::compile(&source).unwrap(); let changes = compiled_registry_change_set(&previous, &candidate, "prior-membership-package"); let plan = change_set_to_applicable_migration_plan(&changes) .expect("membership access changes produce compiler-owned successor DDL"); - assert!( - !plan.statements.is_empty(), - "{stage} helper change needs successor DDL" + let index_id = "entity.membership.membership.key-index"; + assert_eq!( + plan.statements + .iter() + .any(|statement| statement.id == index_id), + stage != "removed" + ); + assert_eq!( + plan.statements + .iter() + .any(|statement| statement.id == format!("{index_id}.drop")), + stage != "added" ); for statement in &plan.statements { migration @@ -553,3 +584,139 @@ async fn real_postgres_membership_successors_match_fresh_install_when_added_chan task.abort(); upgraded.cleanup().await; } + +#[tokio::test] +async fn real_postgres_pre_index_membership_successor_matches_fresh_catalog() { + use registry_breg::package::{ + change_set_to_applicable_migration_plan, compiled_registry_change_set_from_baseline, + CompiledRegistryMigrationBaseline, + }; + use registry_breg::postgres::{ + managed_schema_fingerprint, reconcile_compiled_runtime_acl_for_test, + }; + let candidate = membership_fixture::compile(&membership_fixture::source("facility")).unwrap(); + let mut baseline = CompiledRegistryMigrationBaseline::from_compiled("prior", &candidate); + baseline.generated_ddl_sha256 = + Some("sha256:88ce9380a31f7201ccda598870579c46fba1352db5598b0eb667bbb23bf68042".to_owned()); + let changes = compiled_registry_change_set_from_baseline(&baseline, &candidate, "prior"); + assert!(changes.changes.is_empty()); + let plan = change_set_to_applicable_migration_plan(&changes).unwrap(); + let upgraded = postgres_harness::TestDatabase::create(1).await; + let (migration, task) = upgraded.connect_migration().await; + install_compiled_schema(&migration, &candidate, &upgraded.runtime_role) + .await + .unwrap(); + // Model the pre-index installation precisely: retained helpers and policy + // definitions are already present in the predecessor, only the index is absent. + migration + .batch_execute("DROP INDEX registry_data.breg_membership_key_b9ee6c3037") + .await + .unwrap(); + for statement in &plan.statements { + migration + .batch_execute(&statement.sql) + .await + .unwrap_or_else(|error| { + panic!("compiler successor statement {}: {error}", statement.id) + }); + } + reconcile_compiled_runtime_acl_for_test(&migration, &candidate, &upgraded.runtime_role) + .await + .unwrap(); + let catalog = ExpectedManagedCatalog::compiled(&candidate); + let upgraded_fingerprint = + managed_schema_fingerprint(&migration, &upgraded.runtime_role, &catalog) + .await + .unwrap(); + let fresh = postgres_harness::TestDatabase::create(1).await; + let (fresh_migration, fresh_task) = fresh.connect_migration().await; + install_compiled_schema(&fresh_migration, &candidate, &fresh.runtime_role) + .await + .unwrap(); + let fresh_fingerprint = + managed_schema_fingerprint(&fresh_migration, &fresh.runtime_role, &catalog) + .await + .unwrap(); + assert_eq!(upgraded_fingerprint, fresh_fingerprint); + fresh_task.abort(); + fresh.cleanup().await; + task.abort(); + upgraded.cleanup().await; +} + +#[tokio::test] +async fn real_postgres_non_unique_membership_index_upgrades_to_the_unique_one() { + use registry_breg::package::{ + change_set_to_applicable_migration_plan, compiled_registry_change_set_from_baseline, + CompiledRegistryMigrationBaseline, + }; + use registry_breg::postgres::{ + managed_schema_fingerprint, reconcile_compiled_runtime_acl_for_test, + }; + let candidate = membership_fixture::compile(&membership_fixture::source("facility")).unwrap(); + let index = candidate + .ddl() + .statements + .iter() + .find(|statement| statement.id == "entity.membership.membership.key-index") + .unwrap(); + // A package from before the index was unique, compiled by an earlier + // compiler: its baseline carries a different generated DDL digest. + let mut baseline = CompiledRegistryMigrationBaseline::from_compiled("prior", &candidate); + baseline.generated_ddl_sha256 = + Some("sha256:88ce9380a31f7201ccda598870579c46fba1352db5598b0eb667bbb23bf68042".to_owned()); + let changes = compiled_registry_change_set_from_baseline(&baseline, &candidate, "prior"); + let plan = change_set_to_applicable_migration_plan(&changes).unwrap(); + let upgraded = postgres_harness::TestDatabase::create(1).await; + let (migration, task) = upgraded.connect_migration().await; + install_compiled_schema(&migration, &candidate, &upgraded.runtime_role) + .await + .unwrap(); + // Replace the unique index with the earlier non-unique one of the same + // name, as the predecessor installed it. + let earlier = index.sql.replacen("CREATE UNIQUE INDEX", "CREATE INDEX", 1); + assert_ne!(earlier, index.sql); + migration + .batch_execute(&format!( + "DROP INDEX registry_data.breg_membership_key_b9ee6c3037; {earlier}" + )) + .await + .unwrap(); + for statement in &plan.statements { + migration + .batch_execute(&statement.sql) + .await + .unwrap_or_else(|error| panic!("successor statement {}: {error}", statement.id)); + } + reconcile_compiled_runtime_acl_for_test(&migration, &candidate, &upgraded.runtime_role) + .await + .unwrap(); + let unique: bool = migration + .query_one( + "SELECT indisunique FROM pg_index WHERE indexrelid = 'registry_data.breg_membership_key_b9ee6c3037'::regclass", + &[], + ) + .await + .unwrap() + .get(0); + assert!(unique, "the successor rebuilds the index as unique"); + let catalog = ExpectedManagedCatalog::compiled(&candidate); + let upgraded_fingerprint = + managed_schema_fingerprint(&migration, &upgraded.runtime_role, &catalog) + .await + .unwrap(); + let fresh = postgres_harness::TestDatabase::create(1).await; + let (fresh_migration, fresh_task) = fresh.connect_migration().await; + install_compiled_schema(&fresh_migration, &candidate, &fresh.runtime_role) + .await + .unwrap(); + let fresh_fingerprint = + managed_schema_fingerprint(&fresh_migration, &fresh.runtime_role, &catalog) + .await + .unwrap(); + assert_eq!(upgraded_fingerprint, fresh_fingerprint); + fresh_task.abort(); + fresh.cleanup().await; + task.abort(); + upgraded.cleanup().await; +} diff --git a/crates/registry-breg/tests/postgres_migration.rs b/crates/registry-breg/tests/postgres_migration.rs index 81691101f7..ef99d7ed9d 100644 --- a/crates/registry-breg/tests/postgres_migration.rs +++ b/crates/registry-breg/tests/postgres_migration.rs @@ -179,6 +179,84 @@ async fn subject_access_log_storage_survives_disabled_collection() { database.cleanup().await; } +/// A database a release before the Proposal subject wrote has no +/// `subject_reference` column. Applying a successor package installs it in +/// place and keeps every existing Proposal, with no subject bound. +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn a_successor_adds_the_proposal_subject_column_in_place() { + let database = TestDatabase::create(1).await; + let (prior, fingerprint, active, _initial) = + activate_without_access_log_collection(&database).await; + let existing = Uuid::new_v4(); + database + .admin + .execute( + "INSERT INTO registry_internal.registry_proposal_state + (action_id, proposal_id, owner_reference, state, submission_version, workflow_revision) + VALUES ('earlier-action', $1, 'earlier-owner', 'cancelled', 1, 1)", + &[&existing], + ) + .await + .unwrap(); + database + .admin + .batch_execute( + "DROP INDEX registry_internal.registry_proposal_subject; + ALTER TABLE registry_internal.registry_proposal_state DROP COLUMN subject_reference;", + ) + .await + .unwrap(); + + let successor = publish_and_load( + prepare_package(build_request( + Variant::SubjectWithLog, + Some(&active.package_digest), + &fingerprint, + PackageMigrationPlanInput::Successor { + prior_registry: Box::new(prior), + }, + )) + .unwrap(), + local_context(), + ); + let upgraded = apply( + &database, + &successor, + ApplyPrecondition::Successor { current: &active }, + ) + .await + .expect("a successor installs the subject column over an earlier catalog"); + assert_ready_target(&database, &upgraded).await; + let row = database + .admin + .query_one( + "SELECT subject_reference, to_regclass('registry_internal.registry_proposal_subject') IS NOT NULL + FROM registry_internal.registry_proposal_state WHERE proposal_id=$1", + &[&existing], + ) + .await + .unwrap(); + assert_eq!(row.get::<_, Option>(0), None); + assert!( + row.get::<_, bool>(1), + "the partial subject index is installed" + ); + let constrained: bool = database + .admin + .query_one( + "SELECT EXISTS (SELECT 1 FROM pg_catalog.pg_constraint + WHERE conrelid = 'registry_internal.registry_proposal_state'::regclass + AND contype = 'c' + AND pg_get_constraintdef(oid) LIKE '%subject_reference%')", + &[], + ) + .await + .unwrap() + .get(0); + assert!(constrained, "an empty subject reference is refused"); + database.cleanup().await; +} + /// Every activation installs the subject access-log storage, so a catalog /// without it is not one an activation left behind. The catalog check refuses /// it for a Registry that collects no log exactly as for one that does, and @@ -5314,6 +5392,11 @@ enum Variant { EncryptedSharedLookup, /// `EncryptedSharedLookup` with `nfc` added to its list. EncryptedSharedNfcLookup, + /// A `link` Record type shaped like a membership source, without the + /// declaration. + MembershipFields, + /// `MembershipFields` declaring `link` as a membership source. + MembershipDeclared, } #[derive(Clone, Copy)] @@ -5650,6 +5733,29 @@ fn project_bytes(digest: &str) -> Vec { } fn module_bytes(variant: Variant) -> Vec { + if matches!( + variant, + Variant::MembershipFields | Variant::MembershipDeclared + ) { + let mut source: serde_json::Value = + serde_json::from_slice(&module_bytes(Variant::Base)).unwrap(); + let mut link = serde_json::json!({ + "primaryDataset":"migration-registry","route":"links","mutationMode":"mutable", + "fields":[ + {"id":"asset","type":"reference","target":"asset","classification":"internal"}, + {"id":"principal","type":"string","maximumLength":32,"classification":"internal"}, + {"id":"active","type":"boolean","classification":"internal"} + ], + "accessProfiles":{"reader":{"requiredScopes":["records:write"],"rowBoundaries":"unrestricted", + "principalClaim":"principal","operations":["get"],"readableFields":["asset"]}} + }); + if matches!(variant, Variant::MembershipDeclared) { + link["membership"] = + serde_json::json!({"key":"asset","principal":"principal","active":"active"}); + } + source["recordTypes"]["link"] = link; + return serde_json::to_vec(&source).unwrap(); + } if matches!( variant, Variant::SubjectWithoutLog | Variant::SubjectWithLog @@ -5731,7 +5837,7 @@ fn module_bytes(variant: Variant) -> Vec { _ => "", }; format!( - r#"{{"apiVersion":"id.registrystack.org/formats/breg/module/v1alpha1","kind":"BRegModule","id":"core","version":"1","recordTypes":{{"asset":{{"primaryDataset":"migration-registry","route":"assets","mutationMode":"create-only","fields":[{{"id":"code","type":"string","maximumLength":8,"classification":"internal"}},{{"id":"rank","type":"int64","classification":"internal"{rank_required}}}{legacy}{batch}{secret}{alias}],"accessProfiles":{{"reader":{{"requiredScopes":"unrestricted","rowBoundaries":"unrestricted","principalClaim":"principal","operations":["create","get","list"],"readableFields":["code"],"writableFields":["code"]}}}}}}}}}}"# + r#"{{"apiVersion":"id.registrystack.org/formats/breg/module/v1alpha1","kind":"BRegModule","id":"core","version":"1","recordTypes":{{"asset":{{"primaryDataset":"migration-registry","route":"assets","mutationMode":"create-only","fields":[{{"id":"code","type":"string","maximumLength":8,"classification":"internal"}},{{"id":"rank","type":"int64","classification":"internal"{rank_required}}}{legacy}{batch}{secret}{alias}],"accessProfiles":{{"reader":{{"requiredScopes":["records:write"],"rowBoundaries":"unrestricted","principalClaim":"principal","operations":["create","get","list"],"readableFields":["code"],"writableFields":["code"]}}}}}}}}}}"# ) .into_bytes() } @@ -9462,3 +9568,103 @@ async fn assert_digests_follow_successor(scenario: &ReindexScenario, secrets: &[ .collect::>(); assert_eq!(distinct.len(), secrets.iter().flatten().count()); } + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn duplicate_live_membership_rows_refuse_the_unique_index_by_name_until_repaired() { + let database = TestDatabase::create(1).await; + let fields = compile_variant(Variant::MembershipFields); + let declared = compile_variant(Variant::MembershipDeclared); + let fields_fp = initial_fingerprint(&database, &fields).await; + let declared_fp = initial_fingerprint(&database, &declared).await; + let initial = prepare_and_load_initial_variant(Variant::MembershipFields, &fields, &fields_fp); + let active = apply(&database, &initial, ApplyPrecondition::InitialActivation) + .await + .unwrap(); + let assets = quote(&fields.entities()["asset"].physical_table); + let link = &fields.entities()["link"]; + let table = quote(&link.physical_table); + let column = |field: &str| quote(&link.fields[field].physical_name); + let asset = Uuid::from_u128(71); + database + .admin + .execute( + &format!("INSERT INTO registry_data.{assets} (record_id, active_package_revision) VALUES ($1, $2)"), + &[&asset, &active.activation_id], + ) + .await + .unwrap(); + // Two live rows for one key and principal, written before the source was + // declared, and a third that is inactive. + for (id, live) in [(72_u128, true), (73, true), (74, false)] { + database + .admin + .execute( + &format!( + "INSERT INTO registry_data.{table} (record_id, {}, {}, {}, active_package_revision) VALUES ($1, $2, $3, $4, $5)", + column("asset"), column("principal"), column("active") + ), + &[&Uuid::from_u128(id), &asset, &"person-a", &live, &active.activation_id], + ) + .await + .unwrap(); + } + let prepared = prepare_package(build_request( + Variant::MembershipDeclared, + Some(&active.package_digest), + &declared_fp, + PackageMigrationPlanInput::Successor { + prior_registry: Box::new(fields.clone()), + }, + )) + .unwrap(); + let successor = publish_and_load(prepared, local_context()); + assert_value_free( + apply( + &database, + &successor, + ApplyPrecondition::Successor { current: &active }, + ) + .await + .err(), + MigrationError::MembershipDuplicateLiveRows { + entity_id: "link".to_owned(), + }, + ); + assert_non_ready_target(&database, &active, &successor, "failed").await; + database + .admin + .execute( + &format!( + "UPDATE registry_data.{table} SET {} = false WHERE record_id = $1", + column("active") + ), + &[&Uuid::from_u128(73)], + ) + .await + .unwrap(); + let active = apply( + &database, + &successor, + ApplyPrecondition::Successor { current: &active }, + ) + .await + .expect("repaired rows admit the exact pinned successor"); + assert_ready_target(&database, &active).await; + // The index now refuses a second live row for the same key and principal. + let error = database + .admin + .execute( + &format!( + "UPDATE registry_data.{table} SET {} = true WHERE record_id = $1", + column("active") + ), + &[&Uuid::from_u128(74)], + ) + .await + .unwrap_err(); + assert_eq!( + error.code(), + Some(&tokio_postgres::error::SqlState::UNIQUE_VIOLATION) + ); + database.cleanup().await; +} diff --git a/crates/registry-breg/tests/postgres_mutation.rs b/crates/registry-breg/tests/postgres_mutation.rs index 4e33efb16f..b144d4dc63 100644 --- a/crates/registry-breg/tests/postgres_mutation.rs +++ b/crates/registry-breg/tests/postgres_mutation.rs @@ -1813,7 +1813,7 @@ async fn real_postgres_row_local_constraint_problems_name_only_readable_declarat {"id":"valid-to","type":"date","validTimeRole":"valid-to","classification":"public"} ] }}, - "accessProfiles":{"writer": {"default":true,"principalClaim":"registry_principal","requiredScopes":"unrestricted","requiredPurposes":["case-management"], + "accessProfiles":{"writer": {"default":true,"principalClaim":"registry_principal","requiredScopes":["records:write"],"requiredPurposes":["case-management"], "permissions":{"records":[{ "recordType":"window","operations":["create","get","patch","batch"], "readableFields":["jurisdiction","label","valid-from","valid-to","score","status"], @@ -1825,7 +1825,7 @@ async fn real_postgres_row_local_constraint_problems_name_only_readable_declarat "writableFields":["jurisdiction","scope","valid-from","valid-to"], "rowBoundaries":[{"field":"jurisdiction","claim":"jurisdiction","operator":"equals"}] }]} - },"write-only-end": {"principalClaim":"registry_principal","requiredScopes":"unrestricted","requiredPurposes":["case-management"], + },"write-only-end": {"principalClaim":"registry_principal","requiredScopes":["records:write"],"requiredPurposes":["case-management"], "permissions":{"records":[{ "recordType":"window","operations":["create"], "readableFields":["jurisdiction","label","valid-from","score","status"], @@ -2230,7 +2230,10 @@ async fn real_postgres_http_mutations_are_guarded_and_exactly_replayable() { BREG_SEC_13_PRINCIPAL_CANARY, "case-management", Some(BREG_SEC_13_ZONE_CANARY), - BTreeSet::from(["breg-sec-13-scope-canary".to_owned()]), + BTreeSet::from([ + "records:write".to_owned(), + "breg-sec-13-scope-canary".to_owned(), + ]), ); let operator_openapi = body_json( @@ -3740,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; @@ -3888,7 +3891,7 @@ fn row_boundary_batch_registry() -> registry_breg::CompiledRegistry { {"id":"quantity","type":"int64","required":true,"classification":"public"} ] }}, - "accessProfiles":{"writer": {"default":true,"principalClaim":"registry_principal","requiredScopes":"unrestricted", + "accessProfiles":{"writer": {"default":true,"principalClaim":"registry_principal","requiredScopes":["records:write"], "requiredPurposes":["case-management"], "permissions":{"records":[{ "recordType":"widget","operations":["create","get","list","patch","batch"], @@ -3920,7 +3923,7 @@ fn located_refusal_registry() -> registry_breg::CompiledRegistry { {"id":"secret","type":"string","maximumLength":128,"required":false,"classification":"public"} ] }}, - "accessProfiles":{"writer": {"default":true,"principalClaim":"registry_principal","requiredScopes":"unrestricted", + "accessProfiles":{"writer": {"default":true,"principalClaim":"registry_principal","requiredScopes":["records:write"], "requiredPurposes":["case-management"], "permissions":{"records":[{ "recordType":"widget","operations":["create","get","list","patch","batch"], @@ -3930,7 +3933,7 @@ fn located_refusal_registry() -> registry_breg::CompiledRegistry { "sortableFields":["label"], "rowBoundaries":[{"field":"jurisdiction","claim":"jurisdiction","operator":"equals"}] }]} - },"keeper": {"principalClaim":"registry_principal","requiredScopes":"unrestricted", + },"keeper": {"principalClaim":"registry_principal","requiredScopes":["records:write"], "requiredPurposes":["case-review"], "permissions":{"records":[{ "recordType":"widget","operations":["get","list","patch"], @@ -3940,7 +3943,7 @@ fn located_refusal_registry() -> registry_breg::CompiledRegistry { "sortableFields":["secret"], "rowBoundaries":[{"field":"jurisdiction","claim":"jurisdiction","operator":"equals"}] }]} - },"drafter": {"principalClaim":"registry_principal","requiredScopes":"unrestricted", + },"drafter": {"principalClaim":"registry_principal","requiredScopes":["records:write"], "requiredPurposes":["case-drafting"], "permissions":{"records":[{ "recordType":"widget","operations":["create","get"], @@ -4726,7 +4729,12 @@ fn header_string(headers: &axum::http::HeaderMap, name: &str) -> String { } fn api_claims(purpose: &str, zone: Option<&str>) -> VerifiedRequestClaims { - api_claims_with_principal_and_scopes(PRINCIPAL_CANARY, purpose, zone, BTreeSet::new()) + api_claims_with_principal_and_scopes( + PRINCIPAL_CANARY, + purpose, + zone, + BTreeSet::from(["records:write".to_owned()]), + ) } fn api_claims_with_principal_and_scopes( @@ -4782,7 +4790,7 @@ fn compiled_registry() -> registry_breg::CompiledRegistry { {"id":"name","type":"string","maximumLength":128,"required":true,"classification":"public"} ] }}, - "accessProfiles":{"operator": {"default":true,"principalClaim":"registry_principal","requiredScopes":"unrestricted", + "accessProfiles":{"operator": {"default":true,"principalClaim":"registry_principal","requiredScopes":["records:write"], "requiredPurposes":["case-management","case-review"], "permissions":{"records":[{ "recordType":"widget","operations":["create","get","list","patch","tombstone"], @@ -4790,7 +4798,7 @@ fn compiled_registry() -> registry_breg::CompiledRegistry { "writableFields":["jurisdiction","label","note","quantity"], "rowBoundaries":[{"field":"jurisdiction","claim":"jurisdiction","operator":"equals"}] }]} - },"review-operator": {"principalClaim":"registry_principal","requiredScopes":"unrestricted", + },"review-operator": {"principalClaim":"registry_principal","requiredScopes":["records:write"], "requiredPurposes":["case-management"], "permissions":{"records":[{ "recordType":"widget","operations":["create","get","list","patch","tombstone"], @@ -4804,7 +4812,7 @@ fn compiled_registry() -> registry_breg::CompiledRegistry { "readableFields":["label"], "rowBoundaries": "unrestricted" }]} - },"label-editor": {"principalClaim":"registry_principal","requiredScopes":"unrestricted", + },"label-editor": {"principalClaim":"registry_principal","requiredScopes":["records:write"], "requiredPurposes":["case-management"], "permissions":{"records":[{ "recordType":"widget","operations":["get","patch"], @@ -4812,7 +4820,7 @@ fn compiled_registry() -> registry_breg::CompiledRegistry { "writableFields":["label"], "rowBoundaries":[{"field":"jurisdiction","claim":"jurisdiction","operator":"equals"}] }]} - },"case-operator": {"default":true,"principalClaim":"registry_principal","requiredScopes":"unrestricted", + },"case-operator": {"default":true,"principalClaim":"registry_principal","requiredScopes":["records:write"], "requiredPurposes":["case-management"], "permissions":{"records":[{ "recordType":"log","operations":["create","get","list"], @@ -6167,7 +6175,7 @@ fn linked_registry() -> registry_breg::CompiledRegistry { "externalViews":{"local-with-subject": {"recordType":"local-record", "links":[{"id":"subject","projection":"approved-subjects","fromField":"subjectkey"}] }}, - "accessProfiles":{"operator": {"default":true,"principalClaim":"registry_principal","requiredScopes":"unrestricted", + "accessProfiles":{"operator": {"default":true,"principalClaim":"registry_principal","requiredScopes":["records:write"], "requiredPurposes":["local-consultation"], "permissions":{"records":[{ "recordType":"local-record","operations":["create","get","list","patch"], diff --git a/crates/registry-breg/tests/postgres_mutation_logical_names.rs b/crates/registry-breg/tests/postgres_mutation_logical_names.rs index 1b38090d4b..8f6f4385fc 100644 --- a/crates/registry-breg/tests/postgres_mutation_logical_names.rs +++ b/crates/registry-breg/tests/postgres_mutation_logical_names.rs @@ -15,7 +15,7 @@ use serde_json::{json, Value}; #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn real_postgres_mutations_use_only_governed_api_field_names() { let harness = PilotHarness::start("asset-site-placement").await; - let token = harness.token("asset-management", &[]); + let token = harness.token_with_scopes("asset-management", &[], &["asset:manage"]); let created = harness .send_json( diff --git a/crates/registry-breg/tests/postgres_native_retention.rs b/crates/registry-breg/tests/postgres_native_retention.rs index 7d3de18076..ae1d7e05e0 100644 --- a/crates/registry-breg/tests/postgres_native_retention.rs +++ b/crates/registry-breg/tests/postgres_native_retention.rs @@ -80,7 +80,7 @@ fn registry_source(automatic: bool) -> Value { "actions":[{"action":"correct-name","operations":["start"],"targets":[{"recordType":"target", "rowBoundaries":[{"field":"jurisdiction","claim":"jurisdiction","operator":"equals"}]}]}], "proposals":[{"action":"correct-name","operations":["get","list","edit","submit","revise","rebase","retry","cancel","apply"], - "ownership":"caller","readableInputs":["target","value"],"readableAttachments":["support"],"writableAttachments":["support"],"targets":[{"recordType":"target", + "party":"owner","readableInputs":["target","value"],"readableAttachments":["support"],"writableAttachments":["support"],"targets":[{"recordType":"target", "rowBoundaries":[{"field":"jurisdiction","claim":"jurisdiction","operator":"equals"}]}]}]}}}}); source } diff --git a/crates/registry-breg/tests/postgres_package.rs b/crates/registry-breg/tests/postgres_package.rs index 0f8ca3c5fe..0344099d50 100644 --- a/crates/registry-breg/tests/postgres_package.rs +++ b/crates/registry-breg/tests/postgres_package.rs @@ -3657,7 +3657,7 @@ fn module_bytes(plan: PlanChoice) -> Vec { plan, PlanChoice::SecondTable | PlanChoice::ThirdTable | PlanChoice::HookSecondTable ) { - r#","second-record":{"primaryDataset":"neutral-registry","route":"second-records","mutationMode":"create-only","fields":[{"id":"code","type":"string","maximumLength":8,"classification":"internal"}],"accessProfiles":{"writer": {"principalClaim":"principal","operations":["get","create"],"readableFields":["code"],"writableFields":["code"], "requiredScopes":"unrestricted","rowBoundaries":"unrestricted"}}}"# + r#","second-record":{"primaryDataset":"neutral-registry","route":"second-records","mutationMode":"create-only","fields":[{"id":"code","type":"string","maximumLength":8,"classification":"internal"}],"accessProfiles":{"writer": {"principalClaim":"principal","operations":["get","create"],"readableFields":["code"],"writableFields":["code"], "requiredScopes":["records:write"],"rowBoundaries":"unrestricted"}}}"# } else { "" }; diff --git a/crates/registry-breg/tests/postgres_package/compiler_upgrade.rs b/crates/registry-breg/tests/postgres_package/compiler_upgrade.rs index b2423b1968..c277e4f9e9 100644 --- a/crates/registry-breg/tests/postgres_package/compiler_upgrade.rs +++ b/crates/registry-breg/tests/postgres_package/compiler_upgrade.rs @@ -601,7 +601,7 @@ fn indexed_module_bytes(other: OtherEntity) -> Vec { OtherEntity::Unchanged | OtherEntity::GainsAField => "second-records", }; format!( - r#"{{"apiVersion":"id.registrystack.org/formats/breg/module/v1alpha1","kind":"BRegModule","id":"core","version":"1","recordTypes":{{"neutral-record":{{"primaryDataset":"neutral-registry","route":"neutral-records","mutationMode":"create-only","fields":[{{"id":"code","type":"string","maximumLength":8,"classification":"internal"}}],"indexes":[{{"id":"code-idx","fields":["code"]}}],"accessProfiles":{{"reader":{{"requiredScopes":"unrestricted","rowBoundaries":"unrestricted","principalClaim":"principal","operations":["get","list"],"readableFields":["code"]}}}}}},"second-record":{{"primaryDataset":"neutral-registry","route":"{route}","mutationMode":"create-only","fields":[{{"id":"code","type":"string","maximumLength":8,"classification":"internal"}}{added}],"accessProfiles":{{"writer":{{"principalClaim":"principal","operations":["get","create"],"readableFields":["code"],"writableFields":["code"],"requiredScopes":"unrestricted","rowBoundaries":"unrestricted"}}}}}}}}}}"# + r#"{{"apiVersion":"id.registrystack.org/formats/breg/module/v1alpha1","kind":"BRegModule","id":"core","version":"1","recordTypes":{{"neutral-record":{{"primaryDataset":"neutral-registry","route":"neutral-records","mutationMode":"create-only","fields":[{{"id":"code","type":"string","maximumLength":8,"classification":"internal"}}],"indexes":[{{"id":"code-idx","fields":["code"]}}],"accessProfiles":{{"reader":{{"requiredScopes":"unrestricted","rowBoundaries":"unrestricted","principalClaim":"principal","operations":["get","list"],"readableFields":["code"]}}}}}},"second-record":{{"primaryDataset":"neutral-registry","route":"{route}","mutationMode":"create-only","fields":[{{"id":"code","type":"string","maximumLength":8,"classification":"internal"}}{added}],"accessProfiles":{{"writer":{{"principalClaim":"principal","operations":["get","create"],"readableFields":["code"],"writableFields":["code"],"requiredScopes":["records:write"],"rowBoundaries":"unrestricted"}}}}}}}}}}"# ) .into_bytes() } diff --git a/crates/registry-breg/tests/postgres_package/migration_capacity.rs b/crates/registry-breg/tests/postgres_package/migration_capacity.rs index dcc543c86f..199798ec32 100644 --- a/crates/registry-breg/tests/postgres_package/migration_capacity.rs +++ b/crates/registry-breg/tests/postgres_package/migration_capacity.rs @@ -98,7 +98,7 @@ fn reviewed_flow_project(profile_count: usize, proposal_operations: &[&str]) -> json!({ "action": format!("review-flow-{flow}"), "operations": proposal_operations, - "ownership": "caller", + "party": "owner", "readableInputs": readable_inputs, "targets": targets }) diff --git a/crates/registry-breg/tests/postgres_package/policy_upgrade.rs b/crates/registry-breg/tests/postgres_package/policy_upgrade.rs index 9bcb6df60b..a7dd783bab 100644 --- a/crates/registry-breg/tests/postgres_package/policy_upgrade.rs +++ b/crates/registry-breg/tests/postgres_package/policy_upgrade.rs @@ -19,7 +19,7 @@ async fn ordinary_profile_removal_applies_and_matches_fresh_catalog() { async fn ordinary_profile_operation_narrowing_applies_and_matches_fresh_catalog() { assert_profile_successor( Some(json!({ - "principalClaim": "principal", "requiredScopes":"unrestricted","rowBoundaries":"unrestricted", + "principalClaim": "principal", "requiredScopes":["records:write"],"rowBoundaries":"unrestricted", "operations": ["create"], "writableFields": ["code", "note"] })), ProfileSuccessor::Compiler, @@ -31,7 +31,7 @@ async fn ordinary_profile_operation_narrowing_applies_and_matches_fresh_catalog( async fn ordinary_profile_create_revocation_applies_and_matches_fresh_catalog() { assert_profile_successor( Some(json!({ - "principalClaim": "principal", "requiredScopes":"unrestricted","rowBoundaries":"unrestricted", + "principalClaim": "principal", "requiredScopes":["records:write"],"rowBoundaries":"unrestricted", "operations": ["get", "list"], "readableFields": ["code", "note"] })), ProfileSuccessor::Compiler, @@ -43,7 +43,7 @@ async fn ordinary_profile_create_revocation_applies_and_matches_fresh_catalog() async fn ordinary_profile_field_narrowing_applies_and_matches_fresh_catalog() { assert_profile_successor( Some(json!({ - "principalClaim": "principal", "requiredScopes":"unrestricted","rowBoundaries":"unrestricted", + "principalClaim": "principal", "requiredScopes":["records:write"],"rowBoundaries":"unrestricted", "operations": ["create", "get", "list"], "writableFields": ["code", "note"], "readableFields": ["code"] })), @@ -294,14 +294,14 @@ fn proposal_policy_sources(add_submitter: bool, add_optional_field: bool) -> (Ve json!({"casework-main": {"protocol": "id.registrystack.org/protocols/review/v1"}}); let profile = |id: &str, default: bool| { json!({ - id: {"default": default, "principalClaim": "principal", "requiredScopes": "unrestricted", + id: {"default": default, "principalClaim": "principal", "requiredScopes": ["proposals:write"], "permissions": { "records": [{"recordType": "asset", "operations": ["get", "list"], "readableFields": ["label"], "rowBoundaries": "unrestricted"}], "actions": [{"action": "correct-label", "operations": ["start"], "targets": [{"recordType": "asset", "rowBoundaries": "unrestricted"}]}], "proposals": [{"action": "correct-label", "operations": ["get", "list", "submit"], - "readableInputs": ["asset", "label"], "ownership": "caller", + "readableInputs": ["asset", "label"], "party": "owner", "targets": [{"recordType": "asset", "rowBoundaries": "unrestricted"}]}] }} }) @@ -391,7 +391,7 @@ pub(super) async fn fresh_fingerprint(registry: ®istry_breg::model::CompiledR async fn assert_profile_successor(auditor: Option, kind: ProfileSuccessor) { let baseline_bytes = profile_module(Some(json!({ - "principalClaim": "principal", "requiredScopes":"unrestricted","rowBoundaries":"unrestricted", + "principalClaim": "principal", "requiredScopes":["records:write"],"rowBoundaries":"unrestricted", "operations": ["create", "get", "list"], "writableFields": ["code", "note"], "readableFields": ["code", "note"] }))); diff --git a/crates/registry-breg/tests/postgres_package/reference_upgrade.rs b/crates/registry-breg/tests/postgres_package/reference_upgrade.rs index 53b1b09f3e..702d2f6bcd 100644 --- a/crates/registry-breg/tests/postgres_package/reference_upgrade.rs +++ b/crates/registry-breg/tests/postgres_package/reference_upgrade.rs @@ -970,7 +970,7 @@ fn reference_module_bytes(target: Option<&str>) -> Vec { ) }); format!( - r#"{{"apiVersion":"id.registrystack.org/formats/breg/module/v1alpha1","kind":"BRegModule","id":"core","version":"1","recordTypes":{{"site":{{"primaryDataset":"neutral-registry","route":"sites","mutationMode":"mutable","fields":[{{"id":"code","type":"string","maximumLength":16,"classification":"internal"}}],"accessProfiles":{{"reader":{{"principalClaim":"principal","requiredScopes":"unrestricted","rowBoundaries":"unrestricted","operations":["create","get","list","patch"],"readableFields":["code"],"writableFields":["code"]}}}}}},"location":{{"primaryDataset":"neutral-registry","route":"locations","mutationMode":"mutable","fields":[{{"id":"code","type":"string","maximumLength":16,"classification":"internal"}}],"accessProfiles":{{"reader":{{"principalClaim":"principal","requiredScopes":"unrestricted","rowBoundaries":"unrestricted","operations":["create","get","list","patch"],"readableFields":["code"],"writableFields":["code"]}}}}}},"asset":{{"primaryDataset":"neutral-registry","route":"assets","mutationMode":"mutable","fields":[{{"id":"code","type":"string","maximumLength":16,"classification":"internal"}}{reference_field}],"accessProfiles":{{"reader":{{"principalClaim":"principal","requiredScopes":"unrestricted","rowBoundaries":"unrestricted","operations":["create","get","list","patch"],"readableFields":["code"],"writableFields":["code"]}}}}}}}}}}"# + r#"{{"apiVersion":"id.registrystack.org/formats/breg/module/v1alpha1","kind":"BRegModule","id":"core","version":"1","recordTypes":{{"site":{{"primaryDataset":"neutral-registry","route":"sites","mutationMode":"mutable","fields":[{{"id":"code","type":"string","maximumLength":16,"classification":"internal"}}],"accessProfiles":{{"reader":{{"principalClaim":"principal","requiredScopes":["records:write"],"rowBoundaries":"unrestricted","operations":["create","get","list","patch"],"readableFields":["code"],"writableFields":["code"]}}}}}},"location":{{"primaryDataset":"neutral-registry","route":"locations","mutationMode":"mutable","fields":[{{"id":"code","type":"string","maximumLength":16,"classification":"internal"}}],"accessProfiles":{{"reader":{{"principalClaim":"principal","requiredScopes":["records:write"],"rowBoundaries":"unrestricted","operations":["create","get","list","patch"],"readableFields":["code"],"writableFields":["code"]}}}}}},"asset":{{"primaryDataset":"neutral-registry","route":"assets","mutationMode":"mutable","fields":[{{"id":"code","type":"string","maximumLength":16,"classification":"internal"}}{reference_field}],"accessProfiles":{{"reader":{{"principalClaim":"principal","requiredScopes":["records:write"],"rowBoundaries":"unrestricted","operations":["create","get","list","patch"],"readableFields":["code"],"writableFields":["code"]}}}}}}}}}}"# ) .into_bytes() } diff --git a/crates/registry-breg/tests/postgres_pilot_acceptance.rs b/crates/registry-breg/tests/postgres_pilot_acceptance.rs index 2fd37ea10a..c39a19ec01 100644 --- a/crates/registry-breg/tests/postgres_pilot_acceptance.rs +++ b/crates/registry-breg/tests/postgres_pilot_acceptance.rs @@ -38,9 +38,9 @@ async fn real_postgres_five_domain_pilot_is_configured_production_closed_and_sou } async fn asset_site_placement_journey(harness: &PilotHarness) { - let token = harness.token("asset-management", &[]); + let token = harness.token_with_scopes("asset-management", &[], &["asset:manage"]); assert_fixture_surface(harness, "asset-operator", &token, "asset").await; - let planner_token = harness.token("site-planning", &[]); + let planner_token = harness.token_with_scopes("site-planning", &[], &["asset:plan"]); let planner_openapi = assert_fixture_surface(harness, "site-planner", &planner_token, "asset").await; assert!(planner_openapi["paths"] @@ -414,7 +414,7 @@ async fn establishments_journey(harness: &PilotHarness) { } async fn inspection_journey(harness: &PilotHarness) { - let token = harness.token("facility-inspection", &[]); + let token = harness.token_with_scopes("facility-inspection", &[], &["inspection:manage"]); let openapi = assert_fixture_surface(harness, "inspection-inspector", &token, "inspection").await; assert_eq!( @@ -592,13 +592,15 @@ async fn inspection_journey(harness: &PilotHarness) { } async fn facility_journey(harness: &PilotHarness) { - let north_token = harness.token( + let north_token = harness.token_with_scopes( "facility-registry", &[("administrative_boundaries", json!(["north-district"]))], + &["registry:facility:operate"], ); - let south_token = harness.token( + let south_token = harness.token_with_scopes( "facility-registry", &[("administrative_boundaries", json!(["south-district"]))], + &["registry:facility:operate"], ); let openapi = assert_fixture_surface(harness, "facility-operator", &north_token, "facility").await; @@ -851,7 +853,7 @@ async fn facility_journey(harness: &PilotHarness) { } async fn business_journey(harness: &PilotHarness) { - let token = harness.token("business-registry", &[]); + let token = harness.token_with_scopes("business-registry", &[], &["business:register"]); assert_fixture_surface(harness, "business-registrar", &token, "business").await; let legal_entity = create_record( harness, diff --git a/crates/registry-breg/tests/postgres_proposal.rs b/crates/registry-breg/tests/postgres_proposal.rs index e1efb0d9d8..ae39a50fa0 100644 --- a/crates/registry-breg/tests/postgres_proposal.rs +++ b/crates/registry-breg/tests/postgres_proposal.rs @@ -4,6 +4,10 @@ #[path = "support/client_http.rs"] #[allow(dead_code)] mod client_http; +#[path = "support/membership_fixture.rs"] +mod membership_fixture; +#[path = "support/membership_write_project.rs"] +mod membership_write_project; #[path = "support/postgres_harness.rs"] #[allow(dead_code)] mod postgres_harness; @@ -134,7 +138,7 @@ fn registry_source(automatic: bool) -> Value { "actions":[{"action":"correct-name","operations":["start"],"targets":[{"recordType":"target", "rowBoundaries":[{"field":"jurisdiction","claim":"jurisdiction","operator":"equals"}]}]}], "proposals":[{"action":"correct-name","operations":["get","list","edit","submit","revise","rebase","retry","cancel","apply"], - "ownership":"caller","readableInputs":["target","value"],"readableAttachments":["support"],"writableAttachments":["support"],"targets":[{"recordType":"target", + "party":"owner","readableInputs":["target","value"],"readableAttachments":["support"],"writableAttachments":["support"],"targets":[{"recordType":"target", "rowBoundaries":[{"field":"jurisdiction","claim":"jurisdiction","operator":"equals"}]}]}]}}}}); source } @@ -638,7 +642,7 @@ async fn proposal_list_scans_hidden_rows_without_exposing_their_continuation() { source["accessProfiles"]["clerk"]["permissions"]["proposals"][0] .as_object_mut() .unwrap() - .remove("ownership"); + .remove("party"); let fixture = client_http::ClientFixture::start(compile(source), claims("author", "zone-a")).await; let mut drafts = Vec::new(); @@ -2211,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}", @@ -2597,6 +2602,223 @@ async fn proposal_list_audit_counts_only_each_actions_returned_items() { fixture.finish().await; } +#[tokio::test] +async fn proposal_list_correlates_membership_filtered_page_with_its_journal() { + let registry = membership_fixture::compile(&membership_write_project::proposal_project()) + .unwrap_or_else(|_| panic!("the maintained membership Proposal fixture must compile")); + let human = |principal, scopes| { + VerifiedRequestClaims::authenticated_with_actor_kind( + "sub", + principal, + scopes, + None, + BTreeMap::from([( + "sub".into(), + VerifiedClaimValue::direct_string(principal).unwrap(), + )]), + registry_platform_oidc::ActorKind::Human, + ) + .expect("fixture claims are valid") + }; + let fixture = + client_http::ClientFixture::start(registry, human("member", BTreeSet::new())).await; + let steward = fixture + .client_for(human( + "steward", + BTreeSet::from(["records:manage".into(), "membership:use".into()]), + )) + .await; + let member = &fixture.http.client; + let metadata = member + .registry_contract(Some("member")) + .await + .unwrap_or_else(|_| panic!("member metadata must be available")); + let action = metadata + .value + .select_action("propose-facility", "member") + .expect("member can start a facility Proposal"); + + let http = reqwest::Client::new(); + let create = async |route: &str, body: Value, idempotency_key: String| { + let response = http + .post(format!( + "{}/v1/records/{route}?accessProfile=steward", + steward.base_url + )) + .header("idempotency-key", idempotency_key) + .json(&body) + .send() + .await + .unwrap_or_else(|_| panic!("steward create request failed")); + assert!(response.status() == reqwest::StatusCode::CREATED); + let etag = response.headers().get("etag").cloned(); + let body: Value = response + .json() + .await + .unwrap_or_else(|_| panic!("steward create response must be JSON")); + let id = body["data"]["recordId"] + .as_str() + .expect("steward create returns a Record identifier") + .to_owned(); + (id, etag) + }; + let mut submitted = Vec::new(); + for index in 0..3 { + let (organization, _) = create( + "organizations", + json!({"data":{"name":format!("List organization {index}"),"owner":"member"}}), + format!("list-organization-{index}"), + ) + .await; + let (membership, etag) = create( + "memberships", + json!({"data":{"organization":organization,"principal":"member","active":true}}), + format!("list-membership-{index}"), + ) + .await; + let input = BRegActionInvocationRequest::new( + &action, + map(json!({"organization":organization,"label":format!("List facility {index}")})), + None, + ) + .unwrap_or_else(|_| panic!("fixture inputs must match the Action")); + let draft = member + .start_proposal(&action, &input, &key(&format!("list-start-{index}"))) + .await + .unwrap_or_else(|_| panic!("member must be able to start with active membership")) + .value; + let submit = member + .prepare_proposal( + &draft, + "submit", + json!({}), + &key(&format!("list-submit-{index}")), + ) + .unwrap_or_else(|_| panic!("member must be able to prepare submission")); + let proposal = member + .execute_proposal(&submit) + .await + .unwrap_or_else(|_| panic!("member must be able to submit with active membership")) + .value; + submitted.push((proposal.id().to_owned(), membership, etag)); + } + // The omitted candidate must sort between the returned item and the visible + // lookahead, so one bounded request necessarily scans all three candidates. + submitted.sort_by(|left, right| left.0.cmp(&right.0)); + let (first, _, _) = &submitted[0]; + let (_, membership, etag) = &submitted[1]; + let response = http + .patch(format!( + "{}/v1/records/memberships/{membership}?accessProfile=steward", + steward.base_url + )) + .header("content-type", "application/json-patch+json") + .header( + "if-match", + etag.clone().expect("membership create returns an ETag"), + ) + .header("idempotency-key", "list-withdraw-membership") + .json(&json!([{"op":"replace","path":"/data/active","value":false}])) + .send() + .await + .unwrap_or_else(|_| panic!("steward membership update request failed")); + assert!(response.status() == reqwest::StatusCode::OK); + + let before = fixture.audit_capture.entries().len(); + let response = http + .get(format!( + "{}/v1/proposals?accessProfile=member&limit=1", + fixture.http.base_url + )) + .send() + .await + .unwrap_or_else(|_| panic!("member list request failed")); + assert!(response.status() == reqwest::StatusCode::OK); + let trace_id = response + .headers() + .get("traceparent") + .and_then(|header| header.to_str().ok()) + .and_then(|header| header.split('-').nth(1)) + .expect("successful list returns a trace ID") + .to_owned(); + let page: Value = response + .json() + .await + .unwrap_or_else(|_| panic!("successful list response must be JSON")); + let items = page["items"].as_array().expect("list has an items array"); + assert_eq!(items.len(), 1); + assert!(items[0]["id"].as_str() == Some(first.as_str())); + let cursor = page["nextCursor"].as_str().expect("list has a next cursor"); + assert_eq!(cursor, first.as_str()); + + let entries = fixture.audit_capture.entries(); + let list_entries = &entries[before..]; + assert_eq!( + list_entries.len(), + 4, + "two attempts and two terminal records" + ); + let request_id = list_entries[0]["correlation"] + .as_str() + .expect("list attempt has a request correlation"); + assert!(uuid::Uuid::parse_str(request_id).is_ok()); + for entry in list_entries { + let record = &entry["record"]; + assert!(entry["correlation"].as_str() == Some(request_id)); + assert!(record["requestId"].as_str() == Some(request_id)); + assert!(record["traceId"].as_str() == Some(trace_id.as_str())); + } + for (action, count, outcome) in [ + ("propose-facility", 1, "returned"), + ("propose-move", 0, "empty"), + ] { + let operation = format!("proposals.{action}.list"); + for (phase, envelope_phase) in [("attempt", "request"), ("terminal", "response")] { + let matching = list_entries + .iter() + .filter(|entry| { + let record = &entry["record"]; + entry["phase"] == envelope_phase + && record["phase"] == phase + && record["method"] == "GET" + && record["operationId"].as_str() == Some(operation.as_str()) + && record["actionId"] == action + && (phase == "attempt" + || (record["resultCount"].as_u64() == Some(count) + && record["outcome"] == outcome)) + }) + .count(); + assert_eq!(matching, 1, "one {phase} journal record for {action}"); + } + } + + let response = http + .get(format!( + "{}/v1/proposals?accessProfile=member&limit=1&cursor={cursor}", + fixture.http.base_url + )) + .send() + .await + .unwrap_or_else(|_| panic!("member continuation request failed")); + assert_eq!(response.status(), reqwest::StatusCode::OK); + let page: Value = response + .json() + .await + .unwrap_or_else(|_| panic!("successful continuation response must be JSON")); + let items = page["items"] + .as_array() + .expect("continuation has an items array"); + assert_eq!(items.len(), 1); + assert_eq!(items[0]["id"].as_str(), Some(submitted[2].0.as_str())); + assert!( + page.get("nextCursor").is_none(), + "the visible list is exhausted" + ); + + drop(steward); + fixture.finish().await; +} + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn manual_no_review_attachments_cas_concealment_and_exact_receipt() { let fixture = client_http::ClientFixture::start( @@ -9592,7 +9814,7 @@ async fn standing_officer_grant_revises_only_named_inputs_and_withdraws_exact_re source["actions"]["correct-name"]["execution"]["proposal"]["review"] = json!({"type":"required","authority":"local-review","source":"proposal-test","policy":{"id":"name-correction","version":"1","digest":format!("sha256:{}","b".repeat(64))}}); source["accessProfiles"]["officer"]["requiredScopes"] = json!(["proposal:officer"]); let grant = &mut source["accessProfiles"]["officer"]["permissions"]["proposals"][0]; - grant.as_object_mut().unwrap().remove("ownership"); + grant.as_object_mut().unwrap().remove("party"); grant["writableInputs"] = json!(["value"]); let review = std::sync::Arc::new(LocalReview { calls: 0.into(), diff --git a/crates/registry-breg/tests/postgres_proposal_generated_identifiers.rs b/crates/registry-breg/tests/postgres_proposal_generated_identifiers.rs index c217ce5152..26f85b2e74 100644 --- a/crates/registry-breg/tests/postgres_proposal_generated_identifiers.rs +++ b/crates/registry-breg/tests/postgres_proposal_generated_identifiers.rs @@ -133,13 +133,13 @@ fn registry() -> registry_breg::CompiledRegistry { ], "proposals":[ {"action":"register-target", - "operations":["get","submit","revise","retry","apply"],"ownership":"caller", + "operations":["get","submit","revise","retry","apply"],"party":"owner", "readableInputs":["name","jurisdiction"], "targets":[{"recordType":"target","rowBoundaries":[{ "field":"jurisdiction","claim":"jurisdiction","operator":"equals" }]}]}, {"action":"register-target-with-document", - "operations":["get","edit","submit"],"ownership":"caller", + "operations":["get","edit","submit"],"party":"owner", "readableInputs":["name","jurisdiction"], "readableAttachments":["support"],"writableAttachments":["support"], "targets":[{"recordType":"target","rowBoundaries":[{ diff --git a/crates/registry-breg/tests/postgres_proposal_guard_failure.rs b/crates/registry-breg/tests/postgres_proposal_guard_failure.rs index e15f63fb62..41e95ec6e1 100644 --- a/crates/registry-breg/tests/postgres_proposal_guard_failure.rs +++ b/crates/registry-breg/tests/postgres_proposal_guard_failure.rs @@ -105,7 +105,7 @@ fn guard_project(readable: &[&str], offset: Option<(&str, i32)>) -> Value { "actions":[{"action":"correct-name","operations":["start"],"targets":[{"recordType":"target", "rowBoundaries":[{"field":"jurisdiction","claim":"jurisdiction","operator":"equals"}]}]}], "proposals":[{"action":"correct-name","operations":["get","list","edit","submit","revise","rebase","retry","cancel","apply"], - "ownership":"caller","readableInputs":["target","value","minimum"],"targets":[{"recordType":"target", + "party":"owner","readableInputs":["target","value","minimum"],"targets":[{"recordType":"target", "rowBoundaries":[{"field":"jurisdiction","claim":"jurisdiction","operator":"equals"}]}]}]}}}}); if let Some((member, offset)) = offset { source["project"]["timezone"] = json!("UTC"); diff --git a/crates/registry-breg/tests/postgres_proposal_human_recovery.rs b/crates/registry-breg/tests/postgres_proposal_human_recovery.rs index 1b5ff1016e..eeea94d223 100644 --- a/crates/registry-breg/tests/postgres_proposal_human_recovery.rs +++ b/crates/registry-breg/tests/postgres_proposal_human_recovery.rs @@ -42,7 +42,7 @@ fn registry(automatic: bool) -> registry_breg::CompiledRegistry { "records":[{"recordType":"contact","operations":["create","get"],"readableFields":["name","jurisdiction"], "writableFields":["name","jurisdiction"],"rowBoundaries":boundary}], "actions":[{"action":"correct-name","operations":["start"],"targets":targets}], - "proposals":[{"action":"correct-name","operations":["get","submit","apply","retry"],"ownership":"caller","targets":targets}]}}} + "proposals":[{"action":"correct-name","operations":["get","submit","apply","retry"],"party":"owner","targets":targets}]}}} }); compile_project( &parse_project_json(&serde_json::to_vec(&source).unwrap()).unwrap(), diff --git a/crates/registry-breg/tests/postgres_proposal_messages.rs b/crates/registry-breg/tests/postgres_proposal_messages.rs new file mode 100644 index 0000000000..85823afed0 --- /dev/null +++ b/crates/registry-breg/tests/postgres_proposal_messages.rs @@ -0,0 +1,2028 @@ +// SPDX-License-Identifier: Apache-2.0 + +//! A Proposal whose Action declares `messages` carries one thread between +//! the party (its owner or subject) and the office. BReg stores the thread, +//! decides both sides' authority, and keeps the turn: an unread office +//! message makes it the party's turn without changing the status. +#![cfg(feature = "postgres-test")] +#[path = "support/client_http.rs"] +#[allow(dead_code)] +mod client_http; +#[path = "support/postgres_harness.rs"] +#[allow(dead_code)] +mod postgres_harness; + +use axum::http::{HeaderMap, StatusCode}; +use registry_breg::api::VerifiedRequestClaims; +use registry_breg::compiler::{compile_project, CompileProfile}; +use registry_breg::contract::parse_project_json; +use registry_platform_oidc::ActorKind; +use serde_json::{json, Value}; +use std::collections::{BTreeMap, BTreeSet}; +use uuid::Uuid; + +const CLERK: &str = "clerk-canary"; +const CITIZEN: &str = "citizen-a-canary"; +const NEIGHBOUR: &str = "citizen-b-canary"; +const REVIEWER: &str = "reviewer-canary"; +const OFFICER: &str = "officer-canary"; + +const QUESTION: &str = "Is a scanned copy enough?"; +const ANSWER: &str = "A scan is enough."; + +fn targets() -> Value { + json!([{"recordType":"licence","rowBoundaries":"unrestricted"}]) +} + +fn source() -> Value { + let policy = + json!({"id":"licence-review","version":"1","digest":format!("sha256:{}","b".repeat(64))}); + let inputs = json!([ + {"id":"holder","type":"string","maximumLength":64,"required":true,"classification":"internal"}, + {"id":"statement","type":"string","maximumLength":64,"required":false,"classification":"internal"}]); + let plan = json!({"type":"fixed","effects":[{"id":"issued","target":{"recordType":"licence"},"operation":"create", + "set":{"holder":{"fromInput":"holder"},"statement":{"fromInput":"statement"}}}]}); + let review_free = |messages: Option| { + let mut proposal = json!({"review":{"type":"none"},"application":{"mode":"manual"},"retention":{"mode":"retain"}}); + if messages + .as_ref() + .is_some_and(|messages| messages.get("automatic").is_some()) + { + proposal["application"] = json!({"mode":"automatic","maximumAttempts":3}); + } + let messages = messages.map(|mut messages| { + messages.as_object_mut().unwrap().remove("automatic"); + messages + }); + if let Some(messages) = messages { + proposal["messages"] = messages; + } + json!({"execution":{"mode":"proposal","proposal":proposal},"inputs":inputs,"plan":plan}) + }; + let owner = |action: &str, operations: Value| { + json!({"action":action,"party":"owner","operations":operations, + "readableInputs":["holder","statement"],"writableInputs":["holder","statement"],"targets":targets()}) + }; + json!({ + "apiVersion":"id.registrystack.org/formats/breg/project/v1alpha1","kind":"BRegProject", + "project":{"id":"proposal-messages","version":"1","defaultLanguage":"en","canonicalBaseIri":"https://proposal-messages.example.test"}, + "datasets":{"licences": {}}, + "reviewAuthorities":{"local-review": {"protocol":"id.registrystack.org/protocols/review/v1"}}, + "recordTypes":{ + "licence": {"route":"licences","primaryDataset":"licences","mutationMode":"mutable","classification":"internal", + "batch":{"maximumItems":3,"maximumBytes":8192}, + "fields":[ + {"id":"holder","type":"string","maximumLength":64,"required":true,"classification":"internal"}, + {"id":"statement","type":"string","maximumLength":64,"required":false,"classification":"internal"}]}}, + "actions":{ + // Reviewed, with a declared subject and a small thread limit. + "apply-for-licence": {"execution":{"mode":"proposal","proposal":{ + "review":{"type":"required","authority":"local-review","source":"licence-test","policy":policy}, + "application":{"mode":"manual"},"retention":{"mode":"operator-erase"}, + "subject":{"input":"holder"}, + "messages":{"maximumCount":4}, + "reviewContext":{"id":"licence-context","fields":{"holder":{"type":"input","input":"holder"}}}}}, + "inputs":inputs,"plan":plan}, + // No review: an officer who applies by hand can still talk to the applicant (D6). + "record-change": review_free(Some(json!({}))), + "automatic-change": review_free(Some(json!({"automatic":true}))), + // No thread. + "quiet-change": review_free(None)}, + "accessProfiles":{ + "desk": {"principalClaim":"sub","requiredScopes":["licence:desk"],"actorKind":"human", + "permissions":{ + "actions":[{"action":"apply-for-licence","operations":["start"],"targets":targets()}], + "proposals":[{"action":"apply-for-licence","party":"owner","submitsFor":"anyone", + "operations":["get","list","edit","submit","revise","cancel","get-review-status"], + "readableInputs":["holder","statement"],"targets":targets()}]}}, + "citizen": {"principalClaim":"sub","requiredScopes":["licence:self"],"actorKind":"human", + "permissions":{ + "actions":[ + {"action":"apply-for-licence","operations":["start"],"targets":targets()}, + {"action":"record-change","operations":["start"],"targets":targets()}, + {"action":"automatic-change","operations":["start"],"targets":targets()}, + {"action":"quiet-change","operations":["start"],"targets":targets()}], + "proposals":[ + owner("apply-for-licence", json!(["get","list","edit","submit","revise","cancel","get-review-status","message"])), + {"action":"apply-for-licence","party":"subject", + "operations":["get","list","cancel","get-review-status","message"], + "readableInputs":["holder"],"targets":targets()}, + owner("record-change", json!(["get","list","edit","submit","cancel","message"])), + owner("automatic-change", json!(["get","list","edit","submit","cancel","message"])), + owner("quiet-change", json!(["get","list","edit","submit","cancel"]))]}}, + // The usual reviewer: the review context and the thread, nothing else. + "reviewer": {"principalClaim":"sub","requiredScopes":["licence:review"],"actorKind":"human", + "permissions":{"proposals":[ + {"action":"apply-for-licence","operations":["get-review-context","message"], + "readableContextFields":["holder"],"targets":targets()}]}}, + "owner-review": {"principalClaim":"sub","requiredScopes":["licence:self"],"actorKind":"human", + "permissions":{"proposals":[ + {"action":"apply-for-licence","party":"owner","operations":["get-review-context","message"], + "readableContextFields":["holder"],"targets":targets()}]}}, + // Written for any actor kind: only the human test keeps a + // service with a reviewer's grant out of the thread. + "relay": {"principalClaim":"sub","requiredScopes":["licence:relay"], + "permissions":{"proposals":[ + {"action":"apply-for-licence","operations":["get-review-context","message"], + "readableContextFields":["holder"],"targets":targets()}]}}, + // The office side of the review-free Actions. + "office": {"principalClaim":"sub","requiredScopes":["licence:office"],"actorKind":"human", + "permissions":{ + "records":[{"recordType":"licence","operations":["create","get"], + "readableFields":["holder","statement"],"writableFields":["holder","statement"],"rowBoundaries":"unrestricted"}], + "proposals":[ + {"action":"record-change","operations":["get","list","apply","message"], + "readableInputs":["holder","statement"],"targets":targets()}, + {"action":"automatic-change","operations":["get","list","message"], + "readableInputs":["holder","statement"],"targets":targets()}, + {"action":"quiet-change","operations":["get","list","apply"], + "readableInputs":["holder","statement"],"targets":targets()}]}}} + }) +} + +fn compile(source: &Value) -> registry_breg::CompiledRegistry { + let project = parse_project_json(&serde_json::to_vec(source).unwrap()).unwrap(); + compile_project(&project, &[], CompileProfile::Authoring).expect("messages project compiles") +} + +fn person(principal: &str, scope: &str, kind: ActorKind) -> VerifiedRequestClaims { + VerifiedRequestClaims::authenticated_with_actor_kind( + "sub", + principal, + BTreeSet::from([scope.to_owned()]), + Some("licence-portal".into()), + BTreeMap::new(), + kind, + ) + .unwrap() +} + +fn clerk() -> VerifiedRequestClaims { + person(CLERK, "licence:desk", ActorKind::Human) +} + +fn citizen(principal: &str) -> VerifiedRequestClaims { + person(principal, "licence:self", ActorKind::Human) +} + +fn reviewer() -> VerifiedRequestClaims { + person(REVIEWER, "licence:review", ActorKind::Human) +} + +fn officer() -> VerifiedRequestClaims { + person(OFFICER, "licence:office", ActorKind::Human) +} + +struct NoToken; +#[async_trait::async_trait] +impl registry_platform_httputil::TokenProvider for NoToken { + async fn bearer_token( + &self, + ) -> Result + { + Err(registry_platform_httputil::TokenError::Unavailable) + } +} + +struct NoResult; +#[async_trait::async_trait] +impl registry_breg::review_store::ReviewResultSource for NoResult { + async fn approved_evidence( + &self, + _authority: &str, + _accepted: ®istry_review_client::ReviewRequestAccepted, + ) -> Result< + registry_breg::review_integration::AcceptedReviewEvidence, + registry_breg::mutation::MutationError, + > { + Err(registry_breg::mutation::MutationError::Unavailable) + } +} + +fn local_review() -> std::sync::Arc { + use registry_breg::review_store::{ReviewAuthorityClient, ReviewAuthorityRegistry}; + let client = registry_review_client::ReviewClient::new( + registry_review_client::ReviewClientConfig::new_without_peer_policy( + "http://127.0.0.1:9/".parse().unwrap(), + ), + ) + .unwrap(); + let authority = std::sync::Arc::new( + ReviewAuthorityClient::new( + "local-review".into(), + client, + std::sync::Arc::new(NoToken), + "producer".into(), + "proposal-producer".into(), + 7, + None, + None, + ) + .unwrap(), + ); + std::sync::Arc::new( + ReviewAuthorityRegistry::new(BTreeMap::from([("local-review".into(), authority)])).unwrap(), + ) +} + +async fn fixture() -> client_http::ClientFixture { + client_http::ClientFixture::start_with_mutations(compile(&source()), officer(), |mutations| { + mutations + .with_proposal_review_substitute_for_test(local_review(), std::sync::Arc::new(NoResult)) + }) + .await +} + +async fn request( + fixture: &client_http::ClientFixture, + caller: VerifiedRequestClaims, + method: &str, + path: &str, + etag: Option<&str>, + key: Option<&str>, + body: Value, +) -> (StatusCode, HeaderMap, Value) { + use tower::ServiceExt; + let mut req = axum::http::Request::builder() + .method(method) + .uri(path) + .header("content-type", "application/json"); + if let Some(etag) = etag { + req = req.header("if-match", etag); + } + if let Some(key) = key { + req = req.header("idempotency-key", key); + } + let response = registry_breg::api::router(fixture.service()) + .layer(axum::Extension(caller)) + .oneshot( + req.body(if method == "GET" { + axum::body::Body::empty() + } else { + axum::body::Body::from(serde_json::to_vec(&body).unwrap()) + }) + .unwrap(), + ) + .await + .unwrap(); + let status = response.status(); + let headers = response.headers().clone(); + let bytes = axum::body::to_bytes(response.into_body(), 1 << 22) + .await + .unwrap(); + let value = if bytes.is_empty() { + Value::Null + } else { + serde_json::from_slice(&bytes).unwrap() + }; + (status, headers, value) +} + +async fn get( + fixture: &client_http::ClientFixture, + caller: VerifiedRequestClaims, + id: Uuid, +) -> (StatusCode, Option, Value) { + let (status, headers, value) = request( + fixture, + caller, + "GET", + &format!("/v1/proposals/{id}"), + None, + None, + Value::Null, + ) + .await; + let etag = headers + .get("etag") + .map(|etag| etag.to_str().unwrap().to_owned()); + (status, etag, value) +} + +/// Run a Proposal command as `caller` against the caller's current ETag. +async fn command( + fixture: &client_http::ClientFixture, + caller: VerifiedRequestClaims, + id: Uuid, + operation: &str, + key: &str, + body: Value, +) -> (StatusCode, Value) { + let (status, etag, document) = get(fixture, caller.clone(), id).await; + assert_eq!(status, StatusCode::OK, "{document}"); + let (status, _, value) = request( + fixture, + caller, + "POST", + &format!("/v1/proposals/{id}/{operation}"), + etag.as_deref(), + Some(key), + body, + ) + .await; + (status, value) +} + +async fn start( + fixture: &client_http::ClientFixture, + caller: VerifiedRequestClaims, + action: &str, + input: Value, + key: &str, +) -> Uuid { + let (status, _, value) = request( + fixture, + caller, + "POST", + &format!("/v1/actions/{action}/proposals"), + None, + Some(key), + json!({ "input": input }), + ) + .await; + assert_eq!(status, StatusCode::CREATED, "{value}"); + Uuid::parse_str(value["id"].as_str().unwrap()).unwrap() +} + +/// A Proposal of `action` that `caller` filed naming `holder`, submitted. +async fn filed( + fixture: &client_http::ClientFixture, + caller: VerifiedRequestClaims, + action: &str, + holder: &str, + key: &str, +) -> Uuid { + let id = start( + fixture, + caller.clone(), + action, + json!({"holder":holder,"statement":"Original statement"}), + &format!("{key}-start"), + ) + .await; + let (status, value) = command( + fixture, + caller, + id, + "submit", + &format!("{key}-submit"), + json!({}), + ) + .await; + assert_eq!(status, StatusCode::OK, "{value}"); + id +} + +/// Write `text` to the thread as a caller who can Get the Proposal. +async fn write( + fixture: &client_http::ClientFixture, + caller: VerifiedRequestClaims, + profile: &str, + id: Uuid, + text: &str, + key: &str, +) -> (StatusCode, HeaderMap, Value) { + let (status, etag, document) = get(fixture, caller.clone(), id).await; + assert_eq!(status, StatusCode::OK, "{document}"); + request( + fixture, + caller, + "POST", + &format!("/v1/proposals/{id}/messages?accessProfile={profile}"), + etag.as_deref(), + Some(key), + json!({ "text": text }), + ) + .await +} + +async fn review_context( + fixture: &client_http::ClientFixture, + caller: VerifiedRequestClaims, + profile: &str, + id: Uuid, + include: &str, +) -> (StatusCode, Value) { + let (status, _, value) = request( + fixture, + caller, + "GET", + &format!("/v1/proposals/{id}/review-context?accessProfile={profile}{include}"), + None, + None, + Value::Null, + ) + .await; + (status, value) +} + +async fn list( + fixture: &client_http::ClientFixture, + caller: VerifiedRequestClaims, + query: &str, +) -> Vec { + let (status, _, page) = request( + fixture, + caller, + "GET", + &format!("/v1/proposals{query}"), + None, + None, + Value::Null, + ) + .await; + assert_eq!(status, StatusCode::OK, "{page}"); + page["items"].as_array().unwrap().clone() +} + +async fn mark_read( + fixture: &client_http::ClientFixture, + caller: VerifiedRequestClaims, + profile: &str, + id: Uuid, + through: &str, +) -> (StatusCode, Value) { + let (status, _, value) = request( + fixture, + caller, + "POST", + &format!("/v1/proposals/{id}/messages/read?accessProfile={profile}"), + None, + None, + json!({ "through": through }), + ) + .await; + (status, value) +} + +/// Each command link's name and availability, apart from the thread's own. +fn offered(document: &Value) -> BTreeMap { + document["links"] + .as_object() + .map(|links| { + links + .iter() + .map(|(name, link)| { + let mut availability = link["availability"].clone(); + if let Some(availability) = availability.as_object_mut() { + availability.remove("observedRevision"); + } + (name.clone(), availability) + }) + .collect() + }) + .unwrap_or_default() +} + +/// A served message carries no officer name, pseudonym or sender reference. +fn assert_value_free_sender(item: &Value) { + let keys = item + .as_object() + .unwrap() + .keys() + .map(String::as_str) + .collect::>(); + let allowed = BTreeSet::from(["id", "from", "partyRole", "mine", "sentAt", "text"]); + assert!(keys.is_subset(&allowed), "{item}"); + assert!(!item.to_string().contains(REVIEWER), "{item}"); + assert!(!item.to_string().contains(OFFICER), "{item}"); +} + +/// Return the current review round with changes requested, so the party has +/// the turn and Revise is open. +async fn request_changes(fixture: &client_http::ClientFixture, id: Uuid) { + decide(fixture, id, "changes-requested").await; +} + +/// Record the review authority's `outcome` for the current round. +async fn decide(fixture: &client_http::ClientFixture, id: Uuid, outcome: &str) { + let row = fixture + .database + .admin + .query_one( + "SELECT create_request,expected_submission_digest FROM registry_internal.registry_proposal_review_submissions + WHERE proposal_id=$1 ORDER BY submission_version DESC LIMIT 1", + &[&id], + ) + .await + .unwrap(); + let create: registry_review_client::ReviewCreateRequest = + serde_json::from_value(row.get(0)).unwrap(); + let accepted = registry_review_client::ReviewRequestAccepted { + request_id: Uuid::new_v4(), + subject: create.subject, + policy: serde_json::from_value(json!({"id":"licence-review","version":"1","digest":format!("sha256:{}","b".repeat(64))})).unwrap(), + submission_digest: serde_json::from_value(json!(row.get::<_, String>(1))).unwrap(), + }; + fixture + .database + .admin + .execute( + "UPDATE registry_internal.registry_proposal_review_submissions SET state='accepted',accepted_binding=$2 + WHERE proposal_id=$1 AND state<>'accepted'", + &[&id, &serde_json::to_value(&accepted).unwrap()], + ) + .await + .unwrap(); + let now = chrono::Utc::now(); + let result = registry_review_client::ReviewResult { + result_id: Uuid::new_v4(), + request_id: accepted.request_id, + subject: accepted.subject.clone(), + policy: accepted.policy.clone(), + submission_digest: accepted.submission_digest.clone(), + status: serde_json::from_value(json!(outcome)).unwrap(), + outcome: Some(outcome.to_owned()), + public_reason: Some("Public reason for the applicant".to_owned()), + result: None, + completed_at: now - chrono::Duration::seconds(2), + available_until: now + chrono::Duration::minutes(5), + }; + let (mut migration, task) = fixture.database.connect_migration().await; + let tx = migration.transaction().await.unwrap(); + registry_breg::review_store::reconcile_result( + &tx, + "local-review", + &accepted, + &result, + &fixture.mutations, + ) + .await + .unwrap(); + tx.commit().await.unwrap(); + drop(migration); + task.abort(); +} + +/// The first acceptance criterion of #2801, and the turn rule (D4): the +/// applicant writes, the reviewer reads it in the review context and answers +/// through `links.message`, and the applicant reads the answer with a +/// Proposal grant only. +#[tokio::test] +async fn the_applicant_and_the_reviewer_exchange_messages_and_an_unread_answer_is_the_partys_turn() +{ + let fixture = fixture().await; + let id = filed( + &fixture, + citizen(CITIZEN), + "apply-for-licence", + CITIZEN, + "exchange", + ) + .await; + let (_, before_etag, before) = get(&fixture, citizen(CITIZEN), id).await; + let status_before = before["status"].clone(); + assert_ne!(before["turn"], "party", "{before}"); + assert_eq!(before["messages"]["count"], 0, "{before}"); + assert!(before["messages"].get("lastSentAt").is_none(), "{before}"); + assert_eq!( + before["messages"]["links"]["message"]["path"], + format!("/v1/proposals/{id}/messages") + ); + for operation in ["markRead", "list"] { + let link = &before["messages"]["links"][operation]; + assert!(link.get("ifMatch").is_none(), "{link}"); + let availability = &link["availability"]; + assert_eq!(availability["available"], true, "{availability}"); + assert!(availability.get("reason").is_none(), "{availability}"); + assert!(availability.get("recovery").is_none(), "{availability}"); + } + + let (status, headers, written) = write( + &fixture, + citizen(CITIZEN), + "citizen", + id, + QUESTION, + "citizen-asks", + ) + .await; + assert_eq!(status, StatusCode::OK, "{written}"); + assert_ne!( + headers.get("etag").map(|etag| etag.to_str().unwrap()), + before_etag.as_deref() + ); + let question = &written["messages"]["items"][0]; + assert_eq!(written["messages"]["count"], 1, "{written}"); + assert_eq!(question["from"], "party"); + assert_eq!(question["partyRole"], "owner"); + assert_eq!(question["mine"], true); + assert_eq!(question["text"], QUESTION); + // A party message is not the party's turn to read. + assert_ne!(written["turn"], "party", "{written}"); + + // The review-context read carries the thread only when asked. + let (status, plain) = review_context(&fixture, reviewer(), "reviewer", id, "").await; + assert_eq!(status, StatusCode::OK, "{plain}"); + assert!(plain["context"].get("messages").is_none(), "{plain}"); + let (status, context) = + review_context(&fixture, reviewer(), "reviewer", id, "&include=messages").await; + assert_eq!(status, StatusCode::OK, "{context}"); + let thread = &context["context"]["messages"]; + assert_eq!(thread["count"], 1, "{context}"); + assert_eq!(thread["unread"], 1, "{context}"); + assert!(thread.get("readerSide").is_none(), "{context}"); + assert_eq!(thread["items"][0]["text"], QUESTION); + assert_eq!(thread["items"][0]["from"], "party"); + assert_eq!(thread["items"][0]["partyRole"], "owner"); + assert_eq!(thread["items"][0]["mine"], false); + let link = &thread["links"]["message"]; + assert_eq!(link["method"], "POST"); + assert_eq!(link["path"], format!("/v1/proposals/{id}/messages")); + assert_eq!(link["operation"], "message"); + + // The reviewer holds no `get`: the answer returns the review context. + let (status, answer_headers, answered) = request( + &fixture, + reviewer(), + "POST", + &format!("{}?accessProfile=reviewer", link["path"].as_str().unwrap()), + link["ifMatch"].as_str(), + Some("reviewer-answers"), + json!({ "text": ANSWER }), + ) + .await; + assert_eq!(status, StatusCode::OK, "{answered}"); + let official = &answered["context"]["messages"]["items"][0]; + assert_eq!(official["from"], "official", "{answered}"); + assert_eq!(official["mine"], true); + assert!(official.get("partyRole").is_none(), "{official}"); + + // The applicant reads the answer with a Proposal grant only. While it + // is unread it is the party's turn; the status does not move. + let (status, _, waiting) = get(&fixture, citizen(CITIZEN), id).await; + assert_eq!(status, StatusCode::OK, "{waiting}"); + let messages = &waiting["messages"]; + assert_eq!(messages["count"], 2, "{waiting}"); + assert_eq!(messages["unread"], 1, "{waiting}"); + assert!(messages["lastSentAt"].is_string(), "{waiting}"); + let answer = &messages["items"][0]; + assert_eq!(answer["text"], ANSWER); + assert_eq!(answer["from"], "official"); + assert_eq!(answer["mine"], false); + for item in messages["items"].as_array().unwrap() { + assert_value_free_sender(item); + } + assert_eq!(waiting["turn"], "party", "{waiting}"); + assert_eq!(waiting["status"], status_before, "{waiting}"); + // Every offered command keeps its availability. + assert_eq!( + offered(&waiting), + offered(&before), + "an unread message changed what the party may do" + ); + let listed = list(&fixture, citizen(CITIZEN), "?turn=party").await; + assert_eq!(listed.len(), 1, "{listed:?}"); + assert_eq!(listed[0]["id"], id.to_string()); + assert_eq!(listed[0]["messages"]["unread"], 1); + assert_eq!(listed[0]["messages"]["count"], 2); + assert!( + listed[0]["messages"].get("items").is_none(), + "{:?}", + listed[0] + ); + + // The inbox batch reports the position that supplied the unread count. + // Neither side has marked the other side's message as read. + for (caller, profile, side) in [ + (reviewer(), "reviewer", "official"), + (citizen(CITIZEN), "owner-review", "party"), + ] { + let (status, _, batch) = request( + &fixture, + caller, + "GET", + &format!("/v1/proposals/review-context?ids={id}&accessProfile={profile}"), + None, + None, + Value::Null, + ) + .await; + assert_eq!(status, StatusCode::OK, "{batch}"); + let summary = &batch["items"][0]["context"]["context"]["messages"]; + assert_eq!(summary["count"], 2, "{batch}"); + assert_eq!(summary["unread"], 1, "{batch}"); + assert_eq!(summary["readerSide"], side, "{batch}"); + assert!(summary["lastSentAt"].is_string(), "{batch}"); + assert!(summary.get("items").is_none(), "{batch}"); + assert!(summary.get("links").is_none(), "{batch}"); + let served = batch.to_string(); + assert!(!served.contains(QUESTION) && !served.contains(ANSWER)); + } + + // Mark-read moves the party's side forward; repeating it changes nothing. + let through = answer["id"].as_str().unwrap().to_owned(); + for _ in 0..2 { + let (status, read) = mark_read(&fixture, citizen(CITIZEN), "citizen", id, &through).await; + assert_eq!(status, StatusCode::OK, "{read}"); + assert_eq!(read["messages"]["unread"], 0, "{read}"); + assert_ne!(read["turn"], "party", "{read}"); + assert_eq!(read["status"], status_before, "{read}"); + } + assert!(list(&fixture, citizen(CITIZEN), "?turn=party") + .await + .is_empty()); + + let (status, replay_headers, replay) = request( + &fixture, + reviewer(), + "POST", + &format!("{}?accessProfile=reviewer", link["path"].as_str().unwrap()), + link["ifMatch"].as_str(), + Some("reviewer-answers"), + json!({"text":ANSWER}), + ) + .await; + assert_eq!(status, StatusCode::OK, "{replay}"); + assert_eq!(replay_headers["etag"], answer_headers["etag"]); + assert_eq!( + replay, answered, + "the held review response is exact after mark-read" + ); + + let events = fixture + .database + .admin + .query( + "SELECT payload FROM registry_internal.registry_outbox + WHERE event_type='proposal.messaged' ORDER BY record_revision", + &[], + ) + .await + .unwrap(); + assert_eq!( + events.len(), + 2, + "read markers and replays emit no message event" + ); + for (event, side) in events.iter().zip(["party", "official"]) { + let bytes: Vec = event.get(0); + let wire: Value = serde_json::from_slice(&bytes).unwrap(); + assert_eq!(wire["data"]["messageFrom"], side); + assert!(wire["data"].get("text").is_none()); + let serialized = String::from_utf8_lossy(&bytes); + assert!(!serialized.contains(QUESTION) && !serialized.contains(ANSWER)); + } + + // The paged list returns newest first. + let (status, _, page) = request( + &fixture, + citizen(CITIZEN), + "GET", + &format!("/v1/proposals/{id}/messages?accessProfile=citizen&limit=1"), + None, + None, + Value::Null, + ) + .await; + assert_eq!(status, StatusCode::OK, "{page}"); + assert_eq!(page["items"].as_array().unwrap().len(), 1, "{page}"); + assert_eq!(page["items"][0]["text"], ANSWER); + let cursor = page["nextCursor"] + .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&%6Cimit=%2B1&%63ursor={encoded_cursor}"), + None, + None, + Value::Null, + ) + .await; + assert_eq!(status, StatusCode::OK, "{rest}"); + assert_eq!(rest["items"][0]["text"], QUESTION); + assert!(rest.get("nextCursor").is_none() || rest["nextCursor"].is_null()); + + // Text never reaches audit. + let audit = serde_json::to_string(&fixture.audit_capture.entries()).unwrap(); + assert!(!audit.contains(QUESTION) && !audit.contains(ANSWER)); + fixture.finish().await; +} + +/// The party is the owner or the subject. Both post and read; a neighbour +/// with the same profile learns nothing on any thread route. +#[tokio::test] +async fn the_owner_and_the_subject_post_and_read_and_a_neighbour_gets_not_found() { + let fixture = fixture().await; + let id = filed( + &fixture, + clerk(), + "apply-for-licence", + CITIZEN, + "desk-files", + ) + .await; + + let (status, _, written) = write( + &fixture, + citizen(CITIZEN), + "citizen", + id, + "Filed for me: what happens next?", + "subject-writes", + ) + .await; + assert_eq!(status, StatusCode::OK, "{written}"); + assert_eq!(written["partyRole"], "subject"); + let item = &written["messages"]["items"][0]; + assert_eq!(item["from"], "party"); + assert_eq!(item["partyRole"], "subject"); + assert_eq!(item["mine"], true); + + let (status, context) = + review_context(&fixture, reviewer(), "reviewer", id, "&include=messages").await; + assert_eq!(status, StatusCode::OK, "{context}"); + assert_eq!( + context["context"]["messages"]["items"][0]["partyRole"], + "subject" + ); + let link = context["context"]["messages"]["links"]["message"].clone(); + let (status, _, answered) = request( + &fixture, + reviewer(), + "POST", + &format!("{}?accessProfile=reviewer", link["path"].as_str().unwrap()), + link["ifMatch"].as_str(), + Some("reviewer-answers-subject"), + json!({ "text": ANSWER }), + ) + .await; + assert_eq!(status, StatusCode::OK, "{answered}"); + let (status, _, followed) = get(&fixture, citizen(CITIZEN), id).await; + assert_eq!(status, StatusCode::OK, "{followed}"); + assert_eq!(followed["messages"]["items"][0]["text"], ANSWER); + assert_eq!(followed["messages"]["unread"], 1); + + // The clerk owns the Proposal through a grant without `message`: no + // member, and the write is refused by name, not concealed. + let (status, etag, filer) = get(&fixture, clerk(), id).await; + assert_eq!(status, StatusCode::OK, "{filer}"); + assert!(filer.get("messages").is_none(), "{filer}"); + let (status, _, refused) = request( + &fixture, + clerk(), + "POST", + &format!("/v1/proposals/{id}/messages?accessProfile=desk"), + etag.as_deref(), + Some("clerk-writes"), + json!({"text":"From the desk"}), + ) + .await; + assert_eq!(status, StatusCode::FORBIDDEN, "{refused}"); + assert_eq!(refused["code"], "profile.not-authorized"); + + // A neighbour gets 404 on every thread route. + let neighbour_routes = [ + ( + "POST", + format!("/v1/proposals/{id}/messages?accessProfile=citizen"), + Some("\"breg-proposal-guess\""), + Some("neighbour-writes"), + json!({"text":"Guess"}), + ), + ( + "GET", + format!("/v1/proposals/{id}/messages?accessProfile=citizen"), + None, + None, + Value::Null, + ), + ( + "POST", + format!("/v1/proposals/{id}/messages/read?accessProfile=citizen"), + None, + None, + json!({"through": Uuid::new_v4()}), + ), + ]; + for (method, path, etag, key, body) in neighbour_routes { + let (status, _, concealed) = + request(&fixture, citizen(NEIGHBOUR), method, &path, etag, key, body).await; + assert_eq!( + status, + StatusCode::NOT_FOUND, + "{method} {path}: {concealed}" + ); + assert_eq!(concealed["code"], "resource.not-found", "{concealed}"); + } + let (status, _, _) = get(&fixture, citizen(NEIGHBOUR), id).await; + assert_eq!(status, StatusCode::NOT_FOUND); + for item in list(&fixture, citizen(NEIGHBOUR), "").await { + assert_ne!(item["id"], id.to_string()); + } + 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. +#[tokio::test] +async fn messages_need_no_review_and_close_for_writes_when_the_request_is_applied() { + let fixture = fixture().await; + let id = filed( + &fixture, + citizen(CITIZEN), + "record-change", + CITIZEN, + "review-free", + ) + .await; + let (status, _, written) = write( + &fixture, + citizen(CITIZEN), + "citizen", + id, + QUESTION, + "review-free-asks", + ) + .await; + assert_eq!(status, StatusCode::OK, "{written}"); + + let (status, _, office_view) = get(&fixture, officer(), id).await; + assert_eq!(status, StatusCode::OK, "{office_view}"); + assert_eq!(office_view["messages"]["items"][0]["text"], QUESTION); + assert_eq!(office_view["messages"]["items"][0]["from"], "party"); + assert!(office_view.get("partyRole").is_none(), "{office_view}"); + let (status, _, answered) = write( + &fixture, + officer(), + "office", + id, + ANSWER, + "review-free-answers", + ) + .await; + assert_eq!(status, StatusCode::OK, "{answered}"); + assert_eq!(answered["messages"]["items"][0]["from"], "official"); + + let (_, _, waiting) = get(&fixture, citizen(CITIZEN), id).await; + assert_eq!(waiting["messages"]["unread"], 1, "{waiting}"); + assert_eq!(waiting["turn"], "party", "{waiting}"); + + let apply = json!({"submissionVersion":waiting["submissionVersion"],"effectDigest":waiting["effectDigest"]}); + let (_, etag, _) = get(&fixture, officer(), id).await; + let path = format!("/v1/proposals/{id}/apply"); + let (status, applied_headers, applied) = request( + &fixture, + officer(), + "POST", + &path, + etag.as_deref(), + Some("apply"), + apply.clone(), + ) + .await; + assert_eq!(status, StatusCode::OK, "{applied}"); + assert_eq!(applied["messages"]["items"][0]["text"], ANSWER); + let (status, replay_headers, replay) = request( + &fixture, + officer(), + "POST", + &path, + etag.as_deref(), + Some("apply"), + apply, + ) + .await; + assert_eq!(status, StatusCode::OK, "{replay}"); + assert_eq!(replay_headers["etag"], applied_headers["etag"]); + assert_eq!(replay, applied); + let (status, _, refused) = write( + &fixture, + citizen(CITIZEN), + "citizen", + id, + "One more thing", + "after-apply", + ) + .await; + assert_eq!(status, StatusCode::PRECONDITION_FAILED, "{refused}"); + assert_eq!(refused["code"], "precondition.failed"); + let (status, _, closed) = get(&fixture, citizen(CITIZEN), id).await; + assert_eq!(status, StatusCode::OK, "{closed}"); + assert_eq!(closed["messages"]["count"], 2, "{closed}"); + assert!( + closed["messages"]["links"]["message"] + .to_string() + .contains("already-applied"), + "{closed}" + ); + let (status, _, page) = request( + &fixture, + citizen(CITIZEN), + "GET", + &format!("/v1/proposals/{id}/messages?accessProfile=citizen"), + None, + None, + Value::Null, + ) + .await; + assert_eq!(status, StatusCode::OK, "{page}"); + assert_eq!(page["items"].as_array().unwrap().len(), 2, "{page}"); + fixture.finish().await; +} + +/// Thread activity never fences automatic application. A party message or +/// a mark-read that lands between the worker's read and its Apply leaves the +/// approved request applied, not refused and handed back to the party. +#[tokio::test] +async fn thread_activity_during_automatic_application_does_not_strand_the_request() { + for activity in ["party-message", "party-mark-read"] { + let fixture = fixture().await; + let id = filed( + &fixture, + citizen(CITIZEN), + "automatic-change", + CITIZEN, + activity, + ) + .await; + let mut through = None; + if activity == "party-mark-read" { + let (status, _, answered) = write( + &fixture, + officer(), + "office", + id, + ANSWER, + &format!("{activity}-office"), + ) + .await; + assert_eq!(status, StatusCode::OK, "{answered}"); + through = Some( + answered["messages"]["items"][0]["id"] + .as_str() + .unwrap() + .to_owned(), + ); + } + fixture + .database + .admin + .execute( + "UPDATE registry_internal.registry_proposal_application_jobs + SET next_attempt_at=transaction_timestamp()-interval '1 minute'", + &[], + ) + .await + .unwrap(); + let loaded = std::sync::Arc::new(tokio::sync::Notify::new()); + let resume = std::sync::Arc::new(tokio::sync::Notify::new()); + let worker = fixture + .mutations + .as_ref() + .clone() + .with_automatic_apply_barrier_for_test(loaded.clone(), resume.clone()); + let (attempt, ()) = tokio::join!(worker.run_automatic_proposal_once_for_test(), async { + tokio::time::timeout(std::time::Duration::from_secs(5), loaded.notified()) + .await + .expect("the worker reached Apply"); + match through.as_deref() { + None => { + let (status, _, written) = write( + &fixture, + citizen(CITIZEN), + "citizen", + id, + QUESTION, + &format!("{activity}-party"), + ) + .await; + assert_eq!(status, StatusCode::OK, "{written}"); + } + Some(through) => { + let (status, read) = + mark_read(&fixture, citizen(CITIZEN), "citizen", id, through).await; + assert!(status.is_success(), "{read}"); + } + } + resume.notify_one(); + }); + assert!(attempt.unwrap(), "{activity}: the worker claimed the job"); + let row = fixture + .database + .admin + .query_one( + "SELECT state,last_error_code FROM registry_internal.registry_proposal_application_jobs", + &[], + ) + .await + .unwrap(); + assert_eq!( + row.get::<_, String>(0), + "applied", + "{activity}: {:?}", + row.get::<_, Option>(1) + ); + let (status, _, applied) = get(&fixture, citizen(CITIZEN), id).await; + assert_eq!(status, StatusCode::OK, "{applied}"); + assert_eq!(applied["state"], "applied", "{activity}: {applied}"); + fixture.finish().await; + } +} + +#[tokio::test] +async fn an_action_without_messages_serves_no_thread() { + let fixture = fixture().await; + let id = filed(&fixture, citizen(CITIZEN), "quiet-change", CITIZEN, "quiet").await; + let (status, etag, document) = get(&fixture, citizen(CITIZEN), id).await; + assert_eq!(status, StatusCode::OK, "{document}"); + assert!(document.get("messages").is_none(), "{document}"); + for (method, path, etag, key, body) in [ + ( + "POST", + format!("/v1/proposals/{id}/messages?accessProfile=citizen"), + etag.as_deref(), + Some("quiet-writes"), + json!({"text": QUESTION}), + ), + ( + "GET", + format!("/v1/proposals/{id}/messages?accessProfile=citizen"), + None, + None, + Value::Null, + ), + ( + "POST", + format!("/v1/proposals/{id}/messages/read?accessProfile=citizen"), + None, + None, + json!({"through": Uuid::new_v4()}), + ), + ] { + let (status, _, value) = + request(&fixture, citizen(CITIZEN), method, &path, etag, key, body).await; + assert_eq!(status, StatusCode::NOT_FOUND, "{method} {path}: {value}"); + } + // The route exists for Actions that declare a thread, so the refusal + // above is the declaration's, not a missing route's. + let threaded = filed( + &fixture, + citizen(CITIZEN), + "record-change", + CITIZEN, + "threaded", + ) + .await; + let (status, _, value) = request( + &fixture, + citizen(CITIZEN), + "GET", + &format!("/v1/proposals/{threaded}/messages?accessProfile=citizen"), + None, + None, + Value::Null, + ) + .await; + assert_eq!(status, StatusCode::OK, "{value}"); + fixture.finish().await; +} + +/// Read and write take the human test, whatever the grant says. +#[tokio::test] +async fn only_a_person_acting_for_themselves_reads_or_writes_the_thread() { + let fixture = fixture().await; + let id = filed( + &fixture, + citizen(CITIZEN), + "apply-for-licence", + CITIZEN, + "people-only", + ) + .await; + let (status, _, written) = write( + &fixture, + citizen(CITIZEN), + "citizen", + id, + QUESTION, + "people-only-asks", + ) + .await; + assert_eq!(status, StatusCode::OK, "{written}"); + let relay = |kind| person("relay-canary", "licence:relay", kind); + + // A human under the any-kind profile is admitted. + let (status, context) = review_context( + &fixture, + relay(ActorKind::Human), + "relay", + id, + "&include=messages", + ) + .await; + assert_eq!(status, StatusCode::OK, "{context}"); + assert_eq!(context["context"]["messages"]["items"][0]["text"], QUESTION); + let link = context["context"]["messages"]["links"]["message"].clone(); + + // A service with the same grant neither reads nor writes. + let (status, context) = review_context( + &fixture, + relay(ActorKind::Service), + "relay", + id, + "&include=messages", + ) + .await; + assert!( + status != StatusCode::OK || context["context"].get("messages").is_none(), + "{context}" + ); + assert!(!context.to_string().contains(QUESTION), "{context}"); + let (status, _, refused) = request( + &fixture, + relay(ActorKind::Service), + "POST", + &format!("/v1/proposals/{id}/messages?accessProfile=relay"), + link["ifMatch"].as_str(), + Some("service-writes"), + json!({"text":"Automated"}), + ) + .await; + assert_eq!(status, StatusCode::FORBIDDEN, "{refused}"); + assert_eq!(refused["code"], "profile.not-authorized"); + let (status, _, page) = request( + &fixture, + relay(ActorKind::Service), + "GET", + &format!("/v1/proposals/{id}/messages?accessProfile=relay"), + None, + None, + Value::Null, + ) + .await; + assert_eq!(status, StatusCode::FORBIDDEN, "{page}"); + // An agent on the same profile, writing or marking read, is refused too. + let message = context_message_id(&fixture, id).await; + for (method, path, key, body) in [ + ( + "POST", + format!("/v1/proposals/{id}/messages?accessProfile=relay"), + Some("agent-writes"), + json!({"text":"Automated"}), + ), + ( + "POST", + format!("/v1/proposals/{id}/messages/read?accessProfile=relay"), + None, + json!({"through":message}), + ), + ( + "GET", + format!("/v1/proposals/{id}/messages?accessProfile=relay"), + None, + Value::Null, + ), + ] { + for kind in [ActorKind::Agent, ActorKind::Service] { + let (status, _, refused) = request( + &fixture, + relay(kind), + method, + &path, + link["ifMatch"].as_str(), + key, + body.clone(), + ) + .await; + assert_eq!( + status, + StatusCode::FORBIDDEN, + "{kind:?} {method} {path}: {refused}" + ); + assert!(!refused.to_string().contains(QUESTION), "{refused}"); + } + } + fixture.finish().await; +} + +/// The newest message's ID, read as the usual human reviewer. +async fn context_message_id(fixture: &client_http::ClientFixture, id: Uuid) -> String { + let (status, context) = + review_context(fixture, reviewer(), "reviewer", id, "&include=messages").await; + assert_eq!(status, StatusCode::OK, "{context}"); + context["context"]["messages"]["items"][0]["id"] + .as_str() + .unwrap() + .to_owned() +} + +#[tokio::test] +async fn the_thread_refuses_stale_writes_replays_keys_checks_text_and_stops_at_its_limit() { + let fixture = fixture().await; + let id = filed( + &fixture, + citizen(CITIZEN), + "apply-for-licence", + CITIZEN, + "limits", + ) + .await; + let (_, stale, _) = get(&fixture, citizen(CITIZEN), id).await; + let path = format!("/v1/proposals/{id}/messages?accessProfile=citizen"); + let (status, _, first) = request( + &fixture, + citizen(CITIZEN), + "POST", + &path, + stale.as_deref(), + Some("first"), + json!({ "text": QUESTION }), + ) + .await; + assert_eq!(status, StatusCode::OK, "{first}"); + + // A replayed key returns the stored response; a new key on the old + // ETag is refused. + let (status, _, replayed) = request( + &fixture, + citizen(CITIZEN), + "POST", + &path, + stale.as_deref(), + Some("first"), + json!({ "text": QUESTION }), + ) + .await; + assert_eq!(status, StatusCode::OK, "{replayed}"); + assert_eq!(replayed, first); + let (status, _, refused) = request( + &fixture, + citizen(CITIZEN), + "POST", + &path, + stale.as_deref(), + Some("second-on-stale"), + json!({"text":"Stale"}), + ) + .await; + assert_eq!(status, StatusCode::PRECONDITION_FAILED, "{refused}"); + assert_eq!(refused["code"], "precondition.failed"); + + // Every write names its condition and its key, and a key is bound to its + // request. + let (_, current, _) = get(&fixture, citizen(CITIZEN), id).await; + for (etag, key, text, status, code) in [ + ( + None, + Some("no-condition"), + "Unconditioned", + StatusCode::PRECONDITION_REQUIRED, + "precondition.required", + ), + ( + current.as_deref(), + None, + "Unkeyed", + StatusCode::BAD_REQUEST, + "request.invalid", + ), + ( + current.as_deref(), + Some("first"), + "Changed body", + StatusCode::CONFLICT, + "idempotency.key-reused", + ), + ] { + let (actual, _, refused) = request( + &fixture, + citizen(CITIZEN), + "POST", + &path, + etag, + key, + json!({ "text": text }), + ) + .await; + assert_eq!(actual, status, "{text}: {refused}"); + assert_eq!(refused["code"], code, "{text}: {refused}"); + } + + for (text, key) in [ + (String::new(), "empty"), + ("a".repeat(2001), "too-long"), + ("Bell \u{0007}".to_owned(), "control"), + ("Reordered \u{202E}txet".to_owned(), "reordering"), + ("\u{200B}\u{200C}\u{FEFF}".to_owned(), "invisible-only"), + ( + "Hidden \u{E0041}\u{E0042} tags".to_owned(), + "tag-characters", + ), + ("Joined\u{2060}word".to_owned(), "word-joiner"), + ("Line\u{2028}separator".to_owned(), "line-separator"), + ("Lone\rreturn".to_owned(), "lone-return"), + ] { + let (status, _, refused) = + write(&fixture, citizen(CITIZEN), "citizen", id, &text, key).await; + assert_eq!(status, StatusCode::BAD_REQUEST, "{key}: {refused}"); + assert_eq!(refused["code"], "request.invalid", "{key}"); + assert_eq!(refused["fieldPath"], "/text", "{key}: {refused}"); + } + + // Markup is stored and returned byte for byte; 2,000 bytes fit. + let markup = "bold & "; + let (status, _, stored) = + write(&fixture, citizen(CITIZEN), "citizen", id, markup, "markup").await; + assert_eq!(status, StatusCode::OK, "{stored}"); + assert_eq!(stored["messages"]["items"][0]["text"], markup); + let full = "\u{e9}".repeat(1000); + let (status, _, value) = write(&fixture, citizen(CITIZEN), "citizen", id, &full, "full").await; + assert_eq!(status, StatusCode::OK, "{value}"); + // A form post's line breaks arrive as CRLF and are kept. + let crlf = "Line one\r\nLine two"; + let (status, _, value) = write(&fixture, citizen(CITIZEN), "citizen", id, crlf, "four").await; + assert_eq!(status, StatusCode::OK, "{value}"); + assert_eq!(value["messages"]["items"][0]["text"], crlf); + + // The Action allows four messages from each side. + let (status, _, limited) = + write(&fixture, citizen(CITIZEN), "citizen", id, "Five", "five").await; + assert_eq!(status, StatusCode::CONFLICT, "{limited}"); + assert_eq!(limited["code"], "proposal.message-limit-reached"); + let (_, _, document) = get(&fixture, citizen(CITIZEN), id).await; + assert_eq!(document["messages"]["count"], 4, "{document}"); + assert!( + document["messages"]["links"]["message"] + .to_string() + .contains("limit-reached"), + "{document}" + ); + // A full party side leaves the office its own share. + let (status, context) = + review_context(&fixture, reviewer(), "reviewer", id, "&include=messages").await; + assert_eq!(status, StatusCode::OK, "{context}"); + let link = &context["context"]["messages"]["links"]["message"]; + assert_eq!(link["availability"]["available"], true, "{context}"); + let (status, _, answered) = request( + &fixture, + reviewer(), + "POST", + &format!("/v1/proposals/{id}/messages?accessProfile=reviewer"), + link["ifMatch"].as_str(), + Some("office-after-party-limit"), + json!({ "text": ANSWER }), + ) + .await; + assert_eq!(status, StatusCode::OK, "{answered}"); + assert_eq!(answered["context"]["messages"]["count"], 5, "{answered}"); + fixture.finish().await; +} + +/// The thread belongs to the Proposal, not to a review round. +#[tokio::test] +async fn the_thread_stays_open_across_revise_and_the_next_round_reads_all_of_it() { + let fixture = fixture().await; + let id = filed( + &fixture, + citizen(CITIZEN), + "apply-for-licence", + CITIZEN, + "rounds", + ) + .await; + let (status, _, value) = write( + &fixture, + citizen(CITIZEN), + "citizen", + id, + "Round one question", + "round-one", + ) + .await; + assert_eq!(status, StatusCode::OK, "{value}"); + request_changes(&fixture, id).await; + let (status, revised) = command( + &fixture, + citizen(CITIZEN), + id, + "revise", + "revise", + json!({"input":{"holder":CITIZEN,"statement":"Revised"}}), + ) + .await; + assert_eq!(status, StatusCode::OK, "{revised}"); + let (status, _, value) = write( + &fixture, + citizen(CITIZEN), + "citizen", + id, + "What exactly is wrong?", + "between-rounds", + ) + .await; + assert_eq!(status, StatusCode::OK, "{value}"); + let (status, value) = command( + &fixture, + citizen(CITIZEN), + id, + "submit", + "resubmit", + json!({}), + ) + .await; + assert_eq!(status, StatusCode::OK, "{value}"); + let (status, context) = + review_context(&fixture, reviewer(), "reviewer", id, "&include=messages").await; + assert_eq!(status, StatusCode::OK, "{context}"); + assert_eq!(context["submissionVersion"], 2, "{context}"); + let texts = context["context"]["messages"]["items"] + .as_array() + .unwrap() + .iter() + .map(|item| item["text"].as_str().unwrap().to_owned()) + .collect::>(); + assert_eq!( + texts, + ["What exactly is wrong?", "Round one question"], + "{context}" + ); + let before: i64 = fixture + .database + .admin + .query_one( + "SELECT count(*) FROM registry_internal.registry_idempotency r + JOIN registry_internal.registry_proposal_idempotency_links l USING(key_reference) + WHERE l.proposal_id=$1 AND l.submission_version=2 + AND position('Round one question' in convert_from(r.response_body,'UTF8')) > 0", + &[&id], + ) + .await + .unwrap() + .get(0); + assert!(before > 0); + let (mut client, task) = fixture.database.connect_migration().await; + let erased = registry_breg::proposal_retention::erase_proposal_detail( + &mut client, + &fixture.registry, + registry_breg::proposal_retention::ProposalDetailErasureScope { + action_id: "apply-for-licence", + proposal_id: id, + submission_version: 1, + }, + ) + .await + .unwrap(); + assert_eq!(erased.messages, 1); + let row = fixture + .database + .admin + .query_one( + "SELECT + (SELECT count(*) FROM registry_internal.registry_proposal_messages + WHERE proposal_id=$1 AND submission_version=1 AND text IS NULL AND sent_by IS NULL + AND detail_erased_at IS NOT NULL), + (SELECT count(*) FROM registry_internal.registry_proposal_messages + WHERE proposal_id=$1 AND submission_version=2 AND text='What exactly is wrong?'), + (SELECT count(*) FROM registry_internal.registry_idempotency r + JOIN registry_internal.registry_proposal_idempotency_links l USING(key_reference) + WHERE l.proposal_id=$1 AND l.submission_version=2 + AND position('Round one question' in convert_from(r.response_body,'UTF8')) > 0)", + &[&id], + ) + .await + .unwrap(); + assert_eq!(row.get::<_, i64>(0), 1); + assert_eq!(row.get::<_, i64>(1), 1); + assert_eq!(row.get::<_, i64>(2), 0); + drop(client); + task.abort(); + let (status, context) = + review_context(&fixture, reviewer(), "reviewer", id, "&include=messages").await; + assert_eq!(status, StatusCode::OK, "{context}"); + let items = context["context"]["messages"]["items"].as_array().unwrap(); + assert_eq!(items.len(), 2, "{context}"); + assert_eq!(items[0]["text"], "What exactly is wrong?"); + assert_eq!(items[1]["from"], "party"); + assert!(items[1].get("text").is_none(), "{context}"); + fixture.finish().await; +} + +/// The thread opens at the first Submit and closes for writes when the +/// Proposal is cancelled or rejected, as it does when it is applied. +#[tokio::test] +async fn the_thread_is_closed_before_the_first_submit_and_after_cancel_or_rejection() { + let fixture = fixture().await; + let draft = start( + &fixture, + citizen(CITIZEN), + "apply-for-licence", + json!({"holder":CITIZEN,"statement":"Draft"}), + "unsubmitted-start", + ) + .await; + let (status, _, refused) = write( + &fixture, + citizen(CITIZEN), + "citizen", + draft, + QUESTION, + "before-submit", + ) + .await; + assert_eq!(status, StatusCode::PRECONDITION_FAILED, "{refused}"); + assert_eq!(refused["code"], "precondition.failed"); + + let cancelled = filed( + &fixture, + citizen(CITIZEN), + "apply-for-licence", + CITIZEN, + "to-cancel", + ) + .await; + let (status, value) = command( + &fixture, + citizen(CITIZEN), + cancelled, + "cancel", + "cancel", + json!({}), + ) + .await; + assert_eq!(status, StatusCode::OK, "{value}"); + let (status, _, refused) = write( + &fixture, + citizen(CITIZEN), + "citizen", + cancelled, + QUESTION, + "after-cancel", + ) + .await; + assert_eq!(status, StatusCode::PRECONDITION_FAILED, "{refused}"); + assert_eq!(refused["code"], "precondition.failed"); + + let rejected = filed( + &fixture, + citizen(CITIZEN), + "apply-for-licence", + CITIZEN, + "to-reject", + ) + .await; + decide(&fixture, rejected, "rejected").await; + let (status, _, refused) = write( + &fixture, + citizen(CITIZEN), + "citizen", + rejected, + QUESTION, + "after-rejection", + ) + .await; + assert_eq!(status, StatusCode::CONFLICT, "{refused}"); + assert_eq!(refused["code"], "proposal.rejected"); + let count: i64 = fixture + .database + .admin + .query_one( + "SELECT count(*) FROM registry_internal.registry_proposal_messages", + &[], + ) + .await + .unwrap() + .get(0); + assert_eq!(count, 0); + fixture.finish().await; +} + +/// A reviewer who holds the thread but not Get can still reply between +/// review rounds, when no review context is readable: the first page of the +/// thread carries its links, and the write answers with the thread alone. +#[tokio::test] +async fn a_reviewer_without_get_replies_between_rounds_from_the_thread_alone() { + let fixture = fixture().await; + let id = filed( + &fixture, + citizen(CITIZEN), + "apply-for-licence", + CITIZEN, + "between", + ) + .await; + request_changes(&fixture, id).await; + let (status, revised) = command( + &fixture, + citizen(CITIZEN), + id, + "revise", + "between-revise", + json!({"input":{"holder":CITIZEN,"statement":"Revised"}}), + ) + .await; + assert_eq!(status, StatusCode::OK, "{revised}"); + let (status, _, asked) = write( + &fixture, + citizen(CITIZEN), + "citizen", + id, + "What exactly is wrong?", + "between-asks", + ) + .await; + assert_eq!(status, StatusCode::OK, "{asked}"); + let (status, context) = + review_context(&fixture, reviewer(), "reviewer", id, "&include=messages").await; + assert_ne!(status, StatusCode::OK, "{context}"); + + let (status, _, page) = request( + &fixture, + reviewer(), + "GET", + &format!("/v1/proposals/{id}/messages?accessProfile=reviewer"), + None, + None, + Value::Null, + ) + .await; + assert_eq!(status, StatusCode::OK, "{page}"); + assert_eq!(page["items"][0]["text"], "What exactly is wrong?", "{page}"); + let link = page["links"]["message"].clone(); + assert_eq!(link["availability"]["available"], true, "{page}"); + let (status, _, replied) = request( + &fixture, + reviewer(), + "POST", + &format!("/v1/proposals/{id}/messages?accessProfile=reviewer"), + link["ifMatch"].as_str(), + Some("between-reply"), + json!({ "text": ANSWER }), + ) + .await; + assert_eq!(status, StatusCode::OK, "{replied}"); + assert_eq!(replied["items"][0]["text"], ANSWER, "{replied}"); + assert_eq!(replied["items"][0]["from"], "official", "{replied}"); + assert_eq!(replied["count"], 2, "{replied}"); + assert!(replied.get("context").is_none(), "{replied}"); + + let question = page["items"][0]["id"].as_str().unwrap(); + let (status, read) = mark_read(&fixture, reviewer(), "reviewer", id, question).await; + assert_eq!(status, StatusCode::OK, "{read}"); + assert_eq!(read["unread"], 0, "{read}"); + + let (_, _, waiting) = get(&fixture, citizen(CITIZEN), id).await; + assert_eq!(waiting["messages"]["items"][0]["text"], ANSWER, "{waiting}"); + fixture.finish().await; +} + +/// Office staff whose grant does not reach a Proposal learn nothing about +/// it from a thread route, however malformed the request. +#[tokio::test] +async fn bounded_office_staff_get_the_same_answer_for_a_hidden_proposal_and_an_unknown_one() { + let mut source = source(); + let mut bounded = source["accessProfiles"]["reviewer"].clone(); + bounded["requiredScopes"] = json!(["licence:district"]); + bounded["permissions"]["proposals"][0]["targets"] = json!([{"recordType":"licence", + "rowBoundaries":[{"field":"holder","claim":"holder_scope","operator":"equals"}]}]); + source["accessProfiles"]["district"] = bounded; + let fixture = client_http::ClientFixture::start_with_mutations( + compile(&source), + officer(), + |mutations| { + mutations.with_proposal_review_substitute_for_test( + local_review(), + std::sync::Arc::new(NoResult), + ) + }, + ) + .await; + let id = filed( + &fixture, + citizen(CITIZEN), + "apply-for-licence", + CITIZEN, + "hidden", + ) + .await; + let district = |scope: &str| { + VerifiedRequestClaims::authenticated_with_actor_kind( + "sub", + "district-officer", + BTreeSet::from(["licence:district".to_owned()]), + Some("licence-portal".into()), + BTreeMap::from([( + "holder_scope".to_owned(), + registry_breg::api::VerifiedClaimValue::direct_string(scope).unwrap(), + )]), + ActorKind::Human, + ) + .unwrap() + }; + let (status, _, page) = request( + &fixture, + district(CITIZEN), + "GET", + &format!("/v1/proposals/{id}/messages?accessProfile=district"), + None, + None, + Value::Null, + ) + .await; + assert_eq!( + status, + StatusCode::OK, + "the district that holds it reads it: {page}" + ); + let unknown = Uuid::new_v4(); + for target in [id, unknown] { + for (method, path, etag, key, body) in [ + ( + "POST", + format!("/v1/proposals/{target}/messages?accessProfile=district"), + None, + Some("hidden-write"), + json!({"text":QUESTION}), + ), + ( + "POST", + format!("/v1/proposals/{target}/messages?accessProfile=district"), + Some("\"stale\""), + None, + json!({"text":QUESTION}), + ), + ( + "POST", + format!("/v1/proposals/{target}/messages?accessProfile=district"), + Some("\"stale\""), + Some("hidden-text"), + json!({"text":""}), + ), + ( + "GET", + format!("/v1/proposals/{target}/messages?accessProfile=district&after=0"), + None, + None, + Value::Null, + ), + ( + "GET", + format!("/v1/proposals/{target}/messages?accessProfile=district&limit=0"), + None, + 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"), + None, + None, + json!({"through":"not-a-message"}), + ), + ] { + let (status, _, refused) = request( + &fixture, + district("elsewhere"), + method, + &path, + etag, + key, + body, + ) + .await; + assert_eq!(status, StatusCode::NOT_FOUND, "{method} {path}: {refused}"); + assert_eq!( + refused["code"], "resource.not-found", + "{method} {path}: {refused}" + ); + } + } + fixture.finish().await; +} diff --git a/crates/registry-breg/tests/postgres_proposal_recovery_permissions.rs b/crates/registry-breg/tests/postgres_proposal_recovery_permissions.rs index 8461c30e35..fd51988a42 100644 --- a/crates/registry-breg/tests/postgres_proposal_recovery_permissions.rs +++ b/crates/registry-breg/tests/postgres_proposal_recovery_permissions.rs @@ -109,7 +109,7 @@ fn registry_source() -> Value { "proposals":[{ "action":"correct-name", "operations":["get","list","edit","submit","revise","rebase","retry","cancel","apply"], - "ownership":"caller","readableInputs":["target","value"], + "party":"owner","readableInputs":["target","value"], "targets":[{ "recordType":"target", "rowBoundaries":[{"field":"jurisdiction","claim":"jurisdiction","operator":"equals"}] diff --git a/crates/registry-breg/tests/postgres_proposal_review_delivery.rs b/crates/registry-breg/tests/postgres_proposal_review_delivery.rs index 1b35c0c96b..476ce5819a 100644 --- a/crates/registry-breg/tests/postgres_proposal_review_delivery.rs +++ b/crates/registry-breg/tests/postgres_proposal_review_delivery.rs @@ -440,7 +440,7 @@ fn registry_source(selection: Value) -> Value { "accessProfiles":{"clerk": {"default":true,"principalClaim":"sub","requiredScopes":["proposal:manage"],"requiredPurposes":["registry-administration"],"permissions":{ "records":[{"recordType":"target","operations":["create","get","list"],"readableFields":["name","jurisdiction"],"writableFields":["name","jurisdiction"],"rowBoundaries":[{"field":"jurisdiction","claim":"jurisdiction","operator":"equals"}]}], "actions":[{"action":"correct-name","operations":["start"],"targets":[{"recordType":"target","rowBoundaries":[{"field":"jurisdiction","claim":"jurisdiction","operator":"equals"}]}]}], - "proposals":[{"action":"correct-name","operations":["get","list","submit","cancel","get-review-status"],"ownership":"caller","targets":[{"recordType":"target","rowBoundaries":[{"field":"jurisdiction","claim":"jurisdiction","operator":"equals"}]}]}]}}}}) + "proposals":[{"action":"correct-name","operations":["get","list","submit","cancel","get-review-status"],"party":"owner","targets":[{"recordType":"target","rowBoundaries":[{"field":"jurisdiction","claim":"jurisdiction","operator":"equals"}]}]}]}}}}) } async fn fixture(authority: &Authority) -> client_http::ClientFixture { let bindings = authority.registry.clone(); diff --git a/crates/registry-breg/tests/postgres_proposal_s3.rs b/crates/registry-breg/tests/postgres_proposal_s3.rs index 8716d0b9c1..9e2c007507 100644 --- a/crates/registry-breg/tests/postgres_proposal_s3.rs +++ b/crates/registry-breg/tests/postgres_proposal_s3.rs @@ -82,7 +82,7 @@ fn registry_source(automatic: bool) -> Value { "actions":[{"action":"correct-name","operations":["start"],"targets":[{"recordType":"target", "rowBoundaries":[{"field":"jurisdiction","claim":"jurisdiction","operator":"equals"}]}]}], "proposals":[{"action":"correct-name","operations":["get","list","edit","submit","revise","rebase","retry","cancel","apply"], - "ownership":"caller","readableInputs":["target","value"],"readableAttachments":["support"],"writableAttachments":["support"],"targets":[{"recordType":"target", + "party":"owner","readableInputs":["target","value"],"readableAttachments":["support"],"writableAttachments":["support"],"targets":[{"recordType":"target", "rowBoundaries":[{"field":"jurisdiction","claim":"jurisdiction","operator":"equals"}]}]}]}}}}); source } diff --git a/crates/registry-breg/tests/postgres_proposal_security.rs b/crates/registry-breg/tests/postgres_proposal_security.rs index 8446fbf8aa..5374a27495 100644 --- a/crates/registry-breg/tests/postgres_proposal_security.rs +++ b/crates/registry-breg/tests/postgres_proposal_security.rs @@ -37,10 +37,12 @@ fn source(membership: bool) -> Value { let mut reader = json!({"recordType":"target","operations":["get","list"],"readableFields":["name"], "rowBoundaries":[{"field":"jurisdiction","claim":"recordJurisdiction","operator":"equals"}]}); if membership { - reader["membershipBoundaries"] = json!([{"field":"organization","membershipRecordType":"membership", - "membershipKeyField":"organization","principalField":"principal","activeField":"active"}]); + reader["rowBoundaries"] + .as_array_mut() + .unwrap() + .push(json!({"field":"organization","membership":"membership"})); } - let source = json!({"apiVersion":"id.registrystack.org/formats/breg/project/v1alpha1","kind":"BRegProject", + let mut source = json!({"apiVersion":"id.registrystack.org/formats/breg/project/v1alpha1","kind":"BRegProject", "project":{"id":"proposal-security","version":"1","defaultLanguage":"en","canonicalBaseIri":"https://proposal.example.test"}, "datasets":{"directory": {}},"recordTypes":{ "organization": {"primaryDataset":"directory","route":"organizations","mutationMode":"mutable", @@ -69,16 +71,40 @@ fn source(membership: bool) -> Value { {"recordType":"target","operations":["create","get"],"readableFields":["name","jurisdiction","organization"], "writableFields":["name","jurisdiction","organization"],"rowBoundaries":boundary}], "actions":[{"action":"correct-name","operations":["start"],"targets":targets}], - "proposals":[{"action":"correct-name","operations":["get","edit","submit","cancel"],"ownership":"caller","readableInputs":["target","value"],"targets":targets}]}}, + "proposals":[{"action":"correct-name","operations":["get","edit","submit","cancel"],"party":"owner","readableInputs":["target","value"],"targets":targets}]}}, "task-reviewer": {"principalClaim":"registry_principal","actorKind":"agent","requesterClients":["agent-client"], "requiredScopes":["proposal:manage"],"requiredPurposes":["registry-administration"], "taskGrant":{"sourceIssuer":"https://casework.example"},"permissions":{"records":[reader], "actions":[{"action":"correct-name","operations":["start"],"targets":targets}], "proposals":[{"action":"correct-name","operations":["get","edit","submit","get-review-context"], - "ownership":"caller","readableInputs":["target","value"],"readableContextFields":["currentName","proposedName"],"targets":targets}]}}}}); + "party":"owner","readableInputs":["target","value"],"readableContextFields":["currentName","proposedName"],"targets":targets}]}}}}); + if membership { + source["recordTypes"]["membership"]["membership"] = + json!({"key":"organization","principal":"principal","active":"active"}); + separate_membership_admin(&mut source); + } source } +/// A profile bounded through `membership` cannot also write it, so a +/// separate administrator with the same token keeps the membership rows, and +/// reads the organisations a row may name. +fn separate_membership_admin(source: &mut Value) { + let records = source["accessProfiles"]["clerk"]["permissions"]["records"] + .as_array_mut() + .unwrap(); + let position = records + .iter() + .position(|grant| grant["recordType"] == "membership") + .unwrap(); + let grant = records.remove(position); + source["accessProfiles"]["membership-admin"] = json!({ + "principalClaim":"registry_principal","requiredScopes":["proposal:manage"], + "requiredPurposes":["registry-administration"],"permissions":{"records":[grant, + {"recordType":"organization","operations":["get"],"readableFields":[],"rowBoundaries":"unrestricted"}]} + }); +} + fn compile(source: Value) -> registry_breg::CompiledRegistry { compile_project( &parse_project_json(&serde_json::to_vec(&source).unwrap()).unwrap(), @@ -106,6 +132,21 @@ fn clerk() -> VerifiedRequestClaims { .unwrap() } +fn human_clerk() -> VerifiedRequestClaims { + VerifiedRequestClaims::authenticated_with_actor_kind( + "registry_principal", + "author", + BTreeSet::from(["proposal:manage".into()]), + Some("registry-administration".into()), + BTreeMap::from([( + "jurisdiction".into(), + VerifiedClaimValue::direct_string("zone-a").unwrap(), + )]), + registry_platform_oidc::ActorKind::Human, + ) + .unwrap() +} + struct Status { active: AtomicBool, calls: AtomicUsize, @@ -189,11 +230,24 @@ async fn send( (status, response.json().await.unwrap(), etag) } +/// Membership rows are written by their administrator, everything else by +/// the clerk. +fn record_profile(route: &str) -> &'static str { + if route == "memberships" { + "membership-admin" + } else { + "clerk" + } +} + async fn create(http: &client_http::ClientHttp, route: &str, data: Value, key: &str) -> String { let (status, value, _) = send( http, Method::POST, - &format!("/v1/records/{route}?accessProfile=clerk"), + &format!( + "/v1/records/{route}?accessProfile={}", + record_profile(route) + ), json!({"data":data}), Some(key), None, @@ -221,6 +275,25 @@ async fn seed(fixture: &client_http::ClientFixture) -> (String, String) { (organization, target) } +async fn set_membership_active(http: &client_http::ClientHttp, membership: &str, active: bool) { + let path = format!("/v1/records/memberships/{membership}?accessProfile=membership-admin"); + let (code, _, etag) = send(http, Method::GET, &path, Value::Null, None, None).await; + assert_eq!(code, StatusCode::OK); + let response = reqwest::Client::new() + .patch(format!("{}{path}", http.base_url)) + .header("content-type", "application/json-patch+json") + .header("if-match", etag.unwrap()) + .header( + "idempotency-key", + format!("membership-{membership}-{active}"), + ) + .json(&json!([{"op":"replace","path":"/data/active","value":active}])) + .send() + .await + .unwrap(); + assert_eq!(response.status(), StatusCode::OK); +} + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn signed_proposal_start_and_lifecycle_receipts_reject_sibling_grants() { let status = Arc::new(Status { @@ -1160,7 +1233,7 @@ async fn explicit_service_assessment_preserves_scope_actor_target_and_record_dis service["permissions"]["proposals"][0] .as_object_mut() .unwrap() - .remove("ownership"); + .remove("party"); let mut human = service.clone(); human["actorKind"] = json!("human"); let mut narrow = service.clone(); @@ -1887,9 +1960,9 @@ async fn applicant_progress_rechecks_withdrawal_and_audit_before_release() { #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn review_status_service_reads_only_its_exact_frozen_review_binding() { - let mut source = source(false); - let proposal_targets = - source["accessProfiles"]["clerk"]["permissions"]["proposals"][0]["targets"].clone(); + let mut source = source(true); + source["actions"]["correct-name"]["execution"]["proposal"]["reviewContext"]["fields"] + ["changes"] = json!({"type":"changes","recordType":"target","fields":["name"]}); source["accessProfiles"]["clerk"]["permissions"]["proposals"][0]["operations"] = json!([ "get", "edit", @@ -1899,7 +1972,7 @@ async fn review_status_service_reads_only_its_exact_frozen_review_binding() { "get-review-context" ]); source["accessProfiles"]["clerk"]["permissions"]["proposals"][0]["readableContextFields"] = - json!(["currentName", "proposedName"]); + json!(["changes", "currentName", "proposedName"]); source["reviewAuthorities"] = json!({"casework": {"protocol":"id.registrystack.org/protocols/review/v1"}}); source["actions"]["correct-name"]["execution"]["proposal"]["review"] = json!({"type":"required","authority":"casework","source":"proposal-security", @@ -1910,15 +1983,18 @@ async fn review_status_service_reads_only_its_exact_frozen_review_binding() { "reviewAuthority":"casework","operations":["get-review-status"]}]}})); source["accessProfiles"].as_object_mut().unwrap().insert("task-context".to_owned(), json!({"principalClaim":"registry_principal", "actorKind":"service","requesterClients":["agent-client"],"requiredScopes":["proposal:task-context"], - "requiredPurposes":["registry-administration"],"permissions":{"proposals":[{"action":"correct-name", - "operations":["get","get-task-grant-context"],"ownership":"caller", - "readableContextFields":["proposedName"],"targets":proposal_targets}]}})); + "requiredPurposes":["registry-administration"],"permissions":{"records":[{ + "recordType":"target","operations":["get"],"readableFields":["name"],"rowBoundaries":"unrestricted" + }],"proposals":[{"action":"correct-name", + "operations":["get","get-task-grant-context"],"party":"owner", + "readableContextFields":["changes","currentName","proposedName"], + "targets":[{"recordType":"target","rowBoundaries":[{"field":"organization","membership":"membership"}]}]}]}})); let fixture = client_http::ClientFixture::start_with_mutations(compile(source), clerk(), |service| { service.with_review_result_source(review_binding()) }) .await; - let (_, target) = seed(&fixture).await; + let (organization, target) = seed(&fixture).await; let (code, draft, etag) = send( &fixture.http, Method::POST, @@ -2098,11 +2174,11 @@ async fn review_status_service_reads_only_its_exact_frozen_review_binding() { fixture.database.admin.execute("UPDATE registry_internal.registry_proposal_review_submissions SET authority='casework',create_request=$1,expected_policy=$2,expected_submission_digest=$3", &[&stored,&policy,&digest]).await.unwrap(); } - let create: registry_review_client::ReviewCreateRequest = + let create_request: registry_review_client::ReviewCreateRequest = serde_json::from_value(stored).unwrap(); let accepted = registry_review_client::ReviewRequestAccepted { request_id: uuid::Uuid::new_v4(), - subject: create.subject, + subject: create_request.subject, policy: serde_json::from_value(policy).unwrap(), submission_digest: registry_review_client::SubmissionDigest::parse(&digest).unwrap(), }; @@ -2128,6 +2204,13 @@ async fn review_status_service_reads_only_its_exact_frozen_review_binding() { let task_binding = metadata .select_proposal_task_grant_context("task-context", "correct-name") .unwrap(); + let membership = create( + &fixture.http, + "memberships", + json!({"organization":organization,"principal":"review-service","active":true}), + "task-context-membership", + ) + .await; let typed_task_request: registry_breg_client::BRegProposalTaskContextRequest = serde_json::from_value(task_request.clone()).unwrap(); let task_document = task_service @@ -2141,6 +2224,63 @@ async fn review_status_service_reads_only_its_exact_frozen_review_binding() { task_document.proposal.context.fields.unwrap(), BTreeMap::from([("proposedName".into(), json!("Proposed"))]) ); + let record_path = format!("/v1/records/targets/{target}?accessProfile=task-context"); + let context_fields = [ + ("currentName", json!("current-name-canary")), + ( + "changes", + json!([{"recordId":target,"operation":"patch", + "before":{"name":"current-name-canary"},"after":{"name":"Proposed"}}]), + ), + ]; + for (field, expected_value) in &context_fields { + let mut selected = task_request.clone(); + selected["fields"] = json!([field]); + let selected = serde_json::from_value(selected).unwrap(); + let document = task_service + .client + .read_proposal_task_grant_context(&task_binding, &selected) + .await + .unwrap() + .value; + assert_eq!(document.request, selected); + assert_eq!( + document.proposal.context.fields.unwrap(), + BTreeMap::from([(field.to_string(), expected_value.clone())]) + ); + } + set_membership_active(&fixture.http, &membership, false).await; + assert_eq!( + send( + &task_service, + Method::GET, + &record_path, + Value::Null, + None, + None + ) + .await + .0, + StatusCode::OK, + "the ordinary Record grant is independent of the Proposal target scope" + ); + for (field, _) in context_fields { + let mut selected = task_request.clone(); + selected["fields"] = json!([field]); + let (code, problem, _) = send( + &task_service, + Method::POST, + &task_path, + selected, + None, + None, + ) + .await; + assert_eq!(code, StatusCode::NOT_FOUND); + assert_eq!(problem["code"], "resource.not-found"); + assert!(problem.get("proposal").is_none()); + } + set_membership_active(&fixture.http, &membership, true).await; let mut substituted_request = task_request.clone(); substituted_request["requestId"] = json!(uuid::Uuid::new_v4()); let (code, value, _) = send( @@ -2647,6 +2787,734 @@ async fn frozen_changes_inspection_covers_patch_and_create_without_applying_or_r fixture.finish().await; } +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn review_context_checks_each_frozen_membership_and_saved_document() { + let mut project = source(true); + let profiles = project["accessProfiles"].as_object_mut().unwrap(); + profiles.remove("task-reviewer"); + let clerk_permissions = &mut profiles.get_mut("clerk").unwrap()["permissions"]; + clerk_permissions["actions"][0]["targets"] + .as_array_mut() + .unwrap() + .push(json!({"recordType":"organization","rowBoundaries":"unrestricted"})); + clerk_permissions["proposals"][0]["targets"] + .as_array_mut() + .unwrap() + .push(json!({"recordType":"organization","rowBoundaries":"unrestricted"})); + clerk_permissions["proposals"][0]["operations"] + .as_array_mut() + .unwrap() + .push(json!("apply")); + clerk_permissions["proposals"][0]["readableInputs"] + .as_array_mut() + .unwrap() + .push(json!("destination")); + clerk_permissions["proposals"][0]["writableAttachments"] = json!(["support"]); + profiles.insert("member-review".into(), json!({ + "principalClaim":"registry_principal","actorKind":"human", + "requiredScopes":["proposal:manage"],"requiredPurposes":["registry-administration"], + "permissions":{ + "records":[{"recordType":"target","operations":["get"], + "readableFields":["name"],"rowBoundaries":"unrestricted"}], + "proposals":[{"action":"correct-name","operations":["get-review-context"], + "readableContextFields":["changes","currentName","document"],"targets":[ + {"recordType":"target","rowBoundaries":[{"field":"organization","membership":"membership"}]}, + {"recordType":"organization","rowBoundaries":"unrestricted"} + ]}] + } + })); + let action = &mut project["actions"]["correct-name"]; + action["inputs"].as_array_mut().unwrap().push(json!({ + "id":"destination","type":"reference","target":"organization","required":true, + "classification":"internal" + })); + action["plan"]["effects"][0]["set"]["organization"] = json!({"fromInput":"destination"}); + let proposal = &mut action["execution"]["proposal"]; + proposal["attachments"] = json!([ + {"id":"support","required":false,"maximumBytes":64,"contentTypes":["text/plain"],"classification":"restricted"} + ]); + proposal["reviewContext"]["fields"] = json!({ + "changes":{"type":"changes","recordType":"target","fields":["name"]}, + "currentName":{"type":"record","input":"target","field":"name"}, + "document":{"type":"document","slot":"support"} + }); + let fixture = client_http::ClientFixture::start(compile(project), human_clerk()).await; + let (origin, target) = seed(&fixture).await; + let destination = create( + &fixture.http, + "organizations", + json!({"name":"Destination"}), + "destination", + ) + .await; + let original_membership = create( + &fixture.http, + "memberships", + json!({"organization":origin,"principal":"author","active":true}), + "original-membership", + ) + .await; + let destination_membership = create( + &fixture.http, + "memberships", + json!({"organization":destination,"principal":"author","active":true}), + "destination-membership", + ) + .await; + let (status, draft, etag) = send( + &fixture.http, + Method::POST, + "/v1/actions/correct-name/proposals?accessProfile=clerk", + json!({"input":{"target":target,"value":"Proposed","destination":destination}}), + Some("start-move"), + None, + ) + .await; + assert_eq!(status, StatusCode::CREATED); + let id = draft["id"].as_str().unwrap(); + let support = format!("/v1/proposals/{id}/attachments/support?accessProfile=clerk"); + let response = reqwest::Client::new() + .patch(format!("{}{support}", fixture.http.base_url)) + .header("content-type", "text/plain") + .header("if-match", etag.unwrap()) + .header("idempotency-key", "move-document") + .body("Synthetic review document") + .send() + .await + .unwrap(); + assert_eq!(response.status(), StatusCode::OK); + let (status, submitted, etag) = send( + &fixture.http, + Method::POST, + &format!("/v1/proposals/{id}/submit?accessProfile=clerk"), + json!({}), + Some("submit-move"), + response.headers()["etag"].to_str().ok(), + ) + .await; + assert_eq!(status, StatusCode::OK); + + let scalar = format!("/v1/proposals/{id}/review-context?accessProfile=member-review"); + let batch = format!("/v1/proposals/review-context?accessProfile=member-review&ids={id}"); + let (status, context, _) = + send(&fixture.http, Method::GET, &scalar, Value::Null, None, None).await; + assert_eq!(status, StatusCode::OK); + assert_eq!(context["effectDigest"], submitted["effectDigest"]); + assert_eq!( + context["context"]["fields"]["currentName"], + "current-name-canary" + ); + assert_eq!( + context["context"]["fields"]["changes"], + json!([{ + "recordId":target,"operation":"patch","before":{"name":"current-name-canary"},"after":{"name":"Proposed"} + }]) + ); + let (status, page, _) = send(&fixture.http, Method::GET, &batch, Value::Null, None, None).await; + assert_eq!(status, StatusCode::OK); + assert_eq!( + page, + json!({"items":[{"id":id,"status":"visible","context":context}]}) + ); + let saved = context["context"]["fields"]["document"]["download"]["path"] + .as_str() + .unwrap(); + let download = format!( + "{}{saved}&accessProfile=member-review", + fixture.http.base_url + ); + let http = reqwest::Client::new(); + let response = http.get(&download).send().await.unwrap(); + assert_eq!(response.status(), StatusCode::OK); + assert!(response.bytes().await.unwrap().as_ref() == b"Synthetic review document"); + + for (membership, apply_after) in [ + (&destination_membership, true), + (&original_membership, false), + ] { + set_membership_active(&fixture.http, membership, false).await; + let (status, problem, _) = + send(&fixture.http, Method::GET, &scalar, Value::Null, None, None).await; + assert_eq!(status, StatusCode::NOT_FOUND); + assert_eq!(problem["code"], "resource.not-found"); + assert!(problem.get("context").is_none()); + let (status, page, _) = + send(&fixture.http, Method::GET, &batch, Value::Null, None, None).await; + assert_eq!(status, StatusCode::OK); + assert_eq!(page, json!({"items":[{"id":id,"status":"concealed"}]})); + let response = http.get(&download).send().await.unwrap(); + assert_eq!(response.status(), StatusCode::NOT_FOUND); + assert_eq!( + response.json::().await.unwrap()["code"], + "resource.not-found" + ); + if apply_after { + set_membership_active(&fixture.http, membership, true).await; + let (status, value, _) = send( + &fixture.http, Method::POST, &format!("/v1/proposals/{id}/apply?accessProfile=clerk"), + json!({"submissionVersion":submitted["submissionVersion"],"effectDigest":submitted["effectDigest"]}), + Some("apply-move"), etag.as_deref() + ).await; + assert_eq!(status, StatusCode::OK); + assert_eq!(value["state"], "applied"); + assert_eq!( + send(&fixture.http, Method::GET, &scalar, Value::Null, None, None) + .await + .0, + StatusCode::OK + ); + } + } + fixture.finish().await; +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn attachment_membership_accounting_requires_accepted_refusal_audit() { + use axum::{ + body::{to_bytes, Body}, + http::Request, + }; + use registry_breg::metrics::{metrics_app, Metrics}; + use registry_platform_config::Posture; + use tower::ServiceExt as _; + + // Isolate the process-wide counter from other tests in this target. + const CHILD: &str = "BREG_TEST_ATTACHMENT_MEMBERSHIP_ACCOUNTING_CHILD"; + const TEST: &str = "attachment_membership_accounting_requires_accepted_refusal_audit"; + if std::env::var_os(CHILD).is_none() { + let result = std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", TEST]) + .env(CHILD, "1") + .output() + .unwrap(); + assert!( + result.status.success() + && String::from_utf8_lossy(&result.stdout).contains("1 passed; 0 failed"), + "isolated attachment accounting check failed" + ); + return; + } + + async fn membership_refusals() -> u64 { + let response = metrics_app( + Arc::new(Metrics::without_pool_for_test()), + Posture::Production, + ) + .oneshot( + Request::builder() + .uri("/metrics") + .body(Body::empty()) + .unwrap(), + ) + .await + .unwrap(); + let body = to_bytes(response.into_body(), 4 * 1024 * 1024) + .await + .unwrap(); + std::str::from_utf8(&body) + .unwrap() + .lines() + .find_map(|line| { + line.strip_prefix("breg_request_refusals_total{check=\"membership\"} ") + }) + .expect("membership refusal counter is present") + .parse() + .expect("membership refusal counter is numeric") + } + + let mut project = source(true); + project["accessProfiles"] + .as_object_mut() + .unwrap() + .remove("task-reviewer"); + // A submitted Create checks membership against the frozen after-image. + // Loading an existing target can return a generic 412 before that probe. + let action = &mut project["actions"]["correct-name"]; + action.as_object_mut().unwrap().remove("commitGuards"); + action["inputs"][0] = json!({"id":"organization","type":"reference","target":"organization", + "required":true,"classification":"internal"}); + action["plan"]["effects"] = json!([{ + "id":"record","target":{"recordType":"target"},"operation":"create", + "set":{"name":{"fromInput":"value"},"jurisdiction":{"value":"zone-a"}, + "organization":{"fromInput":"organization"}} + }]); + let proposal = &mut action["execution"]["proposal"]; + proposal["reviewContext"]["fields"] = json!({"proposedName":{"type":"input","input":"value"}}); + proposal["attachments"] = json!([ + {"id":"support","required":false,"maximumBytes":64, + "contentTypes":["text/plain"],"classification":"restricted"} + ]); + let permissions = &mut project["accessProfiles"]["clerk"]["permissions"]; + let mut targets = permissions["actions"][0]["targets"].clone(); + targets[0]["rowBoundaries"] + .as_array_mut() + .unwrap() + .push(json!({"field":"organization","membership":"membership"})); + targets + .as_array_mut() + .unwrap() + .push(json!({"recordType":"organization","rowBoundaries":"unrestricted"})); + permissions["actions"][0]["targets"] = targets.clone(); + let grant = &mut permissions["proposals"][0]; + grant["readableInputs"] = json!(["organization", "value"]); + grant["writableAttachments"] = json!(["support"]); + grant["targets"] = targets; + + for method in [Method::PATCH, Method::DELETE] { + let fixture = client_http::ClientFixture::start(compile(project.clone()), clerk()).await; + let organization = create( + &fixture.http, + "organizations", + json!({"name":"Unit"}), + "organization", + ) + .await; + let membership = create( + &fixture.http, + "memberships", + json!({"organization":organization,"principal":"author","active":true}), + "attachment-accounting-membership", + ) + .await; + let (status, draft, etag) = send( + &fixture.http, + Method::POST, + "/v1/actions/correct-name/proposals?accessProfile=clerk", + json!({"input":{"organization":organization,"value":"Proposed"}}), + Some("attachment-accounting-start"), + None, + ) + .await; + assert_eq!(status, StatusCode::CREATED); + let id = draft["id"].as_str().unwrap(); + let (status, _, etag) = send( + &fixture.http, + Method::POST, + &format!("/v1/proposals/{id}/submit?accessProfile=clerk"), + json!({}), + Some("attachment-accounting-submit"), + etag.as_deref(), + ) + .await; + assert_eq!(status, StatusCode::OK); + let etag = etag.unwrap(); + set_membership_active(&fixture.http, &membership, false).await; + let url = format!( + "{}/v1/proposals/{id}/attachments/support?accessProfile=clerk", + fixture.http.base_url + ); + let http = reqwest::Client::new(); + for (reject_audit, expected_status, expected_code, expected_delta) in [ + ( + false, + StatusCode::PRECONDITION_FAILED, + "precondition.failed", + 1, + ), + ( + true, + StatusCode::SERVICE_UNAVAILABLE, + "source.unavailable", + 0, + ), + ] { + let before_count = membership_refusals().await; + let before_entries = fixture.audit_capture.entries().len(); + let before_rejections = fixture.audit_capture.matched_refusal_count(); + if reject_audit { + fixture + .audit_capture + .fail_on(registry_breg::audit::AUDIT_SCHEMA, "refusal"); + } + let request = http + .request(method.clone(), &url) + .header("if-match", etag.as_str()) + .header( + "idempotency-key", + format!("attachment-accounting-{reject_audit}"), + ); + let request = if method == Method::PATCH { + request + .header("content-type", "text/plain") + .body("Synthetic document") + } else { + request + }; + let response = request.send().await.unwrap(); + assert_eq!(response.status(), expected_status, "{method}"); + let problem: Value = response.json().await.unwrap(); + assert_eq!(problem["code"], expected_code, "{method}"); + assert!(problem.get("failedCheck").is_none(), "{method}"); + assert!(problem.get("guardReason").is_none(), "{method}"); + let accepted = fixture.audit_capture.entries()[before_entries..] + .iter() + .any(|entry| { + entry["record"]["phase"] == "refusal" + && entry["record"]["method"] == method.as_str() + }); + let rejected = fixture.audit_capture.matched_refusal_count() > before_rejections; + assert_eq!( + (accepted, rejected), + (!reject_audit, reject_audit), + "{method}" + ); + assert_eq!( + membership_refusals().await - before_count, + expected_delta, + "{method}" + ); + } + fixture.finish().await; + } +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn submitted_create_membership_controls_attachments_answers_and_commands() { + let mut project = source(true); + project["accessProfiles"] + .as_object_mut() + .unwrap() + .remove("task-reviewer"); + project["reviewAuthorities"] = + json!({"casework":{"protocol":"id.registrystack.org/protocols/review/v1"}}); + let action = &mut project["actions"]["correct-name"]; + action.as_object_mut().unwrap().remove("commitGuards"); + action["inputs"][0] = json!({"id":"organization","type":"reference","target":"organization", + "required":true,"classification":"internal"}); + action["plan"]["effects"] = json!([{ + "id":"record","target":{"recordType":"target"},"operation":"create", + "set":{"name":{"fromInput":"value"},"jurisdiction":{"value":"zone-a"}, + "organization":{"fromInput":"organization"}} + }]); + let proposal = &mut action["execution"]["proposal"]; + proposal["review"] = json!({"type":"required","authority":"casework","source":"proposal-security", + "policy":{"id":"name-correction","version":"1","digest":format!("sha256:{}","b".repeat(64))}}); + proposal["reviewContext"]["fields"] = json!({"proposedName":{"type":"input","input":"value"}}); + proposal["attachments"] = json!([ + {"id":"support","required":false,"maximumBytes":64,"contentTypes":["text/plain"],"classification":"restricted"} + ]); + proposal["additions"] = json!({"id":"other","maximumBytes":64,"maximumCount":3, + "contentTypes":["text/plain"],"classification":"restricted"}); + let permissions = &mut project["accessProfiles"]["clerk"]["permissions"]; + let targets = json!([ + {"recordType":"target","rowBoundaries":[{"field":"organization","membership":"membership"}]}, + {"recordType":"organization","rowBoundaries":"unrestricted"} + ]); + permissions["actions"][0]["targets"] = targets.clone(); + permissions["proposals"][0] = json!({ + "action":"correct-name","party":"owner","targets":targets, + "operations":["get","list","get-review-context","get-review-status","edit","submit","revise","rebase","cancel","retry","answer","add"], + "readableInputs":["organization","value"],"readableContextFields":["proposedName"], + "readableAttachments":["support","other"],"writableAttachments":["support","other"] + }); + project["accessProfiles"]["task-context"] = json!({ + "principalClaim":"registry_principal","actorKind":"service","requesterClients":["agent-client"], + "requiredScopes":["proposal:task-context"],"requiredPurposes":["registry-administration"], + "permissions":{"proposals":[{"action":"correct-name","operations":["get-task-grant-context"], + "readableContextFields":["proposedName"],"targets":targets}]} + }); + let fixture = client_http::ClientFixture::start_with_mutations( + compile(project), + human_clerk(), + |service| service.with_review_result_source(review_binding()), + ) + .await; + let organization = create( + &fixture.http, + "organizations", + json!({"name":"Unit"}), + "attachment-unit", + ) + .await; + let membership = create( + &fixture.http, + "memberships", + json!({"organization":organization,"principal":"author","active":true}), + "attachment-membership", + ) + .await; + let input = json!({"organization":organization,"value":"Proposed"}); + let (status, draft, etag) = send( + &fixture.http, + Method::POST, + "/v1/actions/correct-name/proposals?accessProfile=clerk", + json!({"input":input}), + Some("start-attachments"), + None, + ) + .await; + assert_eq!(status, StatusCode::CREATED); + let id = uuid::Uuid::parse_str(draft["id"].as_str().unwrap()).unwrap(); + let base = format!("/v1/proposals/{id}"); + let attachment = format!("{base}/attachments/support?accessProfile=clerk"); + let addition_upload = format!("{base}/additions/other?accessProfile=clerk"); + let http = reqwest::Client::new(); + let document = |method: Method, path: &str, key: &str, etag: &str| { + let sends_bytes = method != Method::DELETE; + let request = http + .request(method, format!("{}{path}", fixture.http.base_url)) + .header("if-match", etag) + .header("idempotency-key", key); + if sends_bytes { + request + .header("content-type", "text/plain") + .body("Synthetic document") + } else { + request + } + }; + let mut etag = etag.unwrap(); + for (method, key) in [ + (Method::PATCH, "attach-draft-file"), + (Method::DELETE, "remove-draft-file"), + (Method::PATCH, "restore-draft-file"), + ] { + let response = document(method, &attachment, key, &etag) + .send() + .await + .unwrap(); + assert_eq!(response.status(), StatusCode::OK); + etag = response.headers()["etag"].to_str().unwrap().to_owned(); + } + let (status, _, submitted_etag) = send( + &fixture.http, + Method::POST, + &format!("{base}/submit?accessProfile=clerk"), + json!({}), + Some("submit-attachments"), + Some(&etag), + ) + .await; + assert_eq!(status, StatusCode::OK); + let response = document( + Method::POST, + &addition_upload, + "add-document", + &submitted_etag.unwrap(), + ) + .send() + .await + .unwrap(); + assert_eq!(response.status(), StatusCode::OK); + let etag = response.headers()["etag"].to_str().unwrap().to_owned(); + let value: Value = response.json().await.unwrap(); + let addition = value["additions"]["other"]["items"][0]["id"] + .as_str() + .unwrap(); + let addition_download = + format!("{base}/additions/{addition}?submissionVersion=1&accessProfile=clerk"); + let attachment_download = format!("{attachment}&submissionVersion=1"); + for path in [&attachment_download, &addition_download] { + let response = http + .get(format!("{}{path}", fixture.http.base_url)) + .send() + .await + .unwrap(); + assert_eq!(response.status(), StatusCode::OK); + assert!(response.bytes().await.unwrap().as_ref() == b"Synthetic document"); + } + // Install the synthetic review acceptance and mirrored ask. The maintained + // review-delivery suite independently exercises their provider transport. + let row = fixture + .database + .admin + .query_one( + "SELECT create_request,expected_policy,expected_submission_digest + FROM registry_internal.registry_proposal_review_submissions WHERE proposal_id=$1", + &[&id], + ) + .await + .unwrap(); + let create: registry_review_client::ReviewCreateRequest = + serde_json::from_value(row.get(0)).unwrap(); + let accepted = registry_review_client::ReviewRequestAccepted { + request_id: uuid::Uuid::new_v4(), + subject: create.subject, + policy: serde_json::from_value(row.get(1)).unwrap(), + submission_digest: registry_review_client::SubmissionDigest::parse( + row.get::<_, String>(2).as_str(), + ) + .unwrap(), + }; + fixture + .database + .admin + .execute( + "UPDATE registry_internal.registry_proposal_review_submissions + SET state='accepted',accepted_binding=$1 WHERE proposal_id=$2", + &[&serde_json::to_value(&accepted).unwrap(), &id], + ) + .await + .unwrap(); + let as_of = chrono::Utc::now(); + let ask = uuid::Uuid::new_v4(); + fixture.database.admin.execute( + "INSERT INTO registry_internal.registry_proposal_review_asks + (authority,review_request_id,ask_id,action_id,proposal_id,submission_version,text,wants,asked_at,asked_at_wire,state) + VALUES ('casework',$1,$2,'correct-name',$3,1,'Synthetic question',$4,$5,$6,'open')", + &[&accepted.request_id,&ask,&id,&json!([{"kind":"answer"}]),&as_of,&as_of.to_rfc3339()] + ).await.unwrap(); + let answer = format!("{base}/asks/{ask}/answer?accessProfile=clerk"); + let (status, _, answered_etag) = send( + &fixture.http, + Method::POST, + &answer, + json!({"text":"Synthetic answer"}), + Some("answer-ask"), + Some(&etag), + ) + .await; + assert_eq!(status, StatusCode::OK); + let etag = answered_etag.unwrap(); + let (status, context, _) = send( + &fixture.http, + Method::GET, + &format!("{base}/review-context?accessProfile=clerk"), + Value::Null, + None, + None, + ) + .await; + assert_eq!(status, StatusCode::OK); + assert_eq!( + context["context"]["fields"], + json!({"proposedName":"Proposed"}) + ); + let (status, _, _) = send( + &fixture.http, + Method::GET, + &format!("{base}/review-status?accessProfile=clerk"), + Value::Null, + None, + None, + ) + .await; + assert_eq!(status, StatusCode::OK); + let idp = MockIdp::start().await; + let auth = authenticator(&fixture.registry, &idp).await; + let task_caller = fixture.client_for(auth.authenticate(&idp.mint_token(json!({ + "aud":"urn:example:breg","sub":"author","azp":"agent-client","registry_principal":"author", + "registry_actor_kind":"service","registry_purpose":"registry-administration","scope":"proposal:task-context" + }))).await.unwrap()).await; + let task_path = format!("{base}/task-grant-context?accessProfile=task-context"); + let task_request = json!({ + "expected":{"actionId":"correct-name","subject":context["subject"],"contract":context["context"]["contract"]}, + "requestId":accepted.request_id,"taskId":uuid::Uuid::new_v4(),"taskRevision":1, + "policy":accepted.policy,"purpose":"task-grant","fields":["proposedName"] + }); + let (status, task_context, _) = send( + &task_caller, + Method::POST, + &task_path, + task_request.clone(), + None, + None, + ) + .await; + assert_eq!(status, StatusCode::OK); + assert_eq!( + task_context["proposal"]["context"]["fields"], + json!({"proposedName":"Proposed"}) + ); + set_membership_active(&fixture.http, &membership, false).await; + let (status, problem, _) = send( + &task_caller, + Method::POST, + &task_path, + task_request, + None, + None, + ) + .await; + assert_eq!(status, StatusCode::NOT_FOUND); + assert_eq!(problem["code"], "resource.not-found"); + assert!(problem.get("proposal").is_none()); + for path in [&attachment_download, &addition_download] { + let response = http + .get(format!("{}{path}", fixture.http.base_url)) + .send() + .await + .unwrap(); + assert_eq!(response.status(), StatusCode::NOT_FOUND); + assert_eq!( + response.json::().await.unwrap()["code"], + "resource.not-found" + ); + } + for (method, path, key, expected, problem) in [ + ( + Method::PATCH, + &attachment, + "deny-attachment-replace", + StatusCode::PRECONDITION_FAILED, + "precondition.failed", + ), + ( + Method::DELETE, + &attachment, + "remove-draft-file", + StatusCode::PRECONDITION_FAILED, + "precondition.failed", + ), + ( + Method::POST, + &addition_upload, + "deny-addition", + StatusCode::NOT_FOUND, + "resource.not-found", + ), + ] { + let response = document(method, path, key, &etag).send().await.unwrap(); + assert_eq!(response.status(), expected); + let body = response.json::().await.unwrap(); + assert_eq!(body["code"], problem); + assert!(body.get("failedCheck").is_none()); + } + let (status, problem, _) = send( + &fixture.http, + Method::POST, + &answer, + json!({"text":"Synthetic answer"}), + Some("answer-ask"), + Some(&etag), + ) + .await; + assert_eq!(status, StatusCode::NOT_FOUND); + assert_eq!(problem["code"], "resource.not-found"); + for operation in ["review-context", "review-status"] { + let (status, problem, _) = send( + &fixture.http, + Method::GET, + &format!("{base}/{operation}?accessProfile=clerk"), + Value::Null, + None, + None, + ) + .await; + assert_eq!(status, StatusCode::NOT_FOUND); + assert_eq!(problem["code"], "resource.not-found"); + } + for operation in ["revise", "rebase", "cancel", "retry"] { + let (status, problem, _) = send( + &fixture.http, + Method::POST, + &format!("{base}/{operation}?accessProfile=clerk"), + if matches!(operation, "revise" | "rebase") { + json!({"input":input}) + } else { + json!({}) + }, + Some(operation), + Some(&etag), + ) + .await; + assert_eq!(status, StatusCode::PRECONDITION_FAILED); + assert_eq!(problem["code"], "precondition.failed"); + assert!(problem.get("failedCheck").is_none()); + } + fixture.finish().await; +} + fn caller(subject: &str) -> VerifiedRequestClaims { caller_in(subject, "zone-a") } @@ -2701,6 +3569,15 @@ fn link_source() -> Value { /// Proposal id). async fn linked_history(fixture: &client_http::ClientFixture) -> (String, String, String) { let (organization, target) = seed(fixture).await; + let id = apply_and_link_history(fixture, &organization, &target).await; + (organization, target, id) +} + +async fn apply_and_link_history( + fixture: &client_http::ClientFixture, + organization: &str, + target: &str, +) -> String { let (code, condition, _) = send( &fixture.http, Method::POST, @@ -2754,7 +3631,7 @@ async fn linked_history(fixture: &client_http::ClientFixture) -> (String, String ) .await; assert_eq!(code, StatusCode::OK, "{applied}"); - (organization, target, id) + id } async fn history( @@ -2897,6 +3774,60 @@ async fn record_history_omits_the_proposal_from_a_profile_without_a_proposal_gra fixture.finish().await; } +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn record_history_rechecks_proposal_membership_without_hiding_the_revision() { + let mut project = link_source(); + project["recordTypes"]["membership"]["membership"] = + json!({"key":"organization","principal":"principal","active":"active"}); + let clerk_permissions = &mut project["accessProfiles"]["clerk"]["permissions"]; + clerk_permissions["proposals"][0]["targets"][0]["rowBoundaries"] + .as_array_mut() + .unwrap() + .push(json!({"field":"organization","membership":"membership"})); + clerk_permissions["actions"][0]["targets"][0]["rowBoundaries"] + .as_array_mut() + .unwrap() + .push(json!({"field":"organization","membership":"membership"})); + separate_membership_admin(&mut project); + let fixture = client_http::ClientFixture::start(compile(project), clerk()).await; + let (organization, target) = seed(&fixture).await; + let membership = create( + &fixture.http, + "memberships", + json!({"organization":organization,"principal":"author","active":true}), + "history-membership", + ) + .await; + let id = apply_and_link_history(&fixture, &organization, &target).await; + assert_link(&fixture.http, &target, "clerk", &id).await; + set_membership_active(&fixture.http, &membership, false).await; + assert_no_link(&fixture.http, &target, "clerk").await; + let (status, problem, _) = send( + &fixture.http, + Method::GET, + &format!("/v1/proposals/{id}?accessProfile=clerk"), + Value::Null, + None, + None, + ) + .await; + assert_eq!(status, StatusCode::NOT_FOUND); + assert_eq!(problem["code"], "resource.not-found"); + let (status, problem, _) = send( + &fixture.http, + Method::POST, + "/v1/actions/correct-name/proposals?accessProfile=clerk", + json!({"input":{"target":target,"value":"Proposed"}}), + Some("start-without-membership"), + None, + ) + .await; + assert_eq!(status, StatusCode::PRECONDITION_FAILED); + assert_eq!(problem["code"], "precondition.failed"); + assert!(problem.get("failedCheck").is_none()); + fixture.finish().await; +} + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn record_history_omits_the_proposal_when_ownership_does_not_match() { let fixture = client_http::ClientFixture::start(compile(link_source()), clerk()).await; @@ -2938,7 +3869,7 @@ fn row_boundary_link_source() -> Value { "permissions":{"records":[ {"recordType":"target","operations":["get","revisions"],"revisionAccess":true, "readableFields":["name","jurisdiction","organization"],"rowBoundaries":"unrestricted"}], - "proposals":[{"action":"correct-name","operations":["get"],"ownership":"caller", + "proposals":[{"action":"correct-name","operations":["get"],"party":"owner", "targets":[{"recordType":"target","rowBoundaries": [{"field":"jurisdiction","claim":"jurisdiction","operator":"equals"}]}]}]}}); project @@ -3359,7 +4290,7 @@ async fn proposal_target_refusals_are_identical_across_routes_and_postures() { .remove("records"); alternate["permissions"]["actions"][0]["action"] = json!("alternate-name"); alternate["permissions"]["proposals"][0] = json!({ - "action":"alternate-name", "operations":["get"], "ownership":"caller", "targets":targets, + "action":"alternate-name", "operations":["get"], "party":"owner", "targets":targets, }); source["accessProfiles"]["alternate"] = alternate.clone(); alternate["permissions"] diff --git a/crates/registry-breg/tests/postgres_proposal_shape_activation.rs b/crates/registry-breg/tests/postgres_proposal_shape_activation.rs index eb092dc537..763148d654 100644 --- a/crates/registry-breg/tests/postgres_proposal_shape_activation.rs +++ b/crates/registry-breg/tests/postgres_proposal_shape_activation.rs @@ -60,7 +60,7 @@ fn registry_source(automatic: bool) -> Value { "actions":[{"action":"correct-name","operations":["start"],"targets":[{"recordType":"target", "rowBoundaries":[{"field":"jurisdiction","claim":"jurisdiction","operator":"equals"}]}]}], "proposals":[{"action":"correct-name","operations":["get","list","edit","submit","revise","rebase","retry","cancel","apply"], - "ownership":"caller","readableAttachments":["support"],"writableAttachments":["support"],"targets":[{"recordType":"target", + "party":"owner","readableAttachments":["support"],"writableAttachments":["support"],"targets":[{"recordType":"target", "rowBoundaries":[{"field":"jurisdiction","claim":"jurisdiction","operator":"equals"}]}]}]}}}}); source } diff --git a/crates/registry-breg/tests/postgres_proposal_subject.rs b/crates/registry-breg/tests/postgres_proposal_subject.rs new file mode 100644 index 0000000000..aedc7e250e --- /dev/null +++ b/crates/registry-breg/tests/postgres_proposal_subject.rs @@ -0,0 +1,1592 @@ +// SPDX-License-Identifier: Apache-2.0 + +//! The person a Proposal is about follows it when someone else filed it. +//! BReg binds the subject once, at the first Submit, and admits a caller as +//! the subject only when their verified principal equals that value. +#![cfg(feature = "postgres-test")] +#[path = "support/client_http.rs"] +#[allow(dead_code)] +mod client_http; +#[path = "support/postgres_harness.rs"] +#[allow(dead_code)] +mod postgres_harness; + +use axum::http::{HeaderMap, StatusCode}; +use registry_breg::api::VerifiedRequestClaims; +use registry_breg::compiler::{compile_project, CompileProfile}; +use registry_breg::contract::parse_project_json; +use registry_breg_client::{ + BRegCreateRequest, BRegDirectWrite, BRegIdempotencyKey, BRegRecordFormat, +}; +use registry_platform_oidc::ActorKind; +use serde_json::{json, Value}; +use std::collections::{BTreeMap, BTreeSet}; +use uuid::Uuid; + +const CLERK: &str = "clerk-canary"; +const CITIZEN: &str = "citizen-a-canary"; +const NEIGHBOUR: &str = "citizen-b-canary"; + +fn targets() -> Value { + json!([{"recordType":"licence","rowBoundaries":"unrestricted"}]) +} + +fn source() -> Value { + let policy = + json!({"id":"licence-review","version":"1","digest":format!("sha256:{}","b".repeat(64))}); + let proposal = |subject: Value| { + json!({"review":{"type":"required","authority":"local-review","source":"licence-test","policy":policy}, + "application":{"mode":"manual"},"retention":{"mode":"retain"},"subject":subject, + "attachments":[{"id":"id-scan","required":false,"maximumBytes":1024, + "contentTypes":["text/plain"],"classification":"internal"}], + "additions":{"id":"other","maximumBytes":1024,"maximumCount":4, + "contentTypes":["text/plain"],"classification":"internal"}}) + }; + let owner = |action: &str, readable: Value| { + json!({"action":action,"party":"owner", + "operations":["get","list","edit","submit","revise","cancel","get-review-status"], + "readableInputs":readable,"targets":targets()}) + }; + json!({ + "apiVersion":"id.registrystack.org/formats/breg/project/v1alpha1","kind":"BRegProject", + "project":{"id":"proposal-subject","version":"1","defaultLanguage":"en","canonicalBaseIri":"https://proposal-subject.example.test"}, + "datasets":{"licences": {}}, + "reviewAuthorities":{"local-review": {"protocol":"id.registrystack.org/protocols/review/v1"}}, + "recordTypes":{ + "licence": {"route":"licences","primaryDataset":"licences","mutationMode":"mutable","classification":"internal", + "batch":{"maximumItems":3,"maximumBytes":8192}, + "fields":[ + {"id":"holder","type":"string","maximumLength":64,"required":true,"classification":"internal"}, + {"id":"statement","type":"string","maximumLength":64,"required":false,"classification":"internal"}]}}, + "actions":{ + "apply-for-licence": {"execution":{"mode":"proposal","proposal":proposal(json!({"input":"holder"}))}, + "inputs":[ + {"id":"holder","type":"string","maximumLength":64,"required":true,"classification":"internal"}, + {"id":"statement","type":"string","maximumLength":64,"required":false,"classification":"internal"}], + "plan":{"type":"fixed","effects":[{"id":"issued","target":{"recordType":"licence"},"operation":"create", + "set":{"holder":{"fromInput":"holder"},"statement":{"fromInput":"statement"}}}]}}, + "renew-licence": {"execution":{"mode":"proposal","proposal":proposal(json!({"input":"licence","field":"holder"}))}, + "inputs":[ + {"id":"licence","type":"reference","target":"licence","required":true,"classification":"internal"}, + {"id":"statement","type":"string","maximumLength":64,"required":false,"classification":"internal"}], + "plan":{"type":"fixed","effects":[{"id":"renewed","target":{"fromInput":"licence"},"operation":"patch", + "set":{"statement":{"fromInput":"statement"}}}]}}, + "issue-copy": {"execution":{"mode":"proposal","proposal":proposal(json!({"input":"original","field":"holder"}))}, + "inputs":[ + {"id":"original","type":"reference","target":"licence","required":true,"classification":"internal"}, + {"id":"copy-holder","type":"string","maximumLength":64,"required":true,"classification":"internal"}], + "plan":{"type":"fixed","effects":[{"id":"copied","target":{"recordType":"licence"},"operation":"create", + "set":{"holder":{"fromInput":"copy-holder"}}}]}}}, + "accessProfiles":{ + "admin": {"principalClaim":"sub","requiredScopes":["licence:admin"],"actorKind":"human", + "permissions":{"records":[{"recordType":"licence","operations":["create","get","patch"], + "readableFields":["holder","statement"],"writableFields":["holder","statement"],"rowBoundaries":"unrestricted"}]}}, + "desk": {"principalClaim":"sub","requiredScopes":["licence:desk"],"actorKind":"human", + "permissions":{ + "actions":[ + {"action":"apply-for-licence","operations":["start"],"targets":targets()}, + {"action":"renew-licence","operations":["start"],"targets":targets()}, + {"action":"issue-copy","operations":["start"],"targets":targets()}], + "proposals":[ + {"action":"issue-copy","party":"owner","submitsFor":"anyone", + "operations":["get","list","edit","submit","cancel"], + "readableInputs":["original","copy-holder"],"targets":targets()}, + {"action":"apply-for-licence","party":"owner","submitsFor":"anyone", + "operations":["get","list","edit","submit","revise","cancel","get-review-status"], + "readableInputs":["holder","statement"],"readableAttachments":["id-scan"], + "writableAttachments":["id-scan"],"targets":targets()}, + {"action":"renew-licence","party":"owner","submitsFor":"anyone", + "operations":["get","list","edit","submit","revise","cancel","get-review-status"], + "readableInputs":["licence","statement"],"targets":targets()}]}}, + "citizen": {"principalClaim":"sub","requiredScopes":["licence:self"],"actorKind":"human", + "permissions":{ + "actions":[ + {"action":"apply-for-licence","operations":["start"],"targets":targets()}, + {"action":"renew-licence","operations":["start"],"targets":targets()}], + "proposals":[ + {"action":"apply-for-licence","party":"owner", + "operations":["get","list","edit","submit","revise","cancel","get-review-status"], + "readableInputs":["holder","statement"],"readableAttachments":["id-scan"], + "writableAttachments":["id-scan"],"targets":targets()}, + {"action":"apply-for-licence","party":"subject", + "operations":["get","list","cancel","get-review-status","answer","add"], + "readableInputs":["holder"],"writableAttachments":["other"], + "targets":targets()}, + owner("renew-licence", json!(["licence","statement"])), + {"action":"renew-licence","party":"subject", + "operations":["get","list","cancel"], + "readableInputs":["licence"],"targets":targets()}]}}, + // A follower profile written for any actor kind: only the human + // test keeps an agent or service with the same principal out. + "follower": {"principalClaim":"sub","requiredScopes":["licence:follow"], + "permissions":{"proposals":[ + {"action":"apply-for-licence","party":"subject","operations":["get","list"], + "readableInputs":["holder"],"targets":targets()}]}}} + }) +} + +fn compile(source: &Value) -> registry_breg::CompiledRegistry { + let project = parse_project_json(&serde_json::to_vec(source).unwrap()).unwrap(); + compile_project(&project, &[], CompileProfile::Authoring).expect("subject project compiles") +} + +fn person(principal: &str, scope: &str, kind: ActorKind) -> VerifiedRequestClaims { + VerifiedRequestClaims::authenticated_with_actor_kind( + "sub", + principal, + BTreeSet::from([scope.to_owned()]), + Some("licence-portal".into()), + BTreeMap::new(), + kind, + ) + .unwrap() +} + +fn clerk() -> VerifiedRequestClaims { + person(CLERK, "licence:desk", ActorKind::Human) +} + +fn citizen(principal: &str) -> VerifiedRequestClaims { + person(principal, "licence:self", ActorKind::Human) +} + +struct NoToken; +#[async_trait::async_trait] +impl registry_platform_httputil::TokenProvider for NoToken { + async fn bearer_token( + &self, + ) -> Result + { + Err(registry_platform_httputil::TokenError::Unavailable) + } +} + +struct NoResult; +#[async_trait::async_trait] +impl registry_breg::review_store::ReviewResultSource for NoResult { + async fn approved_evidence( + &self, + _authority: &str, + _accepted: ®istry_review_client::ReviewRequestAccepted, + ) -> Result< + registry_breg::review_integration::AcceptedReviewEvidence, + registry_breg::mutation::MutationError, + > { + Err(registry_breg::mutation::MutationError::Unavailable) + } +} + +fn local_review() -> std::sync::Arc { + use registry_breg::review_store::{ReviewAuthorityClient, ReviewAuthorityRegistry}; + let client = registry_review_client::ReviewClient::new( + registry_review_client::ReviewClientConfig::new_without_peer_policy( + "http://127.0.0.1:9/".parse().unwrap(), + ), + ) + .unwrap(); + let authority = std::sync::Arc::new( + ReviewAuthorityClient::new( + "local-review".into(), + client, + std::sync::Arc::new(NoToken), + "producer".into(), + "proposal-producer".into(), + 7, + None, + None, + ) + .unwrap(), + ); + std::sync::Arc::new( + ReviewAuthorityRegistry::new(BTreeMap::from([("local-review".into(), authority)])).unwrap(), + ) +} + +async fn fixture_from(source: &Value) -> client_http::ClientFixture { + client_http::ClientFixture::start_with_mutations( + compile(source), + person("admin-canary", "licence:admin", ActorKind::Human), + |mutations| { + mutations.with_proposal_review_substitute_for_test( + local_review(), + std::sync::Arc::new(NoResult), + ) + }, + ) + .await +} + +async fn fixture() -> client_http::ClientFixture { + fixture_from(&source()).await +} + +async fn request( + fixture: &client_http::ClientFixture, + caller: VerifiedRequestClaims, + method: &str, + path: &str, + etag: Option<&str>, + key: Option<&str>, + body: Value, +) -> (StatusCode, HeaderMap, Value) { + use tower::ServiceExt; + let mut req = axum::http::Request::builder() + .method(method) + .uri(path) + .header("content-type", "application/json"); + if let Some(etag) = etag { + req = req.header("if-match", etag); + } + if let Some(key) = key { + req = req.header("idempotency-key", key); + } + let response = registry_breg::api::router(fixture.service()) + .layer(axum::Extension(caller)) + .oneshot( + req.body(if method == "GET" { + axum::body::Body::empty() + } else { + axum::body::Body::from(serde_json::to_vec(&body).unwrap()) + }) + .unwrap(), + ) + .await + .unwrap(); + let status = response.status(); + let headers = response.headers().clone(); + let bytes = axum::body::to_bytes(response.into_body(), 1 << 22) + .await + .unwrap(); + let value = if bytes.is_empty() { + Value::Null + } else { + serde_json::from_slice(&bytes).unwrap() + }; + (status, headers, value) +} + +async fn get( + fixture: &client_http::ClientFixture, + caller: VerifiedRequestClaims, + id: Uuid, +) -> (StatusCode, Option, Value) { + let (status, headers, value) = request( + fixture, + caller, + "GET", + &format!("/v1/proposals/{id}"), + None, + None, + Value::Null, + ) + .await; + let etag = headers + .get("etag") + .map(|etag| etag.to_str().unwrap().to_owned()); + (status, etag, value) +} + +/// Run `operation` as `caller` against the Proposal's current ETag for that +/// caller. +async fn command( + fixture: &client_http::ClientFixture, + caller: VerifiedRequestClaims, + id: Uuid, + operation: &str, + key: &str, + body: Value, +) -> (StatusCode, Value) { + let (status, etag, document) = get(fixture, caller.clone(), id).await; + assert_eq!(status, StatusCode::OK, "{document}"); + let (status, _, value) = request( + fixture, + caller, + "POST", + &format!("/v1/proposals/{id}/{operation}"), + etag.as_deref(), + Some(key), + body, + ) + .await; + (status, value) +} + +async fn start( + fixture: &client_http::ClientFixture, + caller: VerifiedRequestClaims, + action: &str, + input: Value, + key: &str, +) -> Uuid { + let (status, _, value) = request( + fixture, + caller, + "POST", + &format!("/v1/actions/{action}/proposals"), + None, + Some(key), + json!({ "input": input }), + ) + .await; + assert_eq!(status, StatusCode::CREATED, "{value}"); + Uuid::parse_str(value["id"].as_str().unwrap()).unwrap() +} + +/// A Proposal `caller` filed naming `holder`, submitted. +async fn filed( + fixture: &client_http::ClientFixture, + caller: VerifiedRequestClaims, + holder: &str, + key: &str, +) -> Uuid { + let id = start( + fixture, + caller.clone(), + "apply-for-licence", + json!({"holder":holder,"statement":"Officer-only statement"}), + &format!("{key}-start"), + ) + .await; + let (status, value) = command( + fixture, + caller, + id, + "submit", + &format!("{key}-submit"), + json!({}), + ) + .await; + assert_eq!(status, StatusCode::OK, "{value}"); + id +} + +async fn list( + fixture: &client_http::ClientFixture, + caller: VerifiedRequestClaims, + query: &str, +) -> Vec { + let (status, _, page) = request( + fixture, + caller, + "GET", + &format!("/v1/proposals{query}"), + None, + None, + Value::Null, + ) + .await; + assert_eq!(status, StatusCode::OK, "{page}"); + page["items"].as_array().unwrap().clone() +} + +fn link_names(document: &Value) -> BTreeSet { + document["links"] + .as_object() + .unwrap() + .keys() + .cloned() + .collect() +} + +/// Return the current review round with changes requested, so the party has +/// the turn and Revise is open. +async fn request_changes(fixture: &client_http::ClientFixture, id: Uuid) { + let row = fixture + .database + .admin + .query_one( + "SELECT create_request,expected_submission_digest FROM registry_internal.registry_proposal_review_submissions + WHERE proposal_id=$1 ORDER BY submission_version DESC LIMIT 1", + &[&id], + ) + .await + .unwrap(); + let create: registry_review_client::ReviewCreateRequest = + serde_json::from_value(row.get(0)).unwrap(); + let accepted = registry_review_client::ReviewRequestAccepted { + request_id: Uuid::new_v4(), + subject: create.subject, + policy: serde_json::from_value(json!({"id":"licence-review","version":"1","digest":format!("sha256:{}","b".repeat(64))})).unwrap(), + submission_digest: serde_json::from_value(json!(row.get::<_, String>(1))).unwrap(), + }; + fixture + .database + .admin + .execute( + "UPDATE registry_internal.registry_proposal_review_submissions SET state='accepted',accepted_binding=$2 + WHERE proposal_id=$1 AND state<>'accepted'", + &[&id, &serde_json::to_value(&accepted).unwrap()], + ) + .await + .unwrap(); + let now = chrono::Utc::now(); + let result = registry_review_client::ReviewResult { + result_id: Uuid::new_v4(), + request_id: accepted.request_id, + subject: accepted.subject.clone(), + policy: accepted.policy.clone(), + submission_digest: accepted.submission_digest.clone(), + status: serde_json::from_value(json!("changes-requested")).unwrap(), + outcome: Some("changes-requested".to_owned()), + public_reason: Some("Public reason for the applicant".to_owned()), + result: None, + completed_at: now - chrono::Duration::seconds(2), + available_until: now + chrono::Duration::minutes(5), + }; + let (mut migration, task) = fixture.database.connect_migration().await; + let tx = migration.transaction().await.unwrap(); + registry_breg::review_store::reconcile_result( + &tx, + "local-review", + &accepted, + &result, + &fixture.mutations, + ) + .await + .unwrap(); + tx.commit().await.unwrap(); + drop(migration); + task.abort(); +} + +#[tokio::test] +async fn a_citizen_follows_a_proposal_the_desk_filed_and_a_neighbour_sees_nothing() { + let fixture = fixture().await; + let id = filed(&fixture, clerk(), CITIZEN, "desk-files").await; + + let (status, _, filer) = get(&fixture, clerk(), id).await; + assert_eq!(status, StatusCode::OK, "{filer}"); + assert_eq!(filer["partyRole"], "owner"); + + let (status, _, followed) = get(&fixture, citizen(CITIZEN), id).await; + assert_eq!(status, StatusCode::OK, "{followed}"); + assert_eq!(followed["partyRole"], "subject"); + assert_eq!(followed["state"], "submitted"); + // The subject entry's readable inputs govern the projection. + assert_eq!(followed["input"], json!({"holder": CITIZEN})); + // Only what the subject entry holds is linked. + let links = link_names(&followed); + assert!(links.contains("cancel"), "{links:?}"); + for owner_only in ["edit", "submit", "revise"] { + assert!(!links.contains(owner_only), "{owner_only} in {links:?}"); + } + + request_changes(&fixture, id).await; + let waiting = list(&fixture, citizen(CITIZEN), "?turn=party").await; + assert_eq!(waiting.len(), 1, "{waiting:?}"); + assert_eq!(waiting[0]["id"], id.to_string()); + assert_eq!(waiting[0]["partyRole"], "subject"); + let (_, _, returned) = get(&fixture, citizen(CITIZEN), id).await; + assert_eq!(returned["turn"], "party"); + + // A neighbour with the same profile learns nothing. + let (status, _, concealed) = get(&fixture, citizen(NEIGHBOUR), id).await; + assert_eq!(status, StatusCode::NOT_FOUND, "{concealed}"); + assert!(list(&fixture, citizen(NEIGHBOUR), "").await.is_empty()); + assert!(list(&fixture, citizen(NEIGHBOUR), "?turn=party") + .await + .is_empty()); + let (status, _, value) = request( + &fixture, + citizen(NEIGHBOUR), + "POST", + &format!("/v1/proposals/{id}/cancel"), + Some("\"breg-proposal-guess\""), + Some("neighbour-cancel"), + json!({}), + ) + .await; + assert_eq!(status, StatusCode::NOT_FOUND, "{value}"); + + // The subject may not use an operation only the owner entry holds. The + // subject already knows the Proposal exists, so the refusal names the + // profile rather than concealing it. + let (status, etag, _) = get(&fixture, citizen(CITIZEN), id).await; + assert_eq!(status, StatusCode::OK); + let (status, _, refused) = request( + &fixture, + citizen(CITIZEN), + "POST", + &format!("/v1/proposals/{id}/revise"), + etag.as_deref(), + Some("subject-revise"), + json!({"input":{"holder":CITIZEN,"statement":"Changed by the subject"}}), + ) + .await; + assert_eq!(status, StatusCode::FORBIDDEN, "{refused}"); + assert_eq!(refused["code"], "profile.not-authorized"); + let (_, _, unchanged) = get(&fixture, clerk(), id).await; + assert_eq!(unchanged["input"]["statement"], "Officer-only statement"); + + let (status, cancelled) = command( + &fixture, + citizen(CITIZEN), + id, + "cancel", + "subject-cancel", + json!({}), + ) + .await; + assert_eq!(status, StatusCode::OK, "{cancelled}"); + assert_eq!(cancelled["state"], "cancelled"); + assert_eq!(cancelled["partyRole"], "subject"); + fixture.finish().await; +} + +#[tokio::test] +async fn a_self_filer_is_the_owner_and_sees_what_the_owner_entry_shows() { + let fixture = fixture().await; + let id = filed(&fixture, citizen(CITIZEN), CITIZEN, "self-files").await; + let (status, _, own) = get(&fixture, citizen(CITIZEN), id).await; + assert_eq!(status, StatusCode::OK, "{own}"); + assert_eq!(own["partyRole"], "owner"); + assert_eq!(own["input"]["statement"], "Officer-only statement"); + let mine = list(&fixture, citizen(CITIZEN), "").await; + assert_eq!(mine.len(), 1); + assert_eq!(mine[0]["partyRole"], "owner"); + fixture.finish().await; +} + +#[tokio::test] +async fn submit_names_someone_else_only_under_submits_for_anyone() { + let fixture = fixture().await; + let id = start( + &fixture, + citizen(CITIZEN), + "apply-for-licence", + json!({"holder":NEIGHBOUR}), + "names-neighbour", + ) + .await; + let (status, refused) = command( + &fixture, + citizen(CITIZEN), + id, + "submit", + "names-neighbour-submit", + json!({}), + ) + .await; + assert_eq!(status, StatusCode::FORBIDDEN, "{refused}"); + assert_eq!(refused["code"], "proposal.subject-not-caller"); + let (_, _, draft) = get(&fixture, citizen(CITIZEN), id).await; + assert_eq!(draft["state"], "draft"); + // The neighbour never became the subject of the refused draft. + let (status, _, _) = get(&fixture, citizen(NEIGHBOUR), id).await; + assert_eq!(status, StatusCode::NOT_FOUND); + + // The desk files for the neighbour. + let desk = filed(&fixture, clerk(), NEIGHBOUR, "desk-names-neighbour").await; + let (status, _, followed) = get(&fixture, citizen(NEIGHBOUR), desk).await; + assert_eq!(status, StatusCode::OK, "{followed}"); + fixture.finish().await; +} + +#[tokio::test] +async fn the_subject_is_frozen_at_the_first_submit() { + let fixture = fixture().await; + // A draft names its subject but binds no one until it is submitted. + let draft = start( + &fixture, + clerk(), + "apply-for-licence", + json!({"holder":CITIZEN}), + "unsubmitted", + ) + .await; + let (status, _, _) = get(&fixture, citizen(CITIZEN), draft).await; + assert_eq!(status, StatusCode::NOT_FOUND); + + let id = filed(&fixture, clerk(), CITIZEN, "frozen").await; + request_changes(&fixture, id).await; + let (status, refused) = command( + &fixture, + clerk(), + id, + "revise", + "move-subject", + json!({"input":{"holder":NEIGHBOUR,"statement":"Officer-only statement"}}), + ) + .await; + assert_eq!(status, StatusCode::BAD_REQUEST, "{refused}"); + assert_eq!(refused["code"], "request.invalid"); + assert_eq!(refused["fieldPath"], "/input/holder", "{refused}"); + + let (status, revised) = command( + &fixture, + clerk(), + id, + "revise", + "keep-subject", + json!({"input":{"holder":CITIZEN,"statement":"Revised statement"}}), + ) + .await; + assert_eq!(status, StatusCode::OK, "{revised}"); + // A revised draft keeps its bound subject. + let (status, _, followed) = get(&fixture, citizen(CITIZEN), id).await; + assert_eq!(status, StatusCode::OK, "{followed}"); + assert_eq!(followed["state"], "draft"); + let (status, edited) = command( + &fixture, + clerk(), + id, + "edit", + "edit-subject", + json!({"input":{"holder":NEIGHBOUR}}), + ) + .await; + assert_eq!(status, StatusCode::BAD_REQUEST, "{edited}"); + assert_eq!(edited["fieldPath"], "/input/holder"); + let (status, resubmitted) = + command(&fixture, clerk(), id, "submit", "resubmit", json!({})).await; + assert_eq!(status, StatusCode::OK, "{resubmitted}"); + assert_eq!(resubmitted["submissionVersion"], 2); + let (status, _, _) = get(&fixture, citizen(NEIGHBOUR), id).await; + assert_eq!(status, StatusCode::NOT_FOUND); + fixture.finish().await; +} + +#[tokio::test] +async fn the_field_form_reads_the_holder_and_refuses_a_moved_holder() { + let fixture = fixture().await; + let client = &fixture.http.client; + let metadata = client.registry_contract(Some("admin")).await.unwrap(); + let BRegDirectWrite::Create(create) = metadata + .value + .select_direct_write("records.licence.create", "admin") + .unwrap() + else { + panic!("create") + }; + let licence = client + .create_record( + &create, + &BRegCreateRequest::new(json!({"holder":CITIZEN}).as_object().unwrap().clone()) + .unwrap(), + &BRegIdempotencyKey::parse("seed-licence").unwrap(), + BRegRecordFormat::Json, + ) + .await + .unwrap() + .value + .data + .record_id; + let id = start( + &fixture, + clerk(), + "renew-licence", + json!({"licence":licence,"statement":"Renewal"}), + "renew", + ) + .await; + let (status, value) = command(&fixture, clerk(), id, "submit", "renew-submit", json!({})).await; + assert_eq!(status, StatusCode::OK, "{value}"); + let (status, _, followed) = get(&fixture, citizen(CITIZEN), id).await; + assert_eq!(status, StatusCode::OK, "{followed}"); + assert_eq!(followed["partyRole"], "subject"); + let (status, _, _) = get(&fixture, citizen(NEIGHBOUR), id).await; + assert_eq!(status, StatusCode::NOT_FOUND); + + // The holder moves on the register; the next Submit refuses. + request_changes(&fixture, id).await; + let (status, value) = command( + &fixture, + clerk(), + id, + "revise", + "renew-revise", + json!({"input":{"licence":licence,"statement":"Renewal"}}), + ) + .await; + assert_eq!(status, StatusCode::OK, "{value}"); + // Move the holder underneath BReg, as another writer of the register + // would, without disclosing anything to the submitter. + let licence_id = Uuid::parse_str(&licence).unwrap(); + let located = fixture + .database + .admin + .query_one( + "SELECT format('%I.%I', c.table_schema, c.table_name), quote_ident(c.column_name) + FROM information_schema.columns c + WHERE c.table_name LIKE 'breg_e_licence%' AND c.column_name LIKE '%holder%'", + &[], + ) + .await + .unwrap(); + let (table, column): (String, String) = (located.get(0), located.get(1)); + let moved = fixture + .database + .admin + .execute( + &format!("UPDATE {table} SET {column}=$2 WHERE record_id=$1"), + &[&licence_id, &NEIGHBOUR], + ) + .await + .unwrap(); + assert_eq!(moved, 1); + let (status, refused) = + command(&fixture, clerk(), id, "submit", "renew-resubmit", json!({})).await; + assert_eq!(status, StatusCode::CONFLICT, "{refused}"); + assert_eq!(refused["code"], "proposal.subject-changed"); + fixture.finish().await; +} + +#[tokio::test] +async fn only_a_person_acting_for_themselves_is_matched_as_the_subject() { + let fixture = fixture().await; + let id = filed(&fixture, clerk(), CITIZEN, "people-only").await; + let follower = |kind| person(CITIZEN, "licence:follow", kind); + let (status, _, followed) = get(&fixture, follower(ActorKind::Human), id).await; + assert_eq!(status, StatusCode::OK, "{followed}"); + assert_eq!(followed["partyRole"], "subject"); + // A standing agent is refused at admission, before any Proposal is + // read; a service is admitted and never matched as the subject. + for (kind, expected) in [ + (ActorKind::Agent, StatusCode::FORBIDDEN), + (ActorKind::Service, StatusCode::NOT_FOUND), + ] { + let (status, _, refused) = get(&fixture, follower(kind), id).await; + assert_eq!(status, expected, "{kind:?}: {refused}"); + assert!(refused.get("partyRole").is_none()); + let (status, _, page) = request( + &fixture, + follower(kind), + "GET", + "/v1/proposals", + None, + None, + Value::Null, + ) + .await; + assert!( + status != StatusCode::OK || page["items"] == json!([]), + "{kind:?}: {page}" + ); + } + fixture.finish().await; +} + +#[tokio::test] +async fn audit_names_the_subject_by_pseudonym_and_each_later_request_by_party() { + let fixture = fixture().await; + let id = filed(&fixture, clerk(), CITIZEN, "audited").await; + let (status, _, _) = get(&fixture, citizen(CITIZEN), id).await; + assert_eq!(status, StatusCode::OK); + let entries = fixture.audit_capture.entries(); + let text = serde_json::to_string(&entries).unwrap(); + assert!( + !text.contains(CITIZEN), + "the subject identifier reached audit" + ); + let stored: Option = fixture + .database + .admin + .query_one( + "SELECT subject_reference FROM registry_internal.registry_proposal_state WHERE proposal_id=$1", + &[&id], + ) + .await + .unwrap() + .get(0); + let stored = stored.expect("the subject is bound at Submit"); + assert!( + !text.contains(&stored), + "the internal subject reference reached audit" + ); + let submit = entries + .iter() + .rev() + .find(|entry| entry.to_string().contains("subjectPseudonym")) + .unwrap_or_else(|| panic!("no audit entry carries the subject pseudonym: {text}")); + assert!(submit.to_string().contains("submit"), "{submit}"); + let read = entries.last().unwrap(); + assert!( + read.to_string().contains("\"partyRole\":\"subject\""), + "{read}" + ); + fixture.finish().await; +} + +#[allow(clippy::too_many_arguments)] +async fn request_bytes( + fixture: &client_http::ClientFixture, + caller: VerifiedRequestClaims, + method: &str, + path: &str, + etag: Option<&str>, + key: Option<&str>, + content_type: &str, + body: Vec, +) -> (StatusCode, Vec) { + use tower::ServiceExt; + let mut req = axum::http::Request::builder() + .method(method) + .uri(path) + .header("content-type", content_type); + if let Some(etag) = etag { + req = req.header("if-match", etag); + } + if let Some(key) = key { + req = req.header("idempotency-key", key); + } + let response = registry_breg::api::router(fixture.service()) + .layer(axum::Extension(caller)) + .oneshot(req.body(axum::body::Body::from(body)).unwrap()) + .await + .unwrap(); + let status = response.status(); + let bytes = axum::body::to_bytes(response.into_body(), 1 << 22) + .await + .unwrap() + .to_vec(); + (status, bytes) +} + +/// A draft `caller` started naming `holder`, with `id-scan` uploaded, then +/// submitted. +async fn filed_with_scan( + fixture: &client_http::ClientFixture, + caller: VerifiedRequestClaims, + holder: &str, + key: &str, +) -> Uuid { + let id = start( + fixture, + caller.clone(), + "apply-for-licence", + json!({"holder":holder,"statement":"Officer-only statement"}), + &format!("{key}-start"), + ) + .await; + let (_, etag, _) = get(fixture, caller.clone(), id).await; + let (status, body) = request_bytes( + fixture, + caller.clone(), + "PATCH", + &format!("/v1/proposals/{id}/attachments/id-scan"), + etag.as_deref(), + Some(&format!("{key}-scan")), + "text/plain", + b"identity scan canary".to_vec(), + ) + .await; + assert_eq!(status, StatusCode::OK, "{}", String::from_utf8_lossy(&body)); + let (status, value) = command( + fixture, + caller, + id, + "submit", + &format!("{key}-submit"), + json!({}), + ) + .await; + assert_eq!(status, StatusCode::OK, "{value}"); + id +} + +async fn download_scan( + fixture: &client_http::ClientFixture, + caller: VerifiedRequestClaims, + id: Uuid, +) -> (StatusCode, Vec) { + request_bytes( + fixture, + caller, + "GET", + &format!("/v1/proposals/{id}/attachments/id-scan?submissionVersion=1"), + None, + None, + "application/json", + Vec::new(), + ) + .await +} + +#[tokio::test] +async fn attachment_downloads_follow_the_entry_that_admitted_the_caller() { + let fixture = fixture().await; + let id = filed_with_scan(&fixture, clerk(), CITIZEN, "scan-subject").await; + // The subject entry reads no attachment, whatever the owner entry reads. + let (_, _, followed) = get(&fixture, citizen(CITIZEN), id).await; + assert!(followed.get("attachments").is_none(), "{followed}"); + let (status, bytes) = download_scan(&fixture, citizen(CITIZEN), id).await; + assert_eq!(status, StatusCode::NOT_FOUND); + assert!(!String::from_utf8_lossy(&bytes).contains("canary")); + // The filer's owner entry reads it. + let (status, bytes) = download_scan(&fixture, clerk(), id).await; + assert_eq!(status, StatusCode::OK); + assert_eq!(bytes, b"identity scan canary"); + fixture.finish().await; + + // Authored the other way round: the subject entry reads the slot and + // the owner entry does not, so a self-filer reads nothing. + let mut swapped = source(); + let entries = swapped["accessProfiles"]["citizen"]["permissions"]["proposals"] + .as_array_mut() + .unwrap(); + entries[0]["readableAttachments"] = json!([]); + entries[1]["readableAttachments"] = json!(["id-scan"]); + entries.swap(0, 1); + let fixture = fixture_from(&swapped).await; + let own = filed_with_scan(&fixture, citizen(CITIZEN), CITIZEN, "scan-owner").await; + let (status, _) = download_scan(&fixture, citizen(CITIZEN), own).await; + assert_eq!(status, StatusCode::NOT_FOUND); + let followed = filed_with_scan(&fixture, clerk(), CITIZEN, "scan-followed").await; + let (status, bytes) = download_scan(&fixture, citizen(CITIZEN), followed).await; + assert_eq!(status, StatusCode::OK); + assert_eq!(bytes, b"identity scan canary"); + fixture.finish().await; +} + +#[tokio::test] +async fn the_subject_reads_review_status() { + let fixture = fixture().await; + let id = filed(&fixture, clerk(), CITIZEN, "subject-status").await; + let (status, _, value) = request( + &fixture, + citizen(CITIZEN), + "GET", + &format!("/v1/proposals/{id}/review-status"), + None, + None, + Value::Null, + ) + .await; + assert_eq!(status, StatusCode::OK, "{value}"); + let (status, _, _) = request( + &fixture, + citizen(NEIGHBOUR), + "GET", + &format!("/v1/proposals/{id}/review-status"), + None, + None, + Value::Null, + ) + .await; + assert_eq!(status, StatusCode::NOT_FOUND); + fixture.finish().await; +} + +/// The subject of `renew-licence` is bounded to licences that name them. +fn bounded_subject_source() -> Value { + let mut project = source(); + for entry in project["accessProfiles"]["citizen"]["permissions"]["proposals"] + .as_array_mut() + .unwrap() + { + if entry["action"] == "renew-licence" && entry["party"] == "subject" { + entry["targets"] = json!([{"recordType":"licence","rowBoundaries": + [{"field":"holder","claim":"holder_ref","operator":"equals"}]}]); + } + } + project +} + +/// A citizen whose token also carries the identifier licences name them by. +fn bounded_citizen(principal: &str) -> VerifiedRequestClaims { + VerifiedRequestClaims::authenticated_with_actor_kind( + "sub", + principal, + BTreeSet::from(["licence:self".to_owned()]), + Some("licence-portal".into()), + BTreeMap::from([( + "holder_ref".to_owned(), + registry_breg::api::VerifiedClaimValue::direct_string(principal).unwrap(), + )]), + ActorKind::Human, + ) + .unwrap() +} + +async fn seed_licence(fixture: &client_http::ClientFixture, holder: &str, key: &str) -> String { + let client = &fixture.http.client; + let metadata = client.registry_contract(Some("admin")).await.unwrap(); + let BRegDirectWrite::Create(create) = metadata + .value + .select_direct_write("records.licence.create", "admin") + .unwrap() + else { + panic!("create") + }; + client + .create_record( + &create, + &BRegCreateRequest::new(json!({"holder":holder}).as_object().unwrap().clone()).unwrap(), + &BRegIdempotencyKey::parse(key).unwrap(), + BRegRecordFormat::Json, + ) + .await + .unwrap() + .value + .data + .record_id +} + +async fn move_holder(fixture: &client_http::ClientFixture, licence: &str, holder: &str) { + let located = fixture + .database + .admin + .query_one( + "SELECT format('%I.%I', c.table_schema, c.table_name), quote_ident(c.column_name) + FROM information_schema.columns c + WHERE c.table_name LIKE 'breg_e_licence%' AND c.column_name LIKE '%holder%'", + &[], + ) + .await + .unwrap(); + let (table, column): (String, String) = (located.get(0), located.get(1)); + let moved = fixture + .database + .admin + .execute( + &format!("UPDATE {table} SET {column}=$2 WHERE record_id=$1"), + &[&Uuid::parse_str(licence).unwrap(), &holder], + ) + .await + .unwrap(); + assert_eq!(moved, 1); +} + +#[tokio::test] +async fn a_subject_outside_the_row_boundary_learns_nothing() { + let fixture = fixture_from(&bounded_subject_source()).await; + let licence = seed_licence(&fixture, CITIZEN, "bounded-seed").await; + let id = start( + &fixture, + clerk(), + "renew-licence", + json!({"licence":licence,"statement":"Desk renewal"}), + "bounded-renew", + ) + .await; + let (status, value) = + command(&fixture, clerk(), id, "submit", "bounded-submit", json!({})).await; + assert_eq!(status, StatusCode::OK, "{value}"); + let revise = |key: &'static str, target: Uuid| { + let fixture = &fixture; + let licence = licence.clone(); + async move { + request( + fixture, + bounded_citizen(CITIZEN), + "POST", + &format!("/v1/proposals/{target}/revise"), + Some("\"breg-proposal-guess\""), + Some(key), + json!({"input":{"licence":licence}}), + ) + .await + } + }; + // Within reach, the subject reads it and is told the operation is not theirs. + let (status, _, _) = get(&fixture, bounded_citizen(CITIZEN), id).await; + assert_eq!(status, StatusCode::OK); + let (status, _, refused) = revise("bounded-revise-in", id).await; + assert_eq!(status, StatusCode::FORBIDDEN, "{refused}"); + // Out of reach, every operation answers as an unknown Proposal does. + move_holder(&fixture, &licence, NEIGHBOUR).await; + let (status, _, _) = get(&fixture, bounded_citizen(CITIZEN), id).await; + assert_eq!(status, StatusCode::NOT_FOUND); + let (status, _, _) = revise("bounded-revise-out", id).await; + assert_eq!(status, StatusCode::NOT_FOUND); + let (status, _, _) = revise("bounded-revise-unknown", Uuid::new_v4()).await; + assert_eq!(status, StatusCode::NOT_FOUND); + assert!(list(&fixture, bounded_citizen(CITIZEN), "") + .await + .is_empty()); + fixture.finish().await; +} + +#[tokio::test] +async fn a_self_service_field_submit_answers_alike_for_an_empty_or_another_holder() { + let fixture = fixture().await; + for (holder, key) in [("", "empty-holder"), (NEIGHBOUR, "other-holder")] { + let licence = seed_licence(&fixture, holder, &format!("{key}-seed")).await; + let id = start( + &fixture, + citizen(CITIZEN), + "renew-licence", + json!({"licence":licence,"statement":"Self renewal"}), + &format!("{key}-start"), + ) + .await; + let (status, refused) = command( + &fixture, + citizen(CITIZEN), + id, + "submit", + &format!("{key}-submit"), + json!({}), + ) + .await; + assert_eq!(status, StatusCode::FORBIDDEN, "{key}: {refused}"); + assert_eq!(refused["code"], "proposal.subject-not-caller", "{key}"); + } + fixture.finish().await; +} + +#[tokio::test] +async fn a_submit_replay_neither_rebinds_nor_reveals() { + let fixture = fixture().await; + let id = start( + &fixture, + clerk(), + "apply-for-licence", + json!({"holder":CITIZEN,"statement":"Replayed statement"}), + "replay-start", + ) + .await; + let (_, etag, _) = get(&fixture, clerk(), id).await; + let path = format!("/v1/proposals/{id}/submit"); + let submit = || { + request( + &fixture, + clerk(), + "POST", + &path, + etag.as_deref(), + Some("replay-submit"), + json!({}), + ) + }; + let (first, _, original) = submit().await; + assert_eq!(first, StatusCode::OK, "{original}"); + let bound: Option = fixture + .database + .admin + .query_one( + "SELECT subject_reference FROM registry_internal.registry_proposal_state WHERE proposal_id=$1", + &[&id], + ) + .await + .unwrap() + .get(0); + let (again, _, replayed) = submit().await; + assert_eq!(again, StatusCode::OK, "{replayed}"); + assert_eq!(replayed["submissionVersion"], original["submissionVersion"]); + let after: Option = fixture + .database + .admin + .query_one( + "SELECT subject_reference FROM registry_internal.registry_proposal_state WHERE proposal_id=$1", + &[&id], + ) + .await + .unwrap() + .get(0); + assert_eq!(bound, after); + fixture.finish().await; +} + +#[tokio::test] +async fn a_stored_subject_input_that_drifts_is_refused_at_submit() { + let fixture = fixture().await; + let id = filed(&fixture, clerk(), CITIZEN, "input-drift").await; + request_changes(&fixture, id).await; + let (status, value) = command( + &fixture, + clerk(), + id, + "revise", + "input-drift-revise", + json!({"input":{"holder":CITIZEN,"statement":"Revised"}}), + ) + .await; + assert_eq!(status, StatusCode::OK, "{value}"); + // Model a stored input no command could write, such as one carried over + // from an earlier Action contract. + fixture + .database + .admin + .execute( + "UPDATE registry_internal.registry_proposal_state SET input=jsonb_set(input,'{holder}',to_jsonb($2::text)) WHERE proposal_id=$1", + &[&id, &NEIGHBOUR], + ) + .await + .unwrap(); + let (status, refused) = command( + &fixture, + clerk(), + id, + "submit", + "input-drift-resubmit", + json!({}), + ) + .await; + assert_eq!(status, StatusCode::CONFLICT, "{refused}"); + assert_eq!(refused["code"], "proposal.subject-changed"); + let (status, _, _) = get(&fixture, citizen(NEIGHBOUR), id).await; + assert_eq!(status, StatusCode::NOT_FOUND); + fixture.finish().await; +} + +#[tokio::test] +async fn erasing_a_proposals_detail_forgets_its_subject() { + let mut project = source(); + project["actions"]["apply-for-licence"]["execution"]["proposal"]["retention"] = + json!({"mode":"operator-erase"}); + let fixture = fixture_from(&project).await; + let id = filed(&fixture, clerk(), CITIZEN, "erased").await; + let (status, value) = command( + &fixture, + citizen(CITIZEN), + id, + "cancel", + "erased-cancel", + json!({}), + ) + .await; + assert_eq!(status, StatusCode::OK, "{value}"); + let (mut migration, task) = fixture.database.connect_migration().await; + registry_breg::proposal_retention::erase_proposal_detail( + &mut migration, + &fixture.registry, + registry_breg::proposal_retention::ProposalDetailErasureScope { + action_id: "apply-for-licence", + proposal_id: id, + submission_version: 1, + }, + ) + .await + .unwrap(); + drop(migration); + task.abort(); + let stored: Option = fixture + .database + .admin + .query_one( + "SELECT subject_reference FROM registry_internal.registry_proposal_state WHERE proposal_id=$1", + &[&id], + ) + .await + .unwrap() + .get(0); + assert_eq!( + stored, None, + "an erased Proposal keeps no recoverable subject" + ); + // The subject no longer follows it; the filer still reads its state. + let (status, _, _) = get(&fixture, citizen(CITIZEN), id).await; + assert_eq!(status, StatusCode::NOT_FOUND); + let (status, _, filer) = get(&fixture, clerk(), id).await; + assert_eq!(status, StatusCode::OK, "{filer}"); + fixture.finish().await; +} + +#[tokio::test] +async fn a_subject_cannot_probe_a_hidden_reference_with_the_target_filter() { + let mut project = source(); + for entry in project["accessProfiles"]["citizen"]["permissions"]["proposals"] + .as_array_mut() + .unwrap() + { + if entry["action"] == "renew-licence" && entry["party"] == "subject" { + entry["readableInputs"] = json!([]); + } + } + let fixture = fixture_from(&project).await; + let licence = seed_licence(&fixture, CITIZEN, "hidden-seed").await; + let id = start( + &fixture, + clerk(), + "renew-licence", + json!({"licence":licence,"statement":"Desk renewal"}), + "hidden-renew", + ) + .await; + let (status, value) = + command(&fixture, clerk(), id, "submit", "hidden-submit", json!({})).await; + assert_eq!(status, StatusCode::OK, "{value}"); + assert_eq!(list(&fixture, citizen(CITIZEN), "").await.len(), 1); + assert!( + list(&fixture, citizen(CITIZEN), &format!("?target={licence}")) + .await + .is_empty(), + "the filter matched a reference the subject entry hides" + ); + // The desk reads the licence input, so its filter still matches. + assert_eq!( + list(&fixture, clerk(), &format!("?target={licence}")) + .await + .len(), + 1 + ); + fixture.finish().await; +} + +#[tokio::test] +async fn a_list_audits_each_party_with_its_own_count() { + let fixture = fixture().await; + filed(&fixture, citizen(CITIZEN), CITIZEN, "own-listed").await; + filed(&fixture, clerk(), CITIZEN, "followed-listed").await; + filed(&fixture, clerk(), CITIZEN, "followed-listed-again").await; + assert_eq!(list(&fixture, citizen(CITIZEN), "").await.len(), 3); + let entries = fixture.audit_capture.entries(); + let counts = entries + .iter() + .filter(|entry| { + entry["record"]["operationId"] == "proposals.apply-for-licence.list" + && entry["record"]["phase"] == "terminal" + }) + .map(|entry| { + ( + entry["record"]["partyRole"] + .as_str() + .unwrap_or("none") + .to_owned(), + entry["record"]["resultCount"].as_u64().unwrap(), + ) + }) + .collect::>(); + assert_eq!( + counts, + BTreeMap::from([("owner".to_owned(), 1), ("subject".to_owned(), 2)]), + "{entries:?}" + ); + fixture.finish().await; +} + +#[tokio::test] +async fn a_subjects_pages_hold_only_their_own_proposals() { + let fixture = fixture().await; + let mut mine = BTreeSet::new(); + for (holder, key) in [ + (CITIZEN, "paged-a"), + (NEIGHBOUR, "paged-b"), + (CITIZEN, "paged-c"), + (NEIGHBOUR, "paged-d"), + (CITIZEN, "paged-e"), + ] { + let id = filed(&fixture, clerk(), holder, key).await; + if holder == CITIZEN { + mine.insert(id.to_string()); + } + } + let mut seen = BTreeSet::new(); + let mut query = "?limit=1".to_owned(); + for _ in 0..10 { + let (status, _, page) = request( + &fixture, + citizen(CITIZEN), + "GET", + &format!("/v1/proposals{query}"), + None, + None, + Value::Null, + ) + .await; + assert_eq!(status, StatusCode::OK, "{page}"); + for item in page["items"].as_array().unwrap() { + assert_eq!(item["partyRole"], "subject"); + assert!(seen.insert(item["id"].as_str().unwrap().to_owned())); + } + match page["nextCursor"].as_str() { + Some(cursor) => query = format!("?limit=1&cursor={cursor}"), + None => break, + } + } + assert_eq!(seen, mine); + fixture.finish().await; +} + +#[tokio::test] +async fn a_reference_read_only_for_its_subject_binds_at_submit() { + let fixture = fixture().await; + let original = seed_licence(&fixture, CITIZEN, "copy-seed").await; + let id = start( + &fixture, + clerk(), + "issue-copy", + json!({"original":original,"copyHolder":"Copy holder"}), + "copy-start", + ) + .await; + let (status, value) = command(&fixture, clerk(), id, "submit", "copy-submit", json!({})).await; + assert_eq!(status, StatusCode::OK, "{value}"); + let bound: Option = fixture + .database + .admin + .query_one( + "SELECT subject_reference FROM registry_internal.registry_proposal_state WHERE proposal_id=$1", + &[&id], + ) + .await + .unwrap() + .get(0); + assert!( + bound.is_some(), + "the subject was read from the referenced Record" + ); + fixture.finish().await; +} + +/// Accept the current review round and open one ask the party may answer. +async fn open_ask(fixture: &client_http::ClientFixture, id: Uuid) -> Uuid { + let row = fixture + .database + .admin + .query_one( + "SELECT create_request,expected_submission_digest FROM registry_internal.registry_proposal_review_submissions + WHERE proposal_id=$1 ORDER BY submission_version DESC LIMIT 1", + &[&id], + ) + .await + .unwrap(); + let create: registry_review_client::ReviewCreateRequest = + serde_json::from_value(row.get(0)).unwrap(); + let accepted = registry_review_client::ReviewRequestAccepted { + request_id: Uuid::new_v4(), + subject: create.subject, + policy: serde_json::from_value(json!({"id":"licence-review","version":"1","digest":format!("sha256:{}","b".repeat(64))})).unwrap(), + submission_digest: serde_json::from_value(json!(row.get::<_, String>(1))).unwrap(), + }; + fixture + .database + .admin + .execute( + "UPDATE registry_internal.registry_proposal_review_submissions SET state='accepted',accepted_binding=$2 + WHERE proposal_id=$1", + &[&id, &serde_json::to_value(&accepted).unwrap()], + ) + .await + .unwrap(); + let ask = Uuid::new_v4(); + let asked_at = chrono::Utc::now(); + fixture + .database + .admin + .execute( + "INSERT INTO registry_internal.registry_proposal_review_asks + (authority,review_request_id,ask_id,action_id,proposal_id,submission_version,text,wants,asked_at,asked_at_wire,state) + VALUES ('local-review',$1,$2,'apply-for-licence',$3,1,'Synthetic question',$4,$5,$6,'open')", + &[&accepted.request_id, &ask, &id, &json!([{"kind":"answer"}]), &asked_at, &asked_at.to_rfc3339()], + ) + .await + .unwrap(); + ask +} + +#[tokio::test] +async fn the_subject_answers_an_ask_and_adds_a_file() { + let fixture = fixture().await; + let id = filed(&fixture, clerk(), CITIZEN, "answering").await; + let ask = open_ask(&fixture, id).await; + + // A neighbour reaches neither command. + let answer_path = format!("/v1/proposals/{id}/asks/{ask}/answer"); + let (status, _, _) = request( + &fixture, + citizen(NEIGHBOUR), + "POST", + &answer_path, + Some("\"breg-proposal-guess\""), + Some("neighbour-answer"), + json!({"text":"Not mine to answer"}), + ) + .await; + assert_eq!(status, StatusCode::NOT_FOUND); + + let (status, etag, followed) = get(&fixture, citizen(CITIZEN), id).await; + assert_eq!(status, StatusCode::OK); + assert_eq!(followed["asks"][0]["id"], ask.to_string(), "{followed}"); + let (status, _, answered) = request( + &fixture, + citizen(CITIZEN), + "POST", + &answer_path, + etag.as_deref(), + Some("subject-answer"), + json!({"text":"Answered by the person it is about"}), + ) + .await; + assert_eq!(status, StatusCode::OK, "{answered}"); + assert_eq!(answered["partyRole"], "subject"); + + let (_, etag, _) = get(&fixture, citizen(CITIZEN), id).await; + let (status, body) = request_bytes( + &fixture, + citizen(CITIZEN), + "POST", + &format!("/v1/proposals/{id}/additions/other"), + etag.as_deref(), + Some("subject-add"), + "text/plain", + b"supporting letter".to_vec(), + ) + .await; + assert_eq!(status, StatusCode::OK, "{}", String::from_utf8_lossy(&body)); + let (status, body) = request_bytes( + &fixture, + citizen(NEIGHBOUR), + "POST", + &format!("/v1/proposals/{id}/additions/other"), + Some("\"breg-proposal-guess\""), + Some("neighbour-add"), + "text/plain", + b"not mine".to_vec(), + ) + .await; + assert_eq!( + status, + StatusCode::NOT_FOUND, + "{}", + String::from_utf8_lossy(&body) + ); + fixture.finish().await; +} + +/// Each entry order and each readability split: the self-filer reads the +/// slot exactly when the owner entry does, the subject exactly when the +/// subject entry does. +#[tokio::test] +async fn attachment_reads_follow_the_party_in_either_entry_order() { + for subject_first in [false, true] { + for owner_reads in [true, false] { + let mut project = source(); + let entries = project["accessProfiles"]["citizen"]["permissions"]["proposals"] + .as_array_mut() + .unwrap(); + assert_eq!(entries[0]["party"], "owner"); + assert_eq!(entries[1]["party"], "subject"); + entries[0]["readableAttachments"] = + json!(if owner_reads { vec!["id-scan"] } else { vec![] }); + entries[1]["readableAttachments"] = + json!(if owner_reads { vec![] } else { vec!["id-scan"] }); + if subject_first { + entries.swap(0, 1); + } + let fixture = fixture_from(&project).await; + let tag = format!("{subject_first}-{owner_reads}"); + let own = filed_with_scan( + &fixture, + citizen(CITIZEN), + CITIZEN, + &format!("matrix-own-{tag}"), + ) + .await; + let followed = filed_with_scan( + &fixture, + clerk(), + CITIZEN, + &format!("matrix-followed-{tag}"), + ) + .await; + let (own_status, own_bytes) = download_scan(&fixture, citizen(CITIZEN), own).await; + let (followed_status, followed_bytes) = + download_scan(&fixture, citizen(CITIZEN), followed).await; + let (reader, reader_bytes, refused, refused_bytes) = if owner_reads { + (own_status, own_bytes, followed_status, followed_bytes) + } else { + (followed_status, followed_bytes, own_status, own_bytes) + }; + assert_eq!(reader, StatusCode::OK, "{tag}"); + assert_eq!(reader_bytes, b"identity scan canary", "{tag}"); + assert_eq!(refused, StatusCode::NOT_FOUND, "{tag}"); + assert!( + !String::from_utf8_lossy(&refused_bytes).contains("canary"), + "{tag}" + ); + fixture.finish().await; + } + } +} diff --git a/crates/registry-breg/tests/postgres_proposal_task_authority.rs b/crates/registry-breg/tests/postgres_proposal_task_authority.rs index 1f214854e1..18598ba274 100644 --- a/crates/registry-breg/tests/postgres_proposal_task_authority.rs +++ b/crates/registry-breg/tests/postgres_proposal_task_authority.rs @@ -119,7 +119,7 @@ fn registry(automatic: bool, reviewed: bool) -> registry_breg::CompiledRegistry "proposals":[{ "action":"correct-name", "operations":["get","edit","submit","retry","cancel","apply"], - "ownership":"caller", + "party":"owner", "readableInputs":["target","value"], "targets":[{"recordType":"target","rowBoundaries":[{"field":"jurisdiction","claim":"jurisdiction","operator":"equals"}]}] }] @@ -141,7 +141,7 @@ fn registry(automatic: bool, reviewed: bool) -> registry_breg::CompiledRegistry "proposals":[{ "action":"correct-name", "operations":["get","edit","submit","cancel"], - "ownership":"caller", + "party":"owner", "readableInputs":["target","value"], "targets":[{"recordType":"target","rowBoundaries":[{"field":"jurisdiction","claim":"jurisdiction","operator":"equals"}]}] }] 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 ab74ce3b1f..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