From fc3a0dfc9f8ffaa2abe8618212b8286b5dbb0d4d Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 15:50:47 +0000 Subject: [PATCH 1/3] test(casework): make dispatcher lease observation deterministic [skip ci] Signed-off-by: Jeremi Joslin --- .../tests/review_postgres.rs | 203 +++++++++++++----- 1 file changed, 148 insertions(+), 55 deletions(-) diff --git a/crates/registry-casework/tests/review_postgres.rs b/crates/registry-casework/tests/review_postgres.rs index 18fdd1f3f0..898f72a1ff 100644 --- a/crates/registry-casework/tests/review_postgres.rs +++ b/crates/registry-casework/tests/review_postgres.rs @@ -514,19 +514,20 @@ fn bind_request( request } +fn review_test_database_url() -> String { + env::var("CASEWORK_REVIEW_TEST_DATABASE_URL") + .expect("CASEWORK_REVIEW_TEST_DATABASE_URL is required for review PostgreSQL tests") +} + async fn fixture() -> Fixture { - let base = env::var("CASEWORK_REVIEW_TEST_DATABASE_URL") - .expect("CASEWORK_REVIEW_TEST_DATABASE_URL is required for review PostgreSQL tests"); + let base = review_test_database_url(); let schema = format!("review_{}", Uuid::new_v4().simple()); let application_name = format!("casework-review-{}", Uuid::new_v4().simple()); let separator = if base.contains('?') { '&' } else { '?' }; let scoped_url = format!( "{base}{separator}options=-csearch_path%3D{schema}&application_name={application_name}" ); - let (admin, admin_connection) = tokio_postgres::connect(&base, NoTls) - .await - .expect("connect dedicated review test database"); - tokio::spawn(async move { admin_connection.await.expect("admin connection") }); + let admin = connect_review_test_database(&base).await; admin .batch_execute(&format!("CREATE SCHEMA {schema}")) .await @@ -551,7 +552,7 @@ async fn fixture() -> Fixture { let store = PostgresStore::connect_runtime(&database_config, &secrets, None) .expect("runtime store") .with_audit(registry_casework::CaseworkAudit::capture().0); - let database = connect_scoped(&scoped_url).await; + let database = connect_review_test_database(&scoped_url).await; database .batch_execute( "INSERT INTO casework_teams(team_id,revision) VALUES('review-team',1); @@ -612,11 +613,11 @@ async fn fixture() -> Fixture { } } -async fn connect_scoped(url: &str) -> tokio_postgres::Client { +async fn connect_review_test_database(url: &str) -> tokio_postgres::Client { let (client, connection) = tokio_postgres::connect(url, NoTls) .await - .expect("schema connection"); - tokio::spawn(async move { connection.await.expect("schema connection task") }); + .expect("connect review test database"); + tokio::spawn(async move { connection.await.expect("review test database connection") }); client } @@ -696,50 +697,57 @@ async fn assert_terminal_atomic(fixture: &Fixture, request_id: Uuid, completion_ ); } -async fn assert_store_sessions_hold_no_transaction_or_row_lock(fixture: &Fixture) { - let sessions = fixture - .database - .query_one( - "SELECT count(*), - count(*) FILTER (WHERE xact_start IS NOT NULL), - count(*) FILTER (WHERE state <> 'idle') - FROM pg_stat_activity - WHERE datname=current_database() AND application_name=$1 - AND pid<>pg_backend_pid()", - &[&fixture.application_name], - ) - .await - .expect("inspect completion dispatcher database sessions"); - assert!(sessions.get::<_, i64>(0) > 0, "observe the dispatcher pool"); - assert_eq!( - sessions.get::<_, i64>(1), - 0, - "completion delivery must not retain an open database transaction" - ); - assert_eq!( - sessions.get::<_, i64>(2), - 0, - "completion delivery must leave its database sessions idle" - ); - - let row_locks: i64 = fixture - .database - .query_one( - "SELECT count(*) - FROM pg_locks l - JOIN pg_stat_activity a ON a.pid=l.pid - WHERE a.datname=current_database() AND a.application_name=$1 - AND a.pid<>pg_backend_pid() AND l.granted - AND l.locktype IN ('tuple','transactionid')", - &[&fixture.application_name], - ) - .await - .expect("inspect completion dispatcher row locks") - .get(0); - assert_eq!( - row_locks, 0, - "completion delivery must not retain a row or transaction-id lock" - ); +async fn wait_for_idle_store_sessions( + observer: &tokio_postgres::Client, + application_name: &str, + budget: std::time::Duration, +) -> Result<(), String> { + let mut last_observation = None; + tokio::time::timeout(budget, async { + loop { + // Each autocommit query takes a fresh activity snapshot. The backend + // can still report an active transaction briefly after commit returns. + let observation = observer + .query_one( + "WITH sessions AS MATERIALIZED ( + SELECT pid, xact_start, state + FROM pg_stat_activity + WHERE datname=current_database() AND application_name=$1 + AND pid<>pg_backend_pid() + ) + SELECT count(*), + count(*) FILTER (WHERE xact_start IS NOT NULL), + count(*) FILTER (WHERE state IS DISTINCT FROM 'idle'), + (SELECT count(*) FROM pg_locks l + JOIN sessions s ON s.pid=l.pid + WHERE l.granted AND l.locktype IN ('tuple','transactionid')) + FROM sessions", + &[&application_name], + ) + .await + .expect("inspect completion dispatcher database sessions and locks"); + let sessions: i64 = observation.get(0); + let transactions: i64 = observation.get(1); + let busy_sessions: i64 = observation.get(2); + let locks: i64 = observation.get(3); + if sessions > 0 && transactions == 0 && busy_sessions == 0 && locks == 0 { + return; + } + last_observation = Some((sessions, transactions, busy_sessions, locks)); + tokio::time::sleep(std::time::Duration::from_millis(25)).await; + } + }) + .await + .map_err(|_| { + let details = match last_observation { + Some((sessions, transactions, busy_sessions, locks)) => format!( + "sessions={sessions}, transactions={transactions}, busy_sessions={busy_sessions}, \ + tuple_or_transaction_id_locks={locks}" + ), + None => "no PostgreSQL activity observation completed".to_owned(), + }; + format!("timed out waiting for the dispatcher pool to be idle without transactions or locks ({details})") + }) } #[derive(Default)] @@ -1270,6 +1278,85 @@ async fn at_least_once_completion_durably_deduplicates_after_lost_ack_and_exhaus } } +#[tokio::test] +async fn completion_lease_observer_bounds_a_stalled_database_query() { + let fixture = fixture().await; + let blocker = connect_review_test_database(&review_test_database_url()).await; + let pid: i32 = fixture + .database + .query_one("SELECT pg_backend_pid()", &[]) + .await + .expect("read the observer backend PID") + .get(0); + blocker + .query_one("SELECT pg_advisory_lock(2828, $1)", &[&pid]) + .await + .expect("hold the observer's advisory lock"); + + let bounded = tokio::time::timeout(std::time::Duration::from_secs(5), async { + tokio::select! { + biased; + // Queue a lock wait ahead of the observer query on the same connection. + result = async { + fixture.database.query_one("SELECT pg_advisory_xact_lock(2828, $1)", &[&pid]).await + } => { + panic!("the queued query must remain blocked: {result:?}"); + } + result = wait_for_idle_store_sessions( + &fixture.database, + &fixture.application_name, + std::time::Duration::from_millis(250), + ) => result, + } + }) + .await; + let unlocked: bool = blocker + .query_one("SELECT pg_advisory_unlock(2828, $1)", &[&pid]) + .await + .expect("release the observer's advisory lock") + .get(0); + assert!(unlocked); + let diagnostic = bounded + .expect("the observer must finish while its database query is stalled") + .expect_err("a stalled observer must time out"); + assert!( + diagnostic.contains("no PostgreSQL activity observation completed"), + "expected the stalled query in the diagnostic: {diagnostic}" + ); +} + +#[tokio::test] +async fn completion_lease_observer_refuses_a_held_row_lock_until_rollback() { + let mut fixture = fixture().await; + let request_id = settle_review_for_completion(&fixture, "held-completion-row").await; + let observer = connect_review_test_database(&review_test_database_url()).await; + let transaction = fixture + .database + .transaction() + .await + .expect("begin row locker"); + transaction + .query_one( + "SELECT request_id FROM casework_review_completion_outbox + WHERE request_id=$1 FOR UPDATE", + &[&request_id], + ) + .await + .expect("lock the completion row"); + + let budget = std::time::Duration::from_secs(2); + let observed = wait_for_idle_store_sessions(&observer, &fixture.application_name, budget).await; + transaction.rollback().await.expect("release the row lock"); + let diagnostic = observed.expect_err("a held transaction must exhaust the observer timeout"); + assert!( + diagnostic.contains("transactions=1, busy_sessions=1, tuple_or_transaction_id_locks=1"), + "expected the held transaction and lock in the diagnostic: {diagnostic}" + ); + wait_for_idle_store_sessions(&observer, &fixture.application_name, budget) + .await + .expect("observe fresh idle activity after rollback"); +} + #[tokio::test] async fn completion_dispatcher_leases_one_at_a_time_and_fences_a_stale_owner() { let fixture = fixture().await; @@ -1329,7 +1416,13 @@ async fn completion_dispatcher_leases_one_at_a_time_and_fences_a_stale_owner() { ) .await .expect("completion receiver observes the first leased delivery"); - assert_store_sessions_hold_no_transaction_or_row_lock(&fixture).await; + wait_for_idle_store_sessions( + &fixture.database, + &fixture.application_name, + std::time::Duration::from_secs(2), + ) + .await + .unwrap_or_else(|diagnostic| panic!("{diagnostic}")); let first_pass_states = fixture .database .query( From dcec93009607d48396febee4ab1b8f47022ec11b Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 16:58:52 +0000 Subject: [PATCH 2/3] test(breg): prove holder renewal and crossed authority refusals Signed-off-by: Jeremi Joslin --- .../holder-authorized-action/README.md | 16 +++ .../dev-journeys.yaml | 12 ++ .../holder-authorized-action/dev.yaml | 26 ++++ .../holder-authorized-action/service.yaml | 12 ++ .../holder-authorized-action/verify.sh | 119 ++++++++++++++++++ 5 files changed, 185 insertions(+) create mode 100644 products/breg/fixtures/holder-authorized-action/README.md create mode 100644 products/breg/fixtures/holder-authorized-action/dev-journeys.yaml create mode 100644 products/breg/fixtures/holder-authorized-action/dev.yaml create mode 100644 products/breg/fixtures/holder-authorized-action/service.yaml create mode 100755 products/breg/fixtures/holder-authorized-action/verify.sh diff --git a/products/breg/fixtures/holder-authorized-action/README.md b/products/breg/fixtures/holder-authorized-action/README.md new file mode 100644 index 0000000000..a1f2f47f88 --- /dev/null +++ b/products/breg/fixtures/holder-authorized-action/README.md @@ -0,0 +1,16 @@ +# Holder-authorized renewal fixture + +Pass `verify.sh` the absolute paths to matching `rstack`, `breg`, and +`bregctl` binaries with named-role support. Then pass the medical-renewal +preview's `project` directory and a new private work directory. The script +copies the preview's Record types and Actions and starts disposable PostgreSQL +with Docker. + +The fixture exercises the served BReg routes with two holders and an officer. +A holder reads a target condition, renews their own licence and retries the same +command. The other licence's condition and write remain protected. The officer's +credential is refused on the holder profile. The other holder verifies that +the refused requests leave both the expiry and target condition unchanged. + +The separate holder-functions journey proves the function input and credential +boundary. This fixture reaches BReg directly. diff --git a/products/breg/fixtures/holder-authorized-action/dev-journeys.yaml b/products/breg/fixtures/holder-authorized-action/dev-journeys.yaml new file mode 100644 index 0000000000..e1967bc4fb --- /dev/null +++ b/products/breg/fixtures/holder-authorized-action/dev-journeys.yaml @@ -0,0 +1,12 @@ +# yaml-language-server: $schema=https://id.registrystack.org/schemas/rstack/journeys/journeys.v1alpha1.schema.json +apiVersion: id.registrystack.org/formats/rstack/journeys/v1alpha1 +kind: RStackJourneys +journeys: + - id: holder-profile + steps: + - id: holder-lists-licences + product: breg + as: holder + method: GET + path: /v1/records/licences + expect: {status: 200} diff --git a/products/breg/fixtures/holder-authorized-action/dev.yaml b/products/breg/fixtures/holder-authorized-action/dev.yaml new file mode 100644 index 0000000000..cb99483002 --- /dev/null +++ b/products/breg/fixtures/holder-authorized-action/dev.yaml @@ -0,0 +1,26 @@ +# yaml-language-server: $schema=https://id.registrystack.org/schemas/rstack/dev/dev.v1alpha1.schema.json +apiVersion: id.registrystack.org/formats/rstack/dev/v1alpha1 +kind: RStackDev +issuer: https://identity.licences.example.test +products: + - {product: breg, project: ., audience: "urn:example:licence-registry"} +people: + holder: + subject: 00000000-0000-4000-8000-000000000101 + client: licence-holder + roles: [licence-holder] + claims: + breg: {holder_ref: synthetic-doctor-holder} + officer: + subject: 00000000-0000-4000-8000-000000000102 + client: licence-officer + roles: [licence-officer] + claims: + breg: {jurisdiction: north} + other-holder: + subject: 00000000-0000-4000-8000-000000000103 + client: licence-holder + roles: [licence-holder] + claims: + breg: {holder_ref: synthetic-other-holder} +journeyFile: dev-journeys.yaml diff --git a/products/breg/fixtures/holder-authorized-action/service.yaml b/products/breg/fixtures/holder-authorized-action/service.yaml new file mode 100644 index 0000000000..8f1f73c816 --- /dev/null +++ b/products/breg/fixtures/holder-authorized-action/service.yaml @@ -0,0 +1,12 @@ +# yaml-language-server: $schema=https://id.registrystack.org/schemas/rstack/service/service.v1alpha1.schema.json +apiVersion: id.registrystack.org/formats/rstack/service/v1alpha1 +kind: RStackService +roles: + licence-holder: + actorKind: human + claims: [holder_ref] + accessProfiles: {breg: [licence-holder]} + licence-officer: + actorKind: human + claims: [jurisdiction] + accessProfiles: {breg: [licence-officer]} diff --git a/products/breg/fixtures/holder-authorized-action/verify.sh b/products/breg/fixtures/holder-authorized-action/verify.sh new file mode 100755 index 0000000000..36aaf51405 --- /dev/null +++ b/products/breg/fixtures/holder-authorized-action/verify.sh @@ -0,0 +1,119 @@ +#!/usr/bin/env bash +set -euo pipefail + +if [[ $# != 5 ]]; then + printf 'Usage: %s ABSOLUTE_RSTACK ABSOLUTE_BREG ABSOLUTE_BREGCTL ABSOLUTE_MEDICAL_PROJECT ABSOLUTE_NEW_WORK_DIR\n' "$0" >&2 + exit 2 +fi + +rstack="$1" +export RSTACK_BREG_BIN="$2" RSTACK_BREGCTL_BIN="$3" +donor="$4" +scratch="$5" +for path in "$rstack" "$RSTACK_BREG_BIN" "$RSTACK_BREGCTL_BIN" "$donor" "$scratch"; do + [[ "$path" = /* ]] +done +fixture="${BASH_SOURCE[0]%/*}" +mkdir -m 700 "$scratch" +cp -R "$donor" "$scratch/project" +cp "$fixture/dev.yaml" "$fixture/dev-journeys.yaml" "$fixture/service.yaml" "$scratch/project/" +unset RSTACK_DEV_DATABASE_URL RSTACK_DEV_DATABASE_CA +export RSTACK_DEV_STATE_DIR="$scratch/state" +dev=("$rstack" --install-root "$scratch/install" --format json dev) +run_id='' + +cleanup() { + if [[ -n "$run_id" ]]; then + "${dev[@]}" stop "$run_id" --clean >"$scratch/stop.json" + jq -e '.status == "stopped"' "$scratch/stop.json" >/dev/null + fi +} +trap cleanup EXIT + +"${dev[@]}" start "$scratch/project" --ttl 5m >"$scratch/start.json" +run_id="$(jq -er '.run_id' "$scratch/start.json")" +origin="$(jq -er '.products.breg' "$scratch/start.json")" +[[ "$origin" =~ ^http://127\.0\.0\.1:[0-9]+$ ]] + +credential_file() { + local actor="$1" file + file="$("${dev[@]}" token "$run_id" --as "$actor" | jq -er '.credentials[0].header_file')" || return + [[ "$file" = "$scratch/"* && -f "$file" ]] || return + printf '%s\n' "$file" +} + +holder="$(credential_file holder)" +other_holder="$(credential_file other-holder)" +officer="$(credential_file officer)" +response="$scratch/response.json" + +http() { + local credential="$1" method="$2" route="$3" expected="$4" body="${5:-}" key="${6:-}" + local status + local -a arguments=(--silent --show-error --noproxy '*' --max-time 10 --request "$method" + --header "@$credential" --output "$response" --write-out '%{http_code}') + if [[ -n "$body" ]]; then + arguments+=(--header 'Content-Type: application/json' --data "$body") + fi + if [[ -n "$key" ]]; then + arguments+=(--header "Idempotency-Key: $key") + fi + status="$(curl "${arguments[@]}" "$origin$route")" + if [[ "$status" != "$expected" ]]; then + printf 'Expected HTTP %s, received %s\n' "$expected" "$status" >&2 + jq -c '{code, status}' "$response" >&2 + return 1 + fi +} + +issue() { + local number="$1" holder_ref="$2" body + body="$(jq -cn --arg number "$number" --arg holder "$holder_ref" ' + {input:{licenceNumber:$number,holderRef:$holder,holderName:"Example Holder", + profession:"doctor",jurisdiction:"north",issuedOn:"2026-07-01",expiresOn:"2027-06-30"}} + ')" + http "$officer" POST '/v1/actions/issue?accessProfile=licence-officer' 200 "$body" "issue-$number" || return + jq -er '.results.licence.recordId' "$response" +} + +conditions() { + local credential="$1" licence="$2" expected="$3" body + body="$(jq -cn --arg id "$licence" '{input:{licenceId:$id}}')" + http "$credential" POST '/v1/actions/renew/target-conditions?accessProfile=licence-holder' "$expected" "$body" +} + +renewal() { + jq -cn --arg id "$1" --arg tag "$2" ' + {input:{licenceId:$id,newExpiresOn:"2028-06-30"},preconditions:{licenceId:{ifMatch:$tag}}} + ' +} + +own="$(issue MED-2026-001 synthetic-doctor-holder)" +foreign="$(issue MED-2026-002 synthetic-other-holder)" +[[ "$own" != "$foreign" ]] + +conditions "$holder" "$own" 200 +own_tag="$(jq -er '.preconditions.licenceId.ifMatch' "$response")" +own_body="$(renewal "$own" "$own_tag")" +renew='/v1/actions/renew?accessProfile=licence-holder' +http "$holder" POST "$renew" 200 "$own_body" renew-med-2026-001-to-2028 +http "$holder" POST "$renew" 200 "$own_body" renew-med-2026-001-to-2028 +http "$holder" GET "/v1/records/licences/$own?accessProfile=licence-holder" 200 +jq -e '.data.domainData.expiresOn == "2028-06-30"' "$response" >/dev/null + +conditions "$holder" "$foreign" 404 +jq -e '.code == "resource.not-found"' "$response" >/dev/null +conditions "$other_holder" "$foreign" 200 +foreign_tag="$(jq -er '.preconditions.licenceId.ifMatch' "$response")" +foreign_body="$(renewal "$foreign" "$foreign_tag")" +http "$holder" POST "$renew" 412 "$foreign_body" holder-crossed-record +jq -e '.code == "precondition.failed"' "$response" >/dev/null +http "$officer" POST "$renew" 403 "$foreign_body" officer-crossed-profile +jq -e '.code == "profile.not-authorized"' "$response" >/dev/null + +conditions "$other_holder" "$foreign" 200 +jq -e --arg original "$foreign_tag" '.preconditions.licenceId.ifMatch == $original' "$response" >/dev/null +http "$other_holder" GET "/v1/records/licences/$foreign?accessProfile=licence-holder" 200 +jq -e '.data.domainData.expiresOn == "2027-06-30"' "$response" >/dev/null + +printf '%s\n' 'Holder renewal and replay succeeded. Crossed target and profile refused. Foreign expiry and condition unchanged.' From 936b4848243a8870b42fe3687ccd8d905a3b68a5 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Tue, 1 Dec 2026 17:50:19 +0000 Subject: [PATCH 3/3] feat(rstack): bind holder preparation to one BReg action [skip ci] Signed-off-by: Jeremi Joslin --- clients/typescript/holder-function.ts | 132 +++++++++ .../typescript/tests/holder-function.test.ts | 279 ++++++++++++++++++ 2 files changed, 411 insertions(+) create mode 100644 clients/typescript/holder-function.ts create mode 100644 clients/typescript/tests/holder-function.test.ts diff --git a/clients/typescript/holder-function.ts b/clients/typescript/holder-function.ts new file mode 100644 index 0000000000..eb69f84a5a --- /dev/null +++ b/clients/typescript/holder-function.ts @@ -0,0 +1,132 @@ +import { RegistryError } from './core.ts' + +const uuid = /^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/u +const strongTag = /^"[\x21\x23-\x7e]{1,254}"$/u +const maximumRequestBytes = 32_768 +const bodyTooLarge = Symbol('body too large') + +interface HolderSubmission { + recordId: string + ifMatch: string + preparation: Preparation +} + +interface HolderCommand { + recordId: string + ifMatch: string + idempotencyKey: string + input: Input + signal: AbortSignal +} + +/** Host-owned parsing and invocation for one generated BReg Action and its fixed access profile. */ +interface HolderActionBinding { + path: string + parseSubmission: (body: unknown) => HolderSubmission | undefined + parsePreparation: (body: unknown) => Input | undefined + invoke: (credential: string, command: HolderCommand) => Promise<{ recordId: string }> +} + +function reply(body: object, status: number): Response { + return Response.json(body, { status, headers: { 'Cache-Control': 'no-store' } }) +} + +function parseJson(source: string): unknown { + const value: unknown = JSON.parse(source, (_key, member: unknown) => { + if (typeof member === 'number' && + (!Number.isFinite(member) || Number.isInteger(member) && !Number.isSafeInteger(member))) { + throw new SyntaxError('Unsupported JSON number.') + } + return member + }) + // On valid JSON, a quoted token followed by a colon is an object key. + // Decode the key before comparing so Unicode escapes cannot hide duplicates. + const objects: Set[] = [] + for (const [token, quoted, colon] of source.matchAll(/("(?:[^"\\]|\\.)*")(\s*:)?|[{}]/gu)) { + if (token === '{') objects.push(new Set()) + if (token === '}') objects.pop() + if (quoted && colon) { + const keys = objects.at(-1)! + const key: string = JSON.parse(quoted) + if (keys.has(key)) throw new SyntaxError('Duplicate JSON member.') + keys.add(key) + } + } + return value +} + +async function readSubmission(request: Request): Promise { + if (!request.body) return undefined + const reader = request.body.getReader() + const decoder = new TextDecoder('utf-8', { fatal: true }) + let bytes = 0 + let body = '' + try { + for (let chunk = await reader.read(); !chunk.done; chunk = await reader.read()) { + bytes += chunk.value.byteLength + if (bytes > maximumRequestBytes) { + await reader.cancel() + return bodyTooLarge + } + body += decoder.decode(chunk.value, { stream: true }) + } + return parseJson(body + decoder.decode()) + } finally { + reader.releaseLock() + } +} + +/** Use on the trusted invoker's gateway-only listener. Preparation must reproduce the same input on retry. */ +export function createHolderActionHandler( + { path, parseSubmission, parsePreparation, invoke }: HolderActionBinding, + prepare: (input: Preparation) => unknown | Promise, +): (request: Request) => Promise { + if (!/^\/api\/functions\/[a-z][a-z0-9_-]{0,63}$/u.test(path)) throw new TypeError('Expected a declared function path.') + + return async request => { + const url = new URL(request.url) + if (request.method !== 'POST' || url.pathname !== path || url.search || url.hash) { + return reply({ message: 'Unknown function route.' }, 404) + } + const credential = /^Bearer ([A-Za-z0-9._-]+)$/u.exec(request.headers.get('authorization') ?? '')?.[1] + if (!credential) return reply({ message: 'Sign in to continue.' }, 401) + + const idempotencyKey = request.headers.get('idempotency-key') + const mediaType = request.headers.get('content-type')?.split(';', 1)[0]?.trim().toLowerCase() + if (!idempotencyKey || !uuid.test(idempotencyKey.toLowerCase()) || mediaType !== 'application/json') { + return reply({ message: 'Send a JSON request with its attempt key.' }, 400) + } + let submission: HolderSubmission | undefined + try { + const body = await readSubmission(request) + if (body === bodyTooLarge) return reply({ message: 'The request is too large.' }, 413) + if (body !== undefined) submission = parseSubmission(body) + } catch { + return reply({ message: 'Send a valid JSON request.' }, 400) + } + if (!submission || !uuid.test(submission.recordId) || !strongTag.test(submission.ifMatch)) { + return reply({ message: 'Send a record and its reviewed condition.' }, 400) + } + const { recordId, ifMatch, preparation } = submission + + let input: Input | undefined + try { + request.signal.throwIfAborted() + input = parsePreparation(await prepare(preparation)) + } catch { + return reply({ message: 'The function could not prepare the request.' }, 502) + } + if (!input || request.signal.aborted) return reply({ message: 'The function could not prepare the request.' }, 502) + + try { + const result = await invoke(credential, { recordId, ifMatch, idempotencyKey, input, signal: request.signal }) + if (result.recordId === recordId) return reply({ recordId }, 200) + } catch (error) { + if (error instanceof RegistryError && error.kind === 'refused' && !error.outcomeUnknown && + error.status !== undefined && error.status >= 400 && error.status < 500) { + return reply({ message: 'BReg refused the request.' }, error.status) + } + } + return reply({ message: 'The Action outcome is unavailable. Retry the same attempt.' }, 502) + } +} diff --git a/clients/typescript/tests/holder-function.test.ts b/clients/typescript/tests/holder-function.test.ts new file mode 100644 index 0000000000..86abc8e5f4 --- /dev/null +++ b/clients/typescript/tests/holder-function.test.ts @@ -0,0 +1,279 @@ +import assert from 'node:assert/strict' +import test from 'node:test' +import { Transport, type Operation } from '../core.ts' +import { createHolderActionHandler } from '../holder-function.ts' + +const route = '/api/functions/renew' +const licenceId = 'c137aa49-8a74-4d63-9f38-47fde38b2949' +const otherLicenceId = 'a4d5b3fe-eaf4-456e-ae33-9ef6b85fa4b2' +const reviewedExpiresOn = '2027-06-30' +const newExpiresOn = '2028-06-30' +const ifMatch = '"reviewed-revision"' +const otherIfMatch = '"other-reviewed-revision"' +const idempotencyKey = '08114403-75d2-48d3-961a-5d4fb8b19687' +const holderAuthorization = 'Bearer synthetic-holder' +const submission = { licenceId, reviewedExpiresOn, preconditions: { licenceId: { ifMatch } } } +const holder = { subject: 'person-a', holderRef: 'holder-a', actor: 'human', client: 'licence-holder', + profile: 'licence-holder', audience: 'licences' } +const identities = new Map([ + [holderAuthorization, holder], + ['Bearer synthetic-other-subject', { ...holder, subject: 'person-b', holderRef: 'holder-b' }], + ['Bearer synthetic-agent', { ...holder, actor: 'agent' }], + ['Bearer synthetic-officer', { ...holder, profile: 'licence-officer' }], + ['Bearer synthetic-other-client', { ...holder, client: 'other' }], + ['Bearer synthetic-other-audience', { ...holder, audience: 'other' }], +]) +const records = new Map([[licenceId, { holderRef: 'holder-a', ifMatch }], + [otherLicenceId, { holderRef: 'holder-b', ifMatch: otherIfMatch }]]) +const otherSubmission = { ...submission, licenceId: otherLicenceId, preconditions: { licenceId: { ifMatch: otherIfMatch } } } + +const renewal: Operation = { + method: 'POST', path: '/v1/actions/renew', product: 'breg', + accessProfileParameter: true, accessProfileRequired: true, + keyed: true, mutating: true, requestMediaType: 'application/json', + problemValidators: { default: value => exactObject(value, ['code', 'detail', 'status']) }, + responses: { 200: [{ mode: 'json', mediaType: 'application/json' }] }, +} + +function exactObject(value: unknown, keys: readonly string[]): value is Record { + return value !== null && typeof value === 'object' && !Array.isArray(value) + && Object.keys(value).length === keys.length && keys.every(key => Object.hasOwn(value, key)) +} + +function parseSubmission(value: unknown) { + if (!exactObject(value, ['licenceId', 'reviewedExpiresOn', 'preconditions']) || + typeof value.licenceId !== 'string' || typeof value.reviewedExpiresOn !== 'string' || + !exactObject(value.preconditions, ['licenceId']) || !exactObject(value.preconditions.licenceId, ['ifMatch']) || + typeof value.preconditions.licenceId.ifMatch !== 'string') return undefined + return { + recordId: value.licenceId, ifMatch: value.preconditions.licenceId.ifMatch, + preparation: { reviewedExpiresOn: value.reviewedExpiresOn }, + } +} + +function parsePreparation(value: unknown) { + if (!exactObject(value, ['newExpiresOn']) || typeof value.newExpiresOn !== 'string') return undefined + return { newExpiresOn: value.newExpiresOn } +} + +function request(options: { path?: string; authorization?: string | null; body?: unknown; key?: string } = {}) { + const { path = route, authorization = holderAuthorization, body = submission, key = idempotencyKey } = options + const headers = new Headers({ + 'Content-Type': 'application/json', 'Idempotency-Key': key, + 'Registry-Client': 'page', Cookie: 'synthetic-cookie', 'X-Actor': 'synthetic-spoofed-actor', + }) + if (authorization !== null) headers.set('Authorization', authorization) + return new Request('https://service.test' + path, { method: 'POST', headers, body: JSON.stringify(body) }) +} + +function prepareRenewal({ reviewedExpiresOn }: { reviewedExpiresOn: string }) { + const year = Number(reviewedExpiresOn.slice(0, 4)) + return { newExpiresOn: String(year + 1) + reviewedExpiresOn.slice(4) } +} + +function setup(prepare: (input: { reviewedExpiresOn: string }) => unknown = prepareRenewal, + { loseFirstReceipt = false, parse = parseSubmission, receiptRecordId = '' } = {}, +) { + const preparations: unknown[][] = [] + const calls: { url: string; method: string | undefined; headers: Record; body: unknown }[] = [] + const writes: string[] = [] + const committed = new Map() + + const fetchProduct: typeof fetch = async (target, options) => { + const url = new URL(String(target)) + const headers = new Headers(options?.headers) + const body = JSON.parse(String(options?.body)) + calls.push({ url: url.href, method: options?.method, headers: Object.fromEntries(headers), body }) + if (url.pathname !== renewal.path || options?.method !== 'POST' || url.searchParams.get('accessProfile') !== 'licence-holder') { + throw new Error('The caller changed the checked Action contract.') + } + const refuse = (status: number, code = 'synthetic.refusal') => Response.json({ status, code, detail: 'product-only detail' }, + { status, headers: { 'Content-Type': 'application/problem+json' } }) + const identity = identities.get(headers.get('authorization') ?? '') + if (!identity || identity.audience !== 'licences') return refuse(401) + if (identity.actor !== 'human' || identity.client !== 'licence-holder' || identity.profile !== 'licence-holder') return refuse(403) + const record = records.get(body.input.licenceId) + if (record?.holderRef !== identity.holderRef || body.preconditions.licenceId.ifMatch !== record.ifMatch) return refuse(412) + if (body.input.newExpiresOn !== newExpiresOn) return refuse(412, 'synthetic.guard') + const receiptKey = identity.subject + ':' + headers.get('idempotency-key') + const command = JSON.stringify(body) + if (committed.has(receiptKey)) { + if (committed.get(receiptKey) !== command) return refuse(409) + return Response.json({ recordId: body.input.licenceId }) + } + committed.set(receiptKey, command) + writes.push(body.input.licenceId) + if (loseFirstReceipt && writes.length === 1) throw new Error('Simulated lost product receipt') + return Response.json({ recordId: receiptRecordId || body.input.licenceId, detail: 'product-only detail' }) + } + + const handle = createHolderActionHandler({ + path: route, + parseSubmission: parse, + parsePreparation, + async invoke(credential, command) { + const { recordId, ifMatch, input, idempotencyKey, signal } = command + const client = new Transport({ baseUrl: 'https://licences.test', token: () => credential, fetch: fetchProduct }) + const { data } = await client.call<{ recordId: string }>(renewal, { + query: { accessProfile: 'licence-holder' }, + body: { input: { licenceId: recordId, newExpiresOn: input.newExpiresOn }, preconditions: { licenceId: { ifMatch } } }, + idempotencyKey, + signal, + }) + return data + }, + }, (...args) => { + preparations.push(args) + return prepare(...args) + }) + return { handle, preparations, calls, writes } +} + +test('preparation receives one projected value and the checked Action receives the holder command', async () => { + const { handle, preparations, calls, writes } = setup() + const result = await handle(request()) + assert.equal(result.status, 200) + assert.deepEqual(await result.json(), { recordId: licenceId }) + assert.deepEqual(preparations, [[{ reviewedExpiresOn }]]) + assert.equal(calls.length, 1) + const call = calls[0]! + assert.equal(call.url, 'https://licences.test/v1/actions/renew?accessProfile=licence-holder') + assert.equal(call.method, 'POST') + assert.equal(call.headers.authorization, holderAuthorization) + assert.equal(call.headers['idempotency-key'], idempotencyKey) + for (const header of ['cookie', 'registry-client', 'x-actor']) assert.equal(call.headers[header], undefined) + assert.deepEqual(call.body, { input: { licenceId, newExpiresOn }, preconditions: { licenceId: { ifMatch } } }) + assert.deepEqual(writes, [licenceId]) +}) + +test('a missing caller or request outside the declared binding never reaches preparation or BReg', async () => { + const { handle, preparations, calls } = setup() + const cases = [ + [request({ authorization: null }), 401], + [request({ path: route + '/other' }), 404], + [request({ path: route + '?accessProfile=licence-officer' }), 404], + [request({ path: '/api/functions/issue' }), 404], + [request({ body: { ...submission, action: 'issue' } }), 400], + [request({ body: { ...submission, product: 'other' } }), 400], + [request({ body: { ...submission, accessProfile: 'licence-officer' } }), 400], + [request({ body: { ...submission, subject: 'other' } }), 400], + [request({ body: { ...submission, licenceId: licenceId.toUpperCase() } }), 400], + [request({ key: 'wrong' }), 400], + ] as const + for (const [incoming, expected] of cases) assert.equal((await handle(incoming)).status, expected) + assert.deepEqual(preparations, []) + assert.deepEqual(calls, []) +}) + +test('a preparation result outside its projection cannot substitute the target or invoke BReg', async () => { + const { handle, preparations, calls } = setup(() => ({ newExpiresOn, licenceId: otherLicenceId })) + assert.equal((await handle(request())).status, 502) + assert.deepEqual(preparations, [[{ reviewedExpiresOn }]]) + assert.deepEqual(calls, []) +}) + +test('a throwing submission parser returns a fixed refusal before preparation or BReg', async () => { + const { handle, preparations, calls } = setup(prepareRenewal, { + parse() { throw new Error('submitted values excluded from the reply') }, + }) + const response = await handle(request()) + assert.equal(response.status, 400) + assert.doesNotMatch(await response.text(), /submitted values/u) + assert.deepEqual(preparations, []) + assert.deepEqual(calls, []) +}) + +test('absent and oversized bodies are refused before the submission parser', async () => { + let parsed = 0 + const { handle, preparations, calls } = setup(prepareRenewal, { + parse() { parsed++; return parseSubmission(submission) }, + }) + const { url, headers, method } = request() + assert.equal((await handle(new Request(url, { headers, method }))).status, 400) + assert.equal((await handle(request({ body: 'x'.repeat(32_768) }))).status, 413) + assert.equal(parsed, 0) + assert.deepEqual(preparations, []) + assert.deepEqual(calls, []) +}) + +test('ambiguous request JSON is refused before the submission parser', async () => { + let parsed = 0 + const { handle, preparations, calls } = setup(prepareRenewal, { + parse() { parsed++; return parseSubmission(submission) }, + }) + const { url, headers, method } = request() + const cases = [ + '{"preconditions":{"licenceId":{"ifMatch":"a","ifM\\u0061tch":"b"}}}', + '{"input":9007199254740993}', + ] + for (const body of cases) assert.equal((await handle(new Request(url, { headers, method, body }))).status, 400) + assert.equal(parsed, 0) + assert.deepEqual(preparations, []) + assert.deepEqual(calls, []) +}) + +test('the owning product refuses a wrong subject, actor, role, client, audience, target, or condition', async () => { + const { handle, calls, writes } = setup() + const refusals = [ + [request({ authorization: 'Bearer synthetic-other-subject' }), 412], + [request({ authorization: 'Bearer synthetic-agent' }), 403], + [request({ authorization: 'Bearer synthetic-officer' }), 403], + [request({ authorization: 'Bearer synthetic-other-client' }), 403], + [request({ authorization: 'Bearer synthetic-other-audience' }), 401], + [request({ body: otherSubmission }), 412], + [request({ authorization: 'Bearer synthetic-other-subject', body: { ...submission, licenceId: otherLicenceId } }), 412], + [request({ body: { ...submission, preconditions: { licenceId: { ifMatch: '"stale-revision"' } } } }), 412], + ] as const + for (const [incoming, expected] of refusals) { + const response = await handle(incoming) + assert.equal(response.status, expected) + assert.doesNotMatch(await response.text(), /product-only detail|synthetic/u) + } + assert.equal(calls.length, refusals.length) + assert.deepEqual(writes, []) +}) + +test('overlapping requests keep each captured holder and exact target together', async () => { + const { handle, calls, writes } = setup() + const [first, second] = await Promise.all([ + handle(request()), + handle(request({ authorization: 'Bearer synthetic-other-subject', body: otherSubmission })), + ]) + assert.deepEqual([first.status, second.status], [200, 200]) + assert.deepEqual(await first.json(), { recordId: licenceId }) + assert.deepEqual(await second.json(), { recordId: otherLicenceId }) + assert.deepEqual(calls.map(call => call.headers.authorization).sort(), + [holderAuthorization, 'Bearer synthetic-other-subject'].sort()) + assert.deepEqual(writes.sort(), [licenceId, otherLicenceId].sort()) +}) + +test('a product refusal of the prepared value stays a refusal', async () => { + const { handle, calls, writes } = setup(() => ({ newExpiresOn: '2031-07-01' })) + const response = await handle(request()) + assert.equal(response.status, 412) + assert.deepEqual(await response.json(), { message: 'BReg refused the request.' }) + assert.equal(calls.length, 1) + assert.deepEqual(writes, []) +}) + +test('a product receipt for a different record leaves the original attempt unconfirmed', async () => { + const { handle, calls } = setup(prepareRenewal, { receiptRecordId: otherLicenceId }) + const response = await handle(request()) + assert.equal(response.status, 502) + assert.doesNotMatch(await response.text(), new RegExp(otherLicenceId, 'u')) + assert.equal(calls.length, 1) +}) + +test('after a lost product receipt the same renewal prepares the same command and reads back one effect', async () => { + const { handle, calls, preparations, writes } = setup(prepareRenewal, { loseFirstReceipt: true }) + const first = await handle(request()) + assert.equal(first.status, 502) + assert.doesNotMatch(await first.text(), /Simulated/u) + const retry = await handle(request()) + assert.equal(retry.status, 200) + assert.deepEqual(await retry.json(), { recordId: licenceId }) + assert.equal(calls.length, 2) + assert.deepEqual(calls[0], calls[1]) + assert.deepEqual(preparations, [[{ reviewedExpiresOn }], [{ reviewedExpiresOn }]]) + assert.deepEqual(writes, [licenceId]) +})