From 2217babe6655bfaec336c5eb75fbaf42c341cbbe Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Thu, 12 Nov 2026 19:29:20 +0700 Subject: [PATCH 01/40] feat: support payment collections as native workflow steps Signed-off-by: Jeremi Joslin --- .github/scripts/ci_changes.py | 3 + .github/scripts/test_ci_changes.py | 19 + AGENTS.md | 15 +- Cargo.lock | 53 ++ Cargo.toml | 6 + crates/registry-adapter/Cargo.toml | 12 + crates/registry-adapter/src/cli.rs | 52 +- crates/registry-adapter/src/lib.rs | 1 + crates/registry-adapter/src/main.rs | 6 +- .../registry-adapter/src/payments/config.rs | 200 ++++++ crates/registry-adapter/src/payments/http.rs | 389 ++++++++++++ crates/registry-adapter/src/payments/mod.rs | 9 + crates/registry-adapter/src/payments/model.rs | 223 +++++++ .../registry-adapter/src/payments/registry.rs | 326 ++++++++++ .../registry-adapter/src/payments/service.rs | 579 +++++++++++++++++ crates/registry-adapter/src/payments/store.rs | 293 +++++++++ crates/registry-adapter/src/serve.rs | 57 +- .../registry-adapter/tests/payment_config.rs | 217 +++++++ .../tests/payment_registry.rs | 24 + .../registry-adapter/tests/payment_service.rs | 504 +++++++++++++++ .../registry-adapter/tests/payment_store.rs | 46 ++ crates/registry-adapterctl/Cargo.toml | 2 +- crates/registry-adapterctl/src/lib.rs | 38 ++ crates/registry-adapterctl/src/payments.rs | 95 +++ crates/registry-adapterctl/src/schemas.rs | 18 +- crates/registry-adapterctl/tests/check.rs | 5 +- crates/registry-adapterctl/tests/payments.rs | 65 ++ crates/registry-breg/src/postgres/config.rs | 83 ++- crates/registry-breg/src/postgres/mod.rs | 4 +- crates/registry-breg/src/postgres/schema.rs | 39 +- crates/registry-breg/src/startup.rs | 31 +- crates/registry-bregctl/src/lib.rs | 62 ++ crates/registry-bregctl/src/test_lifecycle.rs | 73 ++- crates/registry-cli-docs/catalog.json | 152 ++++- crates/registry-coordinator/Cargo.toml | 3 +- crates/registry-coordinator/src/adapters.rs | 312 +++++++++ crates/registry-coordinator/src/authoring.rs | 10 + crates/registry-coordinator/src/contracts.rs | 47 ++ crates/registry-coordinator/src/definition.rs | 6 + crates/registry-coordinator/src/operations.rs | 52 ++ crates/registry-coordinator/src/protocol.rs | 9 + crates/registry-coordinator/src/runtime.rs | 44 ++ crates/registry-coordinator/src/scenarios.rs | 91 +++ .../tests/payment_adapter.rs | 285 +++++++++ .../tests/coordinator_navigation.rs | 4 +- crates/registry-payment-client/Cargo.toml | 31 + crates/registry-payment-client/src/client.rs | 414 ++++++++++++ crates/registry-payment-client/src/config.rs | 170 +++++ crates/registry-payment-client/src/error.rs | 82 +++ crates/registry-payment-client/src/lib.rs | 25 + .../tests/http_boundary.rs | 510 +++++++++++++++ crates/registry-payment-protocol/Cargo.toml | 25 + crates/registry-payment-protocol/src/lib.rs | 397 ++++++++++++ .../tests/contract.rs | 143 +++++ .../Cargo.toml | 29 + .../src/lib.rs | 428 +++++++++++++ .../tests/profile.rs | 169 +++++ products/adapter/AGENTS.md | 14 +- products/adapter/CHANGELOG.md | 13 + products/adapter/README.md | 6 + .../examples/payment-collections/CONTRACT.md | 95 +++ .../examples/payment-collections/README.md | 181 ++++++ .../payment-collections/payments.example.yaml | 36 ++ .../payment-collections/runtime.example.yaml | 17 + .../schemas/payments.v1alpha1.schema.json | 238 +++++++ products/adapter/scripts/check-contracts.sh | 4 +- .../scripts/check_dependency_direction.py | 66 +- .../scripts/payment-native-support.mjs | 221 +++++++ .../adapter/scripts/test-payment-native.mjs | 385 ++++++++++++ .../scripts/test_dependency_direction.py | 23 +- .../examples/payment-fee-issuance/README.md | 224 +++++++ .../payment-fee-issuance/lifecycle.sh | 41 ++ .../payment-fee-issuance/registry.yaml | 347 ++++++++++ .../payment-fee-issuance/run-native.sh | 592 ++++++++++++++++++ .../payment-fee-issuance/tests/journeys.yaml | 309 +++++++++ .../tests/lifecycle-smoke.sh | 133 ++++ products/coordinator/CHANGELOG.md | 8 + products/coordinator/README.md | 2 + .../examples/payment-collections/README.md | 148 +++++ .../payment-collections/input.example.json | 4 + .../examples/payment-collections/runtime.yaml | 57 ++ .../payment-collections/scenarios.yaml | 237 +++++++ .../payment-collections/workflow.yaml | 70 +++ .../openapi/coordinator.openapi.json | 5 +- .../generated/operations/README.md | 261 ++++++++ .../generated/operations/catalog.json | 468 ++++++++++++++ ...payments.collection.completion.schema.json | 104 +++ ...ments.read-collection.v1.input.schema.json | 19 + ...ents.read-collection.v1.output.schema.json | 104 +++ ...yments.record-receipt.v1.input.schema.json | 19 + ...ments.record-receipt.v1.output.schema.json | 85 +++ ...ts.request-collection.v1.input.schema.json | 25 + ...s.request-collection.v1.output.schema.json | 41 ++ .../generated/project/project.schema.json | 5 +- .../generated/runtime/runtime.schema.json | 34 + .../identifiers/contracts/catalog-source.json | 2 +- .../identifiers/generated/catalog.v1.json | 60 +- products/platform/config-formats.yaml | 56 ++ tools/payment-simulator/README.md | 7 +- 99 files changed, 11640 insertions(+), 113 deletions(-) create mode 100644 crates/registry-adapter/src/payments/config.rs create mode 100644 crates/registry-adapter/src/payments/http.rs create mode 100644 crates/registry-adapter/src/payments/mod.rs create mode 100644 crates/registry-adapter/src/payments/model.rs create mode 100644 crates/registry-adapter/src/payments/registry.rs create mode 100644 crates/registry-adapter/src/payments/service.rs create mode 100644 crates/registry-adapter/src/payments/store.rs create mode 100644 crates/registry-adapter/tests/payment_config.rs create mode 100644 crates/registry-adapter/tests/payment_registry.rs create mode 100644 crates/registry-adapter/tests/payment_service.rs create mode 100644 crates/registry-adapter/tests/payment_store.rs create mode 100644 crates/registry-adapterctl/src/payments.rs create mode 100644 crates/registry-adapterctl/tests/payments.rs create mode 100644 crates/registry-coordinator/tests/payment_adapter.rs create mode 100644 crates/registry-payment-client/Cargo.toml create mode 100644 crates/registry-payment-client/src/client.rs create mode 100644 crates/registry-payment-client/src/config.rs create mode 100644 crates/registry-payment-client/src/error.rs create mode 100644 crates/registry-payment-client/src/lib.rs create mode 100644 crates/registry-payment-client/tests/http_boundary.rs create mode 100644 crates/registry-payment-protocol/Cargo.toml create mode 100644 crates/registry-payment-protocol/src/lib.rs create mode 100644 crates/registry-payment-protocol/tests/contract.rs create mode 100644 crates/registry-payment-simulator-connector/Cargo.toml create mode 100644 crates/registry-payment-simulator-connector/src/lib.rs create mode 100644 crates/registry-payment-simulator-connector/tests/profile.rs create mode 100644 products/adapter/examples/payment-collections/CONTRACT.md create mode 100644 products/adapter/examples/payment-collections/README.md create mode 100644 products/adapter/examples/payment-collections/payments.example.yaml create mode 100644 products/adapter/examples/payment-collections/runtime.example.yaml create mode 100644 products/adapter/schemas/payments.v1alpha1.schema.json create mode 100644 products/adapter/scripts/payment-native-support.mjs create mode 100644 products/adapter/scripts/test-payment-native.mjs create mode 100644 products/breg/examples/payment-fee-issuance/README.md create mode 100644 products/breg/examples/payment-fee-issuance/lifecycle.sh create mode 100644 products/breg/examples/payment-fee-issuance/registry.yaml create mode 100755 products/breg/examples/payment-fee-issuance/run-native.sh create mode 100644 products/breg/examples/payment-fee-issuance/tests/journeys.yaml create mode 100755 products/breg/examples/payment-fee-issuance/tests/lifecycle-smoke.sh create mode 100644 products/coordinator/examples/payment-collections/README.md create mode 100644 products/coordinator/examples/payment-collections/input.example.json create mode 100644 products/coordinator/examples/payment-collections/runtime.yaml create mode 100644 products/coordinator/examples/payment-collections/scenarios.yaml create mode 100644 products/coordinator/examples/payment-collections/workflow.yaml create mode 100644 products/coordinator/generated/operations/payments.collection.completion.schema.json create mode 100644 products/coordinator/generated/operations/payments.read-collection.v1.input.schema.json create mode 100644 products/coordinator/generated/operations/payments.read-collection.v1.output.schema.json create mode 100644 products/coordinator/generated/operations/payments.record-receipt.v1.input.schema.json create mode 100644 products/coordinator/generated/operations/payments.record-receipt.v1.output.schema.json create mode 100644 products/coordinator/generated/operations/payments.request-collection.v1.input.schema.json create mode 100644 products/coordinator/generated/operations/payments.request-collection.v1.output.schema.json diff --git a/.github/scripts/ci_changes.py b/.github/scripts/ci_changes.py index 2087f429e7..6db654c2d7 100644 --- a/.github/scripts/ci_changes.py +++ b/.github/scripts/ci_changes.py @@ -107,6 +107,9 @@ "registry-adapter-connectors", "registry-adapter-job", "registry-adapterctl", + "registry-payment-protocol", + "registry-payment-client", + "registry-payment-simulator-connector", ), "stack-client": ("registry-record", "registry-stack-client"), "evidence": ( diff --git a/.github/scripts/test_ci_changes.py b/.github/scripts/test_ci_changes.py index 413a312f7e..0f13a11e4a 100644 --- a/.github/scripts/test_ci_changes.py +++ b/.github/scripts/test_ci_changes.py @@ -1298,6 +1298,25 @@ def test_shared_adapter_engine_selects_evidence_consumers(self) -> None: self.assertTrue(outputs["evidence_postgres"]) self.assertTrue(outputs["adapter_contracts"]) + def test_payment_components_select_their_tests_and_consumers(self) -> None: + for package in ( + "registry-payment-protocol", + "registry-payment-client", + "registry-payment-simulator-connector", + ): + with self.subTest(package=package): + outputs = classify(self.workspace, (f"crates/{package}/src/lib.rs",)) + selected = { + name + for row in outputs["rust_matrix"]["include"] + for name in row["packages"] + } + self.assertIn(package, selected) + if package != "registry-payment-client": + self.assertTrue(outputs["adapter_contracts"]) + if package != "registry-payment-simulator-connector": + self.assertTrue(outputs["coordinator"]) + def test_adapter_contract_job_runs_the_facade_recovery_runner(self) -> None: steps = self.workflow_jobs["adapter-contracts"]["steps"] runner = next( diff --git a/AGENTS.md b/AGENTS.md index 83c9115c51..3aaada2132 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -51,10 +51,13 @@ not products of their own. | `products/documents` | Document Store product contracts, starter example, generated schemas and OpenAPI document, and contributor check scripts | | `crates/registry-adapter-core` | Source-neutral Adapter model, wire DTOs, `adapter.*` problem codes, and pure authoring checks | | `crates/registry-adapter-engine` | Shared bounded integration execution, compilation, components and replay; no listener, PostgreSQL client or product runtime | -| `crates/registry-adapter` | Adapter facade: serving, caller admission, write custody and audit journal over the shared engine | +| `crates/registry-adapter` | Adapter host: record-facade serving and custody over the shared engine, plus the optional typed payment module and its separate PostgreSQL attempts | +| `crates/registry-payment-protocol` | Runtime-free exact-money payment intents, observations, receipts and problem vocabulary | +| `crates/registry-payment-client` | Bounded typed HTTP client for the Adapter payment contract | +| `crates/registry-payment-simulator-connector` | Standalone synthetic P2G provider connector; no Adapter, Coordinator or product runtime dependency | | `crates/registry-adapterctl` | Adapter authoring and operator tooling and the `adapterctl` binary | | `crates/registry-adapter-job` | Adapter ingestion-job host and the `adapter-job` binary: item table, pass, interval and authenticated hook triggers, and destination seam; identity and position only, never payloads | -| `crates/registry-adapter-connectors` | BReg connector over `registry-breg-client`, reachable only through the job host's explicit off-by-default `direct-breg` feature; never through the engine or facade; the dependency gate enforces this boundary | +| `crates/registry-adapter-connectors` | Ingestion BReg connector over `registry-breg-client`, reachable only through the job host's explicit off-by-default `direct-breg` feature; never through the engine or facade; distinct from the payment host's direct public BReg client dependency; the dependency gate enforces this boundary | | `products/adapter` | Adapter schemas, profiles, packs, examples, fixtures, the Camel port table, and contributor check scripts | | `crates/registry-discovery` | Immutable Registry Discovery index runtime and the `discovery` binary | | `crates/registry-discovery-profile` | Closed provider-publication profile implemented by Evidence; published v1alpha1 resources retain their historical broader vocabulary | @@ -330,6 +333,14 @@ never reaches a product runtime, CLI, database crate, or any Coordinator crate, and `products/adapter/scripts/check_dependency_direction.py` enforces that split. The adapter inherits no authorization +from any product. The optional payment module is a separate approved host +exception: `registry-adapter` may use `registry-payment-protocol`, the +standalone synthetic provider connector, and the public `registry-breg-client` +for authoritative bill reads and restricted binding/receipt Actions. The +source-neutral core, engine and generic job host gain no payment dependencies. +The payment host retains original attempt bindings and grants no authority +to Coordinator or callers to assert financial facts. The record facade +inherits no authorization from any product and grants none to any source: upstream calls run under the deployment's own credential, or without an application credential for numeric loopback, HTTPS with mTLS, or a fixed HTTPS source carrying the diff --git a/Cargo.lock b/Cargo.lock index e066fe09a3..860f410e7b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5958,6 +5958,7 @@ checksum = "d902046e6a28a1e4c3cab97258a0ce11e994903f01c2d97a9447a0b3df85f4f6" name = "registry-adapter" version = "0.49.0" dependencies = [ + "async-trait", "axum", "base64 0.23.1", "chacha20poly1305", @@ -5972,6 +5973,9 @@ dependencies = [ "rcgen", "registry-adapter-core", "registry-adapter-engine", + "registry-breg-client", + "registry-payment-protocol", + "registry-payment-simulator-connector", "registry-platform-authcommon", "registry-platform-buildinfo", "registry-platform-canonical-json", @@ -5984,6 +5988,7 @@ dependencies = [ "registry-platform-testing", "registry-platform-yaml", "rustls", + "schemars", "serde", "serde_json", "serde_norway", @@ -5998,6 +6003,7 @@ dependencies = [ "tracing", "tracing-subscriber", "url", + "uuid", "zeroize", ] @@ -6714,6 +6720,7 @@ dependencies = [ "registry-cli-api", "registry-messaging-client", "registry-messaging-core", + "registry-payment-client", "registry-platform-activation", "registry-platform-audit", "registry-platform-authcommon", @@ -7683,6 +7690,52 @@ dependencies = [ "zeroize", ] +[[package]] +name = "registry-payment-client" +version = "0.46.1" +dependencies = [ + "axum", + "registry-payment-protocol", + "registry-platform-canonical-json", + "registry-platform-httpsec", + "registry-platform-httputil", + "reqwest 0.12.28", + "serde", + "serde_json", + "thiserror 2.0.21", + "tokio", + "url", + "uuid", +] + +[[package]] +name = "registry-payment-protocol" +version = "0.46.1" +dependencies = [ + "jsonschema", + "schemars", + "serde", + "serde_json", + "thiserror 2.0.21", + "uuid", +] + +[[package]] +name = "registry-payment-simulator-connector" +version = "0.46.1" +dependencies = [ + "registry-payment-protocol", + "registry-platform-httputil", + "registry-platform-yaml", + "reqwest 0.12.28", + "schemars", + "serde", + "serde_json", + "thiserror 2.0.21", + "tokio", + "url", +] + [[package]] name = "registry-platform-activation" version = "0.49.0" diff --git a/Cargo.toml b/Cargo.toml index 5b7bf9ea86..0921774f05 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -6,6 +6,9 @@ members = [ "crates/registry-coordinator-client-py", "crates/registry-review-client", "crates/registry-review-protocol", + "crates/registry-payment-protocol", + "crates/registry-payment-client", + "crates/registry-payment-simulator-connector", "crates/registry-casework-client-node", "crates/registry-casework-client-py", "crates/registry-casework", @@ -126,6 +129,9 @@ registry-cli-api = { path = "crates/registry-cli-api", version = "0.49.0" } registry-cli-report = { path = "crates/registry-cli-report", version = "0.49.0" } registry-review-client = { path = "crates/registry-review-client", version = "0.49.0" } registry-review-protocol = { path = "crates/registry-review-protocol", version = "0.49.0" } +registry-payment-protocol = { path = "crates/registry-payment-protocol", version = "0.49.0" } +registry-payment-client = { path = "crates/registry-payment-client", version = "0.49.0" } +registry-payment-simulator-connector = { path = "crates/registry-payment-simulator-connector", version = "0.49.0" } registry-thunderid-tooling = { path = "crates/registry-thunderid-tooling", version = "0.49.0" } registry-casework = { path = "crates/registry-casework", version = "0.49.0" } registry-caseworkctl = { path = "crates/registry-caseworkctl", version = "0.49.0" } diff --git a/crates/registry-adapter/Cargo.toml b/crates/registry-adapter/Cargo.toml index 55699723a2..d4433d8b64 100644 --- a/crates/registry-adapter/Cargo.toml +++ b/crates/registry-adapter/Cargo.toml @@ -35,6 +35,12 @@ postgres-test = [ # refuses at compile under adapter.job.component-unavailable. job-file = ["registry-adapter-engine/job-file"] job-postgres = ["registry-adapter-engine/job-postgres"] +schema = [ + "dep:schemars", + "registry-payment-protocol/schema", + "registry-payment-simulator-connector/schema", + "registry-platform-yaml/schema", +] [dependencies] # The continuation cursor codec: XChaCha20-Poly1305 @@ -54,6 +60,12 @@ url.workspace = true tokio-postgres.workspace = true registry-adapter-core.workspace = true registry-adapter-engine.workspace = true +registry-payment-protocol.workspace = true +registry-payment-simulator-connector.workspace = true +registry-breg-client.workspace = true +uuid = { workspace = true, features = ["serde"] } +schemars = { workspace = true, optional = true } +async-trait.workspace = true registry-platform-buildinfo.workspace = true registry-platform-config.workspace = true registry-platform-crypto.workspace = true diff --git a/crates/registry-adapter/src/cli.rs b/crates/registry-adapter/src/cli.rs index d017355f98..1fc405c908 100644 --- a/crates/registry-adapter/src/cli.rs +++ b/crates/registry-adapter/src/cli.rs @@ -20,23 +20,30 @@ pub struct Cli { #[derive(Subcommand)] pub enum Command { - /// Serve the governed facade. + /// Serve the governed record facade, typed payment connections, or both. Serve { /// Runtime configuration file. #[arg(long, value_name = "ABSOLUTE_FILE")] runtime_config: PathBuf, /// The directory holding project.yaml. - #[arg(long, value_name = "DIRECTORY")] - project: PathBuf, + #[arg( + long, + value_name = "DIRECTORY", + required_unless_present = "payments_config" + )] + project: Option, + /// Typed payment connections hosted on this listener. + #[arg(long, value_name = "ABSOLUTE_FILE")] + payments_config: Option, /// The profile file; defaults to profile.yaml beside the project. - #[arg(long, value_name = "FILE")] + #[arg(long, value_name = "FILE", requires = "project")] profile: Option, /// The pack file, whose scripts/ sit beside it; defaults to pack.yaml /// beside the project. - #[arg(long, value_name = "FILE")] + #[arg(long, value_name = "FILE", requires = "project")] pack: Option, }, - /// Export the loaded gateway contract without binding a listener. + /// Export the record-facade contract without binding a listener. EffectiveContract { /// Runtime configuration file. #[arg(long, value_name = "ABSOLUTE_FILE")] @@ -62,6 +69,39 @@ pub fn command() -> clap::Command { #[cfg(test)] mod tests { + use clap::Parser; + + #[test] + fn a_payment_only_host_needs_no_record_project() { + assert!(super::Cli::try_parse_from([ + "adapter", + "serve", + "--runtime-config", + "/runtime.yaml", + "--payments-config", + "/payments.yaml" + ]) + .is_ok()); + assert!(super::Cli::try_parse_from([ + "adapter", + "serve", + "--runtime-config", + "/runtime.yaml" + ]) + .is_err()); + assert!(super::Cli::try_parse_from([ + "adapter", + "serve", + "--runtime-config", + "/runtime.yaml", + "--payments-config", + "/payments.yaml", + "--profile", + "profile.yaml" + ]) + .is_err()); + } + #[test] fn the_version_is_the_display_version_the_ctl_tools_report() { assert_eq!( diff --git a/crates/registry-adapter/src/lib.rs b/crates/registry-adapter/src/lib.rs index c95d2276a1..ab84eecb08 100644 --- a/crates/registry-adapter/src/lib.rs +++ b/crates/registry-adapter/src/lib.rs @@ -44,5 +44,6 @@ pub mod idempotent; pub mod journal; pub mod metrics; pub mod notifier; +pub mod payments; pub mod replay_serve; pub mod serve; diff --git a/crates/registry-adapter/src/main.rs b/crates/registry-adapter/src/main.rs index 8b8cbae655..d0f6b3f291 100644 --- a/crates/registry-adapter/src/main.rs +++ b/crates/registry-adapter/src/main.rs @@ -27,13 +27,15 @@ async fn main() { Command::Serve { runtime_config, project, + payments_config, profile, pack, - } => registry_adapter::serve::run( - &project, + } => registry_adapter::serve::run_configured( + project.as_deref(), profile.as_deref(), pack.as_deref(), &runtime_config, + payments_config.as_deref(), ) .await .map_err(|error| error.to_string()), diff --git a/crates/registry-adapter/src/payments/config.rs b/crates/registry-adapter/src/payments/config.rs new file mode 100644 index 0000000000..82e1f90cbc --- /dev/null +++ b/crates/registry-adapter/src/payments/config.rs @@ -0,0 +1,200 @@ +// SPDX-License-Identifier: Apache-2.0 +//! Operator-owned payment connections and their immutable attempt snapshots. + +use registry_payment_protocol::Money; +use registry_payment_simulator_connector::SimulatorConnection; +use registry_platform_httputil::client::ServiceBaseUrl; +use registry_platform_yaml::SecretReference; +use serde::{Deserialize, Serialize}; +use std::collections::BTreeSet; + +pub const API_VERSION: &str = "id.registrystack.org/formats/adapter/payments/v1alpha1"; +pub const KIND: &str = "AdapterPayments"; +pub const BILL_CONTRACT: &str = "service-fee-bill/v1"; +pub const SCHEMA_ID: &str = + "https://id.registrystack.org/schemas/adapter/payments/payments.v1alpha1.schema.json"; + +#[derive(Clone, Serialize, Deserialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct PaymentsConfig { + #[cfg_attr(feature = "schema", schemars(length(min = 1, max = 64)))] + pub connections: Vec, +} + +#[derive(Clone, Serialize, Deserialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct PaymentConnection { + #[cfg_attr(feature = "schema", schemars(with = "registry_platform_yaml::LocalId"))] + pub id: String, + #[cfg_attr( + feature = "schema", + schemars(length(min = 1, max = 128), pattern(r"^[\x21-\x7e]+$")) + )] + pub institution_id: String, + #[cfg_attr( + feature = "schema", + schemars(length(min = 1, max = 128), pattern(r"^[\x21-\x7e]+$")) + )] + pub service_id: String, + #[cfg_attr(feature = "schema", schemars(length(min = 1, max = 64), extend("uniqueItems" = true)))] + #[serde(deserialize_with = "unique_clients")] + pub allowed_clients: Vec, + #[cfg_attr( + feature = "schema", + schemars(length(min = 1, max = 128), pattern(r"^[\x21-\x7e]+$")) + )] + pub required_scope: String, + pub binding: PaymentBinding, +} + +/// Persisted in full before a provider send. It holds credential references +/// and identities, never credential values. Rotation at the same reference is +/// supported; changing a reference does not reroute a retained attempt. +#[derive(Clone, Serialize, Deserialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct PaymentBinding { + #[cfg_attr(feature = "schema", schemars(extend("const" = true)))] + pub simulation: bool, + #[cfg_attr(feature = "schema", schemars(pattern("^[A-Z]{3}$")))] + pub currency: String, + #[cfg_attr(feature = "schema", schemars(range(min = 0, max = 6)))] + #[serde(deserialize_with = "currency_scale")] + pub currency_scale: u8, + pub provider: SimulatorConnection, + pub provider_credential_ref: SecretReference, + pub provider_credential_identity: String, + #[cfg_attr(feature = "schema", schemars(range(min = 1, max = 86_400)))] + #[serde(deserialize_with = "replay_window")] + pub replay_window_seconds: u64, + pub registry: RegistryBinding, +} + +#[derive(Clone, Serialize, Deserialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct RegistryBinding { + #[cfg_attr(feature = "schema", schemars(with = "registry_platform_yaml::Url"))] + pub base_url: String, + pub record_type: String, + pub record_route: String, + pub read_profile: String, + pub bind_profile: String, + pub receipt_profile: String, + pub bind_action: String, + pub receipt_action: String, + pub credential_ref: SecretReference, + pub credential_identity: String, +} + +#[derive(Clone, Copy, Debug, thiserror::Error)] +#[error("adapter.payment.configuration")] +pub struct ConfigError; + +fn unique_clients<'de, D: serde::Deserializer<'de>>( + deserializer: D, +) -> Result, D::Error> { + registry_platform_yaml::UniqueList::::deserialize(deserializer) + .map(|values| values.into_vec()) +} + +fn currency_scale<'de, D: serde::Deserializer<'de>>(deserializer: D) -> Result { + registry_platform_yaml::BoundedU32::<0, 6>::deserialize(deserializer) + .map(|value| u8::try_from(value.get()).expect("the bounded scale fits in u8")) +} + +fn replay_window<'de, D: serde::Deserializer<'de>>(deserializer: D) -> Result { + registry_platform_yaml::BoundedU64::<1, 86_400>::deserialize(deserializer) + .map(|value| value.get()) +} + +impl PaymentsConfig { + pub fn validate(&self) -> Result<(), ConfigError> { + if self.connections.is_empty() || self.connections.len() > 64 { + return Err(ConfigError); + } + let mut ids = BTreeSet::new(); + for connection in &self.connections { + if !connection_id(&connection.id) + || !ids.insert(&connection.id) + || !text(&connection.institution_id, 128) + || !text(&connection.service_id, 128) + || connection.allowed_clients.is_empty() + || connection.allowed_clients.len() > 64 + || connection.allowed_clients.iter().any(|s| !text(s, 128)) + || connection + .allowed_clients + .iter() + .collect::>() + .len() + != connection.allowed_clients.len() + || !text(&connection.required_scope, 128) + { + return Err(ConfigError); + } + connection.binding.validate()?; + } + Ok(()) + } +} + +impl PaymentBinding { + pub fn validate(&self) -> Result<(), ConfigError> { + if !self.simulation + || !text(&self.provider_credential_identity, 128) + || !(1..=86_400).contains(&self.replay_window_seconds) + { + return Err(ConfigError); + } + self.provider.validate().map_err(|_| ConfigError)?; + Money { + value: "1".into(), + currency: self.currency.clone(), + scale: self.currency_scale, + } + .minor_units() + .map_err(|_| ConfigError)?; + let registry = &self.registry; + registry_platform_yaml::Url::new(registry.base_url.clone()).map_err(|_| ConfigError)?; + ServiceBaseUrl::new(url::Url::parse(®istry.base_url).map_err(|_| ConfigError)?) + .map_err(|_| ConfigError)?; + if !text(®istry.read_profile, 128) + || !text(®istry.bind_profile, 128) + || !text(®istry.receipt_profile, 128) + || !text(®istry.credential_identity, 128) + || !local_id(®istry.record_route) + || !local_id(®istry.record_type) + || !local_id(®istry.bind_action) + || !local_id(®istry.receipt_action) + || registry.bind_action == registry.receipt_action + { + return Err(ConfigError); + } + Ok(()) + } + + pub fn revision(&self) -> Result { + let value = serde_json::json!({ + "connector": registry_payment_simulator_connector::CONNECTOR_VERSION, + "billContract": BILL_CONTRACT, "binding": self, + }); + let canonical = + registry_platform_canonical_json::canonicalize_json(&value).map_err(|_| ConfigError)?; + Ok(registry_platform_config::sha256_uri(&canonical)) + } +} + +pub(crate) fn text(value: &str, max: usize) -> bool { + !value.is_empty() && value.len() <= max && value.bytes().all(|b| (0x21..=0x7e).contains(&b)) +} +fn local_id(value: &str) -> bool { + text(value, 128) + && value + .bytes() + .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_')) +} +fn connection_id(value: &str) -> bool { + registry_platform_yaml::LocalId::new(value).is_ok() +} diff --git a/crates/registry-adapter/src/payments/http.rs b/crates/registry-adapter/src/payments/http.rs new file mode 100644 index 0000000000..96d70c8bf1 --- /dev/null +++ b/crates/registry-adapter/src/payments/http.rs @@ -0,0 +1,389 @@ +// SPDX-License-Identifier: Apache-2.0 +//! Typed payment routes sharing the Adapter's authentication and database host. + +use super::{ + config::{PaymentsConfig, API_VERSION, KIND}, + registry::BregBridge, + service::{PaymentService, SyntheticProvider}, + store::{migrate, PaymentStore}, +}; +use crate::serve::{Authenticator, Caller, CallerRefusal, ServeError}; +use axum::{ + body::Bytes, + extract::{DefaultBodyLimit, Path as RoutePath, State}, + http::{HeaderMap, HeaderValue, StatusCode, Uri}, + response::{IntoResponse, Response}, + routing::{get, post}, + Json, Router, +}; +use registry_adapter_core::AdapterRuntimeConfig; +use registry_payment_protocol::{ + PaymentProblem, PaymentProblemCode as Error, RecordReceipt, RequestCollection, +}; +use registry_platform_config::{ + RuntimeConfigLoader, RuntimeEnvelope, SecretProvider, SecretResolver, +}; +use serde::{de::DeserializeOwned, Serialize}; +use std::{path::Path, sync::Arc}; +use uuid::Uuid; + +struct HttpState { + authenticator: Authenticator, + service: PaymentService, +} + +/// Fixed payment routes and wire schemas, without origins or credential references. +#[cfg(feature = "schema")] +pub fn contract(config: &PaymentsConfig) -> serde_json::Value { + use registry_payment_protocol::{CollectionAccepted, CollectionStatus, RegistryReceipt}; + serde_json::json!({ + "protocol":"payments/v1", + "authentication":"OIDC access tokens under the Adapter runtime issuer and client policy", + "simulation":true, + "connections":config.connections.iter().map(|connection| { + let base=format!("/v1/payments/{}/collections",connection.id); + serde_json::json!({ + "connection":connection.id, + "allowedClients":connection.allowed_clients, + "requiredScope":connection.required_scope, + "operations":[ + {"operation":"payments.request-collection/v1","method":"POST","path":base,"successStatus":202,"effect":"mutation"}, + {"operation":"payments.request-collection-receipt/v1","method":"POST","path":format!("{base}/receipt"),"successStatus":200,"effect":"read","recoveryOnly":true}, + {"operation":"payments.read-collection/v1","method":"GET","path":format!("{base}/{{collectionId}}"),"successStatus":200,"effect":"read"}, + {"operation":"payments.record-receipt/v1","method":"POST","path":format!("{base}/{{collectionId}}/record-receipt"),"successStatus":200,"effect":"mutation"} + ] + }) + }).collect::>(), + "schemas":{ + "RequestCollection":schemars::schema_for!(RequestCollection), + "CollectionAccepted":schemars::schema_for!(CollectionAccepted), + "CollectionStatus":schemars::schema_for!(CollectionStatus), + "RecordReceipt":schemars::schema_for!(RecordReceipt), + "RegistryReceipt":schemars::schema_for!(RegistryReceipt), + "PaymentProblem":schemars::schema_for!(PaymentProblem) + } + }) +} + +pub fn load_config(path: &Path) -> Result { + let absolute = std::fs::canonicalize(path) + .map_err(|_| refused("payment configuration could not be read"))?; + let config = RuntimeConfigLoader::new(RuntimeEnvelope { + api_version: API_VERSION, + kind: KIND, + }) + .load::(&absolute) + .map_err(|_| refused("payment configuration was refused"))? + .config; + config + .validate() + .map_err(|_| refused("payment connections were refused"))?; + Ok(config) +} + +fn resolver(runtime: &AdapterRuntimeConfig) -> Result { + match &runtime.secret_providers { + Some(providers) => providers.resolver(), + None => SecretResolver::new([SecretProvider::Environment], ""), + } + .map_err(|_| refused("payment secret providers were refused")) +} + +pub async fn load_router( + runtime: &AdapterRuntimeConfig, + path: &Path, + pool: deadpool_postgres::Pool, +) -> Result { + let config = load_config(path)?; + let resolver = Arc::new(resolver(runtime)?); + for connection in &config.connections { + for reference in [ + &connection.binding.provider_credential_ref, + &connection.binding.registry.credential_ref, + ] { + let value = resolver + .resolve(reference.as_str()) + .map_err(|_| refused("a payment credential could not be resolved"))?; + let value = std::str::from_utf8(value.expose_secret()) + .map_err(|_| refused("a payment credential was refused"))?; + registry_platform_httputil::client::BearerToken::new(value.to_owned()) + .map_err(|_| refused("a payment credential was refused"))?; + } + } + let authenticator = crate::serve::authenticator(runtime, &resolver).await?; + let migration = crate::serve::pool(&runtime.database, &resolver, true)?; + { + let mut client = migration + .get() + .await + .map_err(|_| refused("payment migration database unavailable"))?; + migrate(&mut client) + .await + .map_err(|_| refused("payment database migration failed"))?; + } + let store = PaymentStore::new(pool, runtime.id.as_str().to_owned()); + store + .check_privileges() + .await + .map_err(|_| refused("payment runtime role lacks required table or sequence privileges"))?; + let service = PaymentService::new( + config, + store, + Arc::new(BregBridge::new(resolver.clone())), + Arc::new(SyntheticProvider::new(resolver)), + ) + .map_err(|_| refused("payment service was refused"))?; + let state = Arc::new(HttpState { + authenticator, + service, + }); + Ok(Router::new() + .route("/v1/payments/{connection}/collections", post(request)) + .route( + "/v1/payments/{connection}/collections/receipt", + post(request_receipt), + ) + .route( + "/v1/payments/{connection}/collections/{collection}", + get(read), + ) + .route( + "/v1/payments/{connection}/collections/{collection}/record-receipt", + post(record_receipt), + ) + .layer(DefaultBodyLimit::max(4096)) + .with_state(state)) +} + +pub async fn run_only(runtime_path: &Path, payments_path: &Path) -> Result<(), ServeError> { + let absolute = std::fs::canonicalize(runtime_path) + .map_err(|_| refused("runtime configuration could not be read"))?; + let runtime = RuntimeConfigLoader::new(RuntimeEnvelope { + api_version: registry_adapter_core::ADAPTER_RUNTIME_API_VERSION, + kind: registry_adapter_core::ADAPTER_RUNTIME_KIND, + }) + .removed_keys(registry_adapter_core::ADAPTER_REMOVED_KEYS) + .load::(&absolute) + .map_err(|_| refused("runtime configuration was refused"))? + .config; + let resolver = resolver(&runtime)?; + let pool = crate::serve::pool(&runtime.database, &resolver, false)?; + let router = load_router(&runtime, payments_path, pool).await?; + let shutdown = crate::serve::shutdown_signal()?; + let listener = tokio::net::TcpListener::bind(runtime.listener.bind.0) + .await + .map_err(|_| refused("payment listener could not bind"))?; + tracing::info!("payment listener ready"); + axum::serve(listener, router) + .with_graceful_shutdown(shutdown) + .await + .map_err(|_| refused("payment listener stopped")) +} + +async fn caller(state: &HttpState, headers: &HeaderMap) -> Result { + let value = + single_header(headers, "authorization").map_err(|_| HttpError(Error::Unauthenticated))?; + let bearer = value + .strip_prefix("Bearer ") + .ok_or(HttpError(Error::Unauthenticated))?; + state + .authenticator + .authenticate(bearer) + .await + .map_err(|error| { + HttpError(match error { + CallerRefusal::Unauthenticated => Error::Unauthenticated, + CallerRefusal::Unavailable => Error::Unavailable, + }) + }) +} + +fn single_header<'a>(headers: &'a HeaderMap, name: &str) -> Result<&'a str, HttpError> { + let mut values = headers.get_all(name).iter(); + match (values.next(), values.next()) { + (Some(value), None) => value.to_str().map_err(|_| HttpError(Error::InvalidRequest)), + _ => Err(HttpError(Error::InvalidRequest)), + } +} +fn body(headers: &HeaderMap, uri: &Uri, body: &[u8]) -> Result { + if uri.query().is_some() || single_header(headers, "content-type")? != "application/json" { + return Err(HttpError(Error::InvalidRequest)); + } + serde_json::from_slice(body).map_err(|_| HttpError(Error::InvalidRequest)) +} +fn collection(value: &str) -> Result { + Uuid::parse_str(value) + .ok() + .filter(|id| !id.is_nil()) + .ok_or(HttpError(Error::InvalidRequest)) +} + +async fn request( + State(state): State>, + RoutePath(connection): RoutePath, + uri: Uri, + headers: HeaderMap, + bytes: Bytes, +) -> Result { + let caller = caller(&state, &headers).await?; + let request: RequestCollection = body(&headers, &uri, &bytes)?; + let key = single_header(&headers, "idempotency-key")?; + let result = state + .service + .request(&connection, &caller, key, &request) + .await; + finish( + &state, + &caller, + "request", + None, + true, + StatusCode::ACCEPTED, + result, + ) + .await +} +async fn request_receipt( + State(state): State>, + RoutePath(connection): RoutePath, + uri: Uri, + headers: HeaderMap, + bytes: Bytes, +) -> Result { + let caller = caller(&state, &headers).await?; + let request: RequestCollection = body(&headers, &uri, &bytes)?; + let key = single_header(&headers, "idempotency-key")?; + let result = state + .service + .request_receipt(&connection, &caller, key, &request) + .await; + finish( + &state, + &caller, + "request-receipt", + None, + false, + StatusCode::OK, + result, + ) + .await +} +async fn read( + State(state): State>, + RoutePath((connection, id)): RoutePath<(String, String)>, + uri: Uri, + headers: HeaderMap, + bytes: Bytes, +) -> Result { + let caller = caller(&state, &headers).await?; + if uri.query().is_some() || !bytes.is_empty() { + return Err(HttpError(Error::InvalidRequest)); + } + let id = collection(&id)?; + let result = state.service.read(&connection, &caller, id).await; + finish( + &state, + &caller, + "read", + Some(id), + false, + StatusCode::OK, + result, + ) + .await +} +async fn record_receipt( + State(state): State>, + RoutePath((connection, id)): RoutePath<(String, String)>, + uri: Uri, + headers: HeaderMap, + bytes: Bytes, +) -> Result { + let caller = caller(&state, &headers).await?; + let id = collection(&id)?; + let request: RecordReceipt = body(&headers, &uri, &bytes)?; + if request.collection_id != id { + return Err(HttpError(Error::InvalidRequest)); + } + let key = single_header(&headers, "idempotency-key")?; + let result = state + .service + .record_receipt(&connection, &caller, key, id) + .await; + finish( + &state, + &caller, + "record-receipt", + Some(id), + true, + StatusCode::OK, + result, + ) + .await +} + +#[allow(clippy::too_many_arguments)] +async fn finish( + state: &HttpState, + caller: &Caller, + operation: &str, + id: Option, + mutation: bool, + status: StatusCode, + result: Result, +) -> Result { + state + .service + .audit_access(caller, operation, id, result.as_ref().err().copied()) + .await + .map_err(|_| { + HttpError(if mutation { + Error::OutcomeUnknown + } else { + Error::Unavailable + }) + })?; + result + .map(|value| headers((status, Json(value)).into_response())) + .map_err(HttpError) +} + +struct HttpError(Error); +impl IntoResponse for HttpError { + fn into_response(self) -> Response { + let problem = PaymentProblem::from(self.0); + let status = + StatusCode::from_u16(problem.status).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR); + let mut response = (status, Json(problem)).into_response(); + response.headers_mut().insert( + "content-type", + HeaderValue::from_static("application/problem+json"), + ); + headers(response) + } +} +fn headers(mut response: Response) -> Response { + let trace = format!( + "00-{}-{}-00", + Uuid::new_v4().simple(), + &Uuid::new_v4().simple().to_string()[..16] + ); + response.headers_mut().insert( + "traceparent", + HeaderValue::from_str(&trace).expect("UUID hex produces a valid trace header"), + ); + response + .headers_mut() + .insert("cache-control", HeaderValue::from_static("no-store")); + response.headers_mut().insert( + "x-content-type-options", + HeaderValue::from_static("nosniff"), + ); + response + .headers_mut() + .insert("x-payment-simulator", HeaderValue::from_static("synthetic")); + response +} +fn refused(message: &str) -> ServeError { + ServeError::Configuration(format!("adapter.payment.configuration: {message}")) +} diff --git a/crates/registry-adapter/src/payments/mod.rs b/crates/registry-adapter/src/payments/mod.rs new file mode 100644 index 0000000000..80304c56f3 --- /dev/null +++ b/crates/registry-adapter/src/payments/mod.rs @@ -0,0 +1,9 @@ +// SPDX-License-Identifier: Apache-2.0 +//! Payment-specific attempt custody at the Adapter host boundary. The generic +//! route engine has no payment state, provider semantics, or receipt authority. +pub mod config; +pub mod http; +pub mod model; +pub mod registry; +pub mod service; +pub mod store; diff --git a/crates/registry-adapter/src/payments/model.rs b/crates/registry-adapter/src/payments/model.rs new file mode 100644 index 0000000000..c6566a95a4 --- /dev/null +++ b/crates/registry-adapter/src/payments/model.rs @@ -0,0 +1,223 @@ +// SPDX-License-Identifier: Apache-2.0 +//! Immutable bill and provider facts retained for exact recovery. + +use super::config::{PaymentBinding, PaymentConnection}; +use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine}; +use registry_payment_protocol::{ + CollectionAccepted, CollectionState, CollectionStatus, Money, PaymentProblemCode, + RegistryReceipt, MAX_MINOR_UNITS, +}; +use registry_payment_simulator_connector::{Observation, ProviderCommand}; +use serde::{Deserialize, Serialize}; +use serde_json::{Map, Value}; +use sha2::{Digest, Sha256}; +use uuid::Uuid; + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct BillSnapshot { + pub bill_id: Uuid, + pub bill_version: u64, + pub bill_digest: String, + pub institution_id: String, + pub service_id: String, + pub request_id: String, + pub tariff_id: String, + pub tariff_version: u64, + pub tariff_digest: String, + pub payer_id: String, + pub payer_financial_address: String, + pub money: Money, + pub simulation: bool, +} + +impl BillSnapshot { + pub fn validate_for(&self, connection: &PaymentConnection) -> Result<(), PaymentProblemCode> { + if self.bill_id.is_nil() + || self.bill_version == 0 + || self.bill_version > MAX_MINOR_UNITS + || self.institution_id != connection.institution_id + || self.service_id != connection.service_id + || !self.simulation + || !connection.binding.simulation + || self.money.currency != connection.binding.currency + || self.money.scale != connection.binding.currency_scale + || !super::config::text(&self.bill_digest, 64) + || self.bill_digest.len() != 64 + || !super::config::text(&self.request_id, 128) + || !super::config::text(&self.tariff_id, 128) + || !super::config::text(&self.tariff_digest, 64) + || self.tariff_digest.len() != 64 + || self.tariff_version == 0 + || self.tariff_version > MAX_MINOR_UNITS + || !super::config::text(&self.payer_id, 128) + || !super::config::text(&self.payer_financial_address, 30) + { + return Err(PaymentProblemCode::Conflict); + } + self.money + .minor_units() + .map_err(|_| PaymentProblemCode::Conflict)?; + Ok(()) + } + pub fn digest(&self) -> Result { + digest(self) + } + + /// Stable across independent Adapter stores. The complete bill and logical + /// provider namespace bind the command; credentials and replay policy do not + /// create another financial identity. The persisted command is never edited. + pub fn provider_command( + &self, + binding: &PaymentBinding, + ) -> Result { + let origin = url::Url::parse(&binding.provider.base_url) + .map_err(|_| PaymentProblemCode::Unavailable)?; + let identity = serde_json::json!({ + "domain": "registry-adapter/payment-provider-command/v1", + "provider": { + "origin": origin.as_str(), + "producer": binding.provider_credential_identity, + "tenant": binding.provider.tenant, + "biller": binding.provider.biller, + }, + "bill": self, + }); + let canonical = registry_platform_canonical_json::canonicalize_json(&identity) + .map_err(|_| PaymentProblemCode::Unavailable)?; + let digest = Sha256::digest(canonical); + // Disjoint digest portions retain 180 bits across the bounded wire tuple. + // A requestId collision with a different body must remain a provider conflict. + let mut number = [0_u8; 8]; + number[1..].copy_from_slice(&digest[16..23]); + let command = ProviderCommand { + request_id: URL_SAFE_NO_PAD.encode(&digest[..9]), + bill_id: URL_SAFE_NO_PAD.encode(&digest[9..16]), + rtp_id: (u64::from_be_bytes(number) & ((1_u64 << 52) - 1)) + 1, + payer_address: self.payer_financial_address.clone(), + money: self.money.clone(), + }; + command + .validate() + .map_err(|_| PaymentProblemCode::Unavailable)?; + Ok(command) + } +} + +#[derive(Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct PreparedRegistryAction { + pub action: String, + pub key: String, + pub inputs: Map, + pub evidence: String, +} + +#[derive(Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct Attempt { + pub id: Uuid, + pub connection: String, + pub principal: String, + pub bill: BillSnapshot, + pub bill_snapshot_digest: String, + pub binding: PaymentBinding, + pub binding_revision: String, + pub provider_command: ProviderCommand, + pub bind_action: Option, + pub bound: bool, + pub first_send_at: Option, + pub transfer_id: Option, + pub observation: Option, + pub report_action: Option, + pub receipt_digest: Option, + pub receipt: Option, +} + +impl Attempt { + pub fn acceptance(&self) -> CollectionAccepted { + CollectionAccepted { + collection_id: self.id, + bill_id: self.bill.bill_id, + bill_version: self.bill.bill_version, + binding_revision: self.binding_revision.clone(), + simulation: self.bill.simulation, + } + } + + pub fn status(&self) -> CollectionStatus { + let (state, reference, failure) = self.observation.as_ref().map_or( + ( + if self.transfer_id.is_some() { + CollectionState::Accepted + } else { + CollectionState::Unknown + }, + None, + None, + ), + |o| { + ( + o.state, + o.provider_reference.clone(), + o.failure_reason.clone(), + ) + }, + ); + CollectionStatus { + collection_id: self.id, + bill_id: self.bill.bill_id, + bill_version: self.bill.bill_version, + binding_revision: self.binding_revision.clone(), + simulation: self.bill.simulation, + state, + money: self.bill.money.clone(), + provider_reference: reference, + failure_reason: failure, + } + } + + pub fn may_dispatch(&self, now: i64) -> Result<(), PaymentProblemCode> { + if !self.bound { + return Err(PaymentProblemCode::Conflict); + } + if let Some(first) = self.first_send_at { + if now < first + || u64::try_from(now - first).map_err(|_| PaymentProblemCode::RecoveryHeld)? + >= self.binding.replay_window_seconds + { + return Err(PaymentProblemCode::RecoveryHeld); + } + } + Ok(()) + } + + pub fn validate_integrity(&self) -> Result<(), PaymentProblemCode> { + if self + .binding + .revision() + .map_err(|_| PaymentProblemCode::Unavailable)? + != self.binding_revision + || self.bill.digest()? != self.bill_snapshot_digest + || !self.bill.simulation + || !self.binding.simulation + || self.provider_command != self.bill.provider_command(&self.binding)? + { + return Err(PaymentProblemCode::Unavailable); + } + self.provider_command + .validate() + .map_err(|_| PaymentProblemCode::Unavailable)?; + self.status() + .validate() + .map_err(|_| PaymentProblemCode::Unavailable)?; + Ok(()) + } +} + +pub fn digest(value: &impl Serialize) -> Result { + let value = serde_json::to_value(value).map_err(|_| PaymentProblemCode::Unavailable)?; + let bytes = registry_platform_canonical_json::canonicalize_json(&value) + .map_err(|_| PaymentProblemCode::Unavailable)?; + Ok(registry_platform_config::sha256_uri(&bytes)) +} diff --git a/crates/registry-adapter/src/payments/registry.rs b/crates/registry-adapter/src/payments/registry.rs new file mode 100644 index 0000000000..311365acd8 --- /dev/null +++ b/crates/registry-adapter/src/payments/registry.rs @@ -0,0 +1,326 @@ +// SPDX-License-Identifier: Apache-2.0 +//! Restricted BReg bill reads and exact prepared Actions through its public client. + +use super::{ + config::PaymentBinding, + model::{Attempt, BillSnapshot, PreparedRegistryAction}, +}; +use async_trait::async_trait; +use registry_breg_client::{ + BRegActionInvocationRequest, BRegActionTargetConditionsRequest, BRegIdempotencyKey, + BRegPreparedAction, BRegRecordOptions, BaseRegistryClient, BaseRegistryClientConfig, + StaticToken, +}; +use registry_payment_protocol::{ + Money, PaymentProblemCode as Error, RegistryReceipt, MAX_MINOR_UNITS, +}; +use registry_platform_config::SecretResolver; +use serde_json::{json, Map, Value}; +use std::{collections::BTreeMap, sync::Arc, time::Duration}; +use uuid::Uuid; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum BillState { + DueUnbound, + AttemptBound, + Paid, + Issued, +} + +#[derive(Clone)] +pub struct BillView { + pub snapshot: BillSnapshot, + pub state: BillState, + pub attempt_id: Option, + pub binding_revision: Option, + pub receipt_id: Option, + pub provider_reference: Option, + pub receipt_digest: Option, +} + +impl BillView { + pub fn decode(id: Uuid, data: BTreeMap) -> Result { + let string = |key: &str| { + data.get(key) + .and_then(Value::as_str) + .map(str::to_owned) + .ok_or(Error::Unavailable) + }; + let integer = |key: &str| { + data.get(key) + .and_then(Value::as_u64) + .filter(|v| *v <= MAX_MINOR_UNITS) + .ok_or(Error::Unavailable) + }; + let optional = |key: &str| match data.get(key) { + None | Some(Value::Null) => Ok(None), + Some(Value::String(s)) if !s.is_empty() => Ok(Some(s.clone())), + _ => Err(Error::Unavailable), + }; + let minor = integer("amountMinor")?; + let scale = u8::try_from(integer("currencyScale")?).map_err(|_| Error::Unavailable)?; + if scale > 6 || minor == 0 { + return Err(Error::Unavailable); + } + let factor = 10_u64.pow(u32::from(scale)); + let value = if scale == 0 { + minor.to_string() + } else { + format!( + "{}.{:0width$}", + minor / factor, + minor % factor, + width = usize::from(scale) + ) + }; + let money = Money { + value, + currency: string("currency")?, + scale, + }; + money.minor_units().map_err(|_| Error::Unavailable)?; + let snapshot = BillSnapshot { + bill_id: id, + bill_version: integer("billVersion")?, + bill_digest: string("billDigest")?, + institution_id: string("institutionId")?, + service_id: string("serviceId")?, + request_id: string("requestId")?, + tariff_id: string("tariffId")?, + tariff_version: integer("tariffVersion")?, + tariff_digest: string("tariffDigest")?, + payer_id: string("payerId")?, + payer_financial_address: string("payerFinancialAddress")?, + money, + simulation: data + .get("simulation") + .and_then(Value::as_bool) + .ok_or(Error::Unavailable)?, + }; + let state = match string("paymentState")?.as_str() { + "due-unbound" => BillState::DueUnbound, + "attempt-bound" => BillState::AttemptBound, + "paid" => BillState::Paid, + "issued" => BillState::Issued, + _ => return Err(Error::Unavailable), + }; + let attempt_id = optional("paymentAttemptId")? + .map(|v| Uuid::parse_str(&v).map_err(|_| Error::Unavailable)) + .transpose()?; + Ok(Self { + snapshot, + state, + attempt_id, + binding_revision: optional("providerBindingRevision")?, + receipt_id: optional("paymentReceiptId")?, + provider_reference: optional("providerReference")?, + receipt_digest: optional("receiptDigest")?, + }) + } + + pub fn matches_binding(&self, attempt: &Attempt) -> bool { + self.snapshot == attempt.bill + && self.attempt_id == Some(attempt.id) + && self.binding_revision.as_deref() == Some(&attempt.binding_revision) + && matches!( + self.state, + BillState::AttemptBound | BillState::Paid | BillState::Issued + ) + } + + pub fn matches_receipt( + &self, + attempt: &Attempt, + receipt: &RegistryReceipt, + digest: &str, + ) -> bool { + self.matches_binding(attempt) + && matches!(self.state, BillState::Paid | BillState::Issued) + && self.receipt_id.as_deref() == Some(&receipt.receipt_id) + && self.provider_reference.as_deref() == Some(&receipt.provider_reference) + && self.receipt_digest.as_deref() == Some(digest) + } +} + +pub fn binding_inputs(attempt: &Attempt) -> Result, Error> { + let bill = &attempt.bill; + let value = json!({"billId":bill.bill_id,"billVersion":bill.bill_version,"billDigest":bill.bill_digest, + "institutionId":bill.institution_id,"serviceId":bill.service_id,"requestId":bill.request_id, + "tariffId":bill.tariff_id,"tariffVersion":bill.tariff_version,"tariffDigest":bill.tariff_digest, + "payerId":bill.payer_id,"payerFinancialAddress":bill.payer_financial_address, + "amountMinor":bill.money.minor_units().map_err(|_| Error::Unavailable)?,"currency":bill.money.currency,"currencyScale":bill.money.scale, + "simulation":bill.simulation,"paymentAttemptId":attempt.id,"providerBindingRevision":attempt.binding_revision}); + value.as_object().cloned().ok_or(Error::Unavailable) +} + +#[async_trait] +pub trait RegistryPort: Send + Sync { + async fn read_bill(&self, binding: &PaymentBinding, id: Uuid) -> Result; + async fn prepare( + &self, + binding: &PaymentBinding, + receipt: bool, + key: &str, + inputs: Map, + ) -> Result; + async fn invoke( + &self, + binding: &PaymentBinding, + receipt: bool, + prepared: &PreparedRegistryAction, + ) -> Result<(), Error>; +} + +pub struct BregBridge { + resolver: Arc, +} +impl BregBridge { + pub fn new(resolver: Arc) -> Self { + Self { resolver } + } + fn client(&self, binding: &PaymentBinding) -> Result { + let secret = self + .resolver + .resolve(binding.registry.credential_ref.as_str()) + .map_err(|_| Error::Unavailable)?; + let token = std::str::from_utf8(secret.expose_secret()).map_err(|_| Error::Unavailable)?; + let provider = StaticToken::new(token.to_owned()).map_err(|_| Error::Unavailable)?; + let url = url::Url::parse(&binding.registry.base_url).map_err(|_| Error::Unavailable)?; + BaseRegistryClient::new( + BaseRegistryClientConfig::new(url) + .with_token_provider(Arc::new(provider)) + .with_attempt_timeout(Duration::from_secs(15)) + .with_connect_timeout(Duration::from_secs(5)) + .with_maximum_response_bytes(65_536) + .with_maximum_mutation_retries(0), + ) + .map_err(|_| Error::Unavailable) + } +} + +#[async_trait] +impl RegistryPort for BregBridge { + async fn read_bill(&self, binding: &PaymentBinding, id: Uuid) -> Result { + let client = self.client(binding)?; + let options = BRegRecordOptions::default() + .access_profile(&binding.registry.read_profile) + .map_err(|_| Error::Unavailable)?; + let response = client + .get_record(&binding.registry.record_route, &id.to_string(), &options) + .await + .map_err(|_| Error::Unavailable)? + .value; + if response.meta.record_type_identifier != binding.registry.record_type + || response.data.record_identifier != id.to_string() + { + return Err(Error::Unavailable); + } + BillView::decode(id, response.data.domain_data) + } + + async fn prepare( + &self, + binding: &PaymentBinding, + receipt: bool, + key: &str, + inputs: Map, + ) -> Result { + let client = self.client(binding)?; + let (action, profile) = if receipt { + ( + &binding.registry.receipt_action, + &binding.registry.receipt_profile, + ) + } else { + ( + &binding.registry.bind_action, + &binding.registry.bind_profile, + ) + }; + let metadata = client + .registry_contract(Some(profile)) + .await + .map_err(|_| Error::Unavailable)? + .value; + let selected = metadata + .select_action(action, profile) + .map_err(|_| Error::Unavailable)?; + let key = BRegIdempotencyKey::parse(key).map_err(|_| Error::Unavailable)?; + let conditions = if selected.required_condition_keys().is_empty() { + None + } else { + let references = selected + .required_condition_keys() + .iter() + .map(|key| inputs.get(key).cloned().map(|v| (key.clone(), v))) + .collect::>>() + .ok_or(Error::Unavailable)?; + let request = BRegActionTargetConditionsRequest::new(&selected, references) + .map_err(|_| Error::Unavailable)?; + Some( + client + .action_target_conditions(&selected, &request) + .await + .map_err(|_| Error::Unavailable)? + .value, + ) + }; + let request = + BRegActionInvocationRequest::new(&selected, inputs.clone(), conditions.as_ref()) + .map_err(|_| Error::Unavailable)?; + let evidence = client + .prepare_action(&selected, &request, &key) + .map_err(|_| Error::Unavailable)?; + let evidence = std::str::from_utf8(evidence.as_bytes()) + .map_err(|_| Error::Unavailable)? + .to_owned(); + Ok(PreparedRegistryAction { + action: action.clone(), + key: key.as_str().to_owned(), + inputs, + evidence, + }) + } + + async fn invoke( + &self, + binding: &PaymentBinding, + receipt: bool, + prepared: &PreparedRegistryAction, + ) -> Result<(), Error> { + let client = self.client(binding)?; + let (action, profile) = if receipt { + ( + &binding.registry.receipt_action, + &binding.registry.receipt_profile, + ) + } else { + ( + &binding.registry.bind_action, + &binding.registry.bind_profile, + ) + }; + if action != &prepared.action { + return Err(Error::RecoveryHeld); + } + let metadata = client + .registry_contract(Some(profile)) + .await + .map_err(|_| Error::Unavailable)? + .value; + let selected = metadata + .select_action(action, profile) + .map_err(|_| Error::RecoveryHeld)?; + let key = BRegIdempotencyKey::parse(&prepared.key).map_err(|_| Error::RecoveryHeld)?; + let saved = BRegPreparedAction::from_slice(prepared.evidence.as_bytes()) + .map_err(|_| Error::RecoveryHeld)?; + let request = client + .recover_action(&selected, &saved, &prepared.inputs, &key) + .map_err(|_| Error::RecoveryHeld)?; + client + .invoke_action(&selected, &request, &key) + .await + .map_err(|_| Error::OutcomeUnknown)?; + Ok(()) + } +} diff --git a/crates/registry-adapter/src/payments/service.rs b/crates/registry-adapter/src/payments/service.rs new file mode 100644 index 0000000000..f2f0a6cdf3 --- /dev/null +++ b/crates/registry-adapter/src/payments/service.rs @@ -0,0 +1,579 @@ +// SPDX-License-Identifier: Apache-2.0 +//! Explicitly initiated collection, observation, and receipt operations. + +use super::{ + config::{PaymentBinding, PaymentConnection, PaymentsConfig}, + model::{digest, Attempt}, + registry::{binding_inputs, BillState, RegistryPort}, + store::PaymentStore, +}; +use crate::serve::Caller; +use async_trait::async_trait; +use registry_payment_protocol::{ + CollectionAccepted, CollectionState, CollectionStatus, PaymentProblemCode as Error, + RegistryReceipt, RequestCollection, +}; +use registry_payment_simulator_connector::{ + ConnectorError, Observation, ProviderCommand, SimulatorClient, +}; +use registry_platform_config::SecretResolver; +use registry_platform_httputil::client::BearerToken; +use std::sync::Arc; +use tokio::sync::Semaphore; +use uuid::Uuid; + +#[async_trait] +pub trait ProviderPort: Send + Sync { + async fn submit( + &self, + binding: &PaymentBinding, + command: &ProviderCommand, + ) -> Result; + async fn observe( + &self, + binding: &PaymentBinding, + command: &ProviderCommand, + transfer: &str, + ) -> Result; +} + +pub struct SyntheticProvider { + resolver: Arc, +} +impl SyntheticProvider { + pub fn new(resolver: Arc) -> Self { + Self { resolver } + } + fn token(&self, binding: &PaymentBinding) -> Result { + let secret = self + .resolver + .resolve(binding.provider_credential_ref.as_str()) + .map_err(|_| ConnectorError::Unavailable)?; + let token = + std::str::from_utf8(secret.expose_secret()).map_err(|_| ConnectorError::Unavailable)?; + BearerToken::new(token.to_owned()).map_err(|_| ConnectorError::Unavailable) + } +} +#[async_trait] +impl ProviderPort for SyntheticProvider { + async fn submit( + &self, + binding: &PaymentBinding, + command: &ProviderCommand, + ) -> Result { + SimulatorClient::new(binding.provider.clone())? + .submit(command, &self.token(binding)?) + .await + } + async fn observe( + &self, + binding: &PaymentBinding, + command: &ProviderCommand, + transfer: &str, + ) -> Result { + SimulatorClient::new(binding.provider.clone())? + .observe(command, transfer, &self.token(binding)?) + .await + } +} + +pub struct PaymentService { + config: PaymentsConfig, + store: PaymentStore, + registry: Arc, + provider: Arc, + // Each in-flight attempt holds one lock transaction and can use one + // additional store connection. Bound concurrency leaves pool capacity for + // commits; try-lock refuses contention without consuming a waiting slot. + calls: Arc, +} + +impl PaymentService { + pub fn new( + config: PaymentsConfig, + store: PaymentStore, + registry: Arc, + provider: Arc, + ) -> Result { + config.validate().map_err(|_| Error::Unavailable)?; + Ok(Self { + config, + store, + registry, + provider, + calls: Arc::new(Semaphore::new(8)), + }) + } + + pub async fn audit_access( + &self, + caller: &Caller, + operation: &str, + id: Option, + error: Option, + ) -> Result<(), Error> { + let kind = format!("{operation}.{}", error.map_or("released", Error::as_str)); + self.store + .audit_access(&principal(caller)?, &kind, id) + .await + } + + fn connection(&self, id: &str, caller: &Caller) -> Result<&PaymentConnection, Error> { + let connection = self + .config + .connections + .iter() + .find(|c| c.id == id) + .ok_or(Error::NotFound)?; + if !connection.allowed_clients.contains(&caller.client_id) + || !caller.scopes.contains(&connection.required_scope) + { + return Err(Error::Forbidden); + } + Ok(connection) + } + + fn authorize( + attempt: &Attempt, + connection: &PaymentConnection, + principal: &str, + ) -> Result<(), Error> { + if attempt.connection != connection.id + || attempt.principal != principal + || attempt.bill.institution_id != connection.institution_id + || attempt.bill.service_id != connection.service_id + { + return Err(Error::NotFound); + } + Ok(()) + } + + pub async fn request( + &self, + id: &str, + caller: &Caller, + key: &str, + request: &RequestCollection, + ) -> Result { + let connection = self.connection(id, caller)?; + validate_key(key)?; + request.validate().map_err(|_| Error::InvalidRequest)?; + let principal = principal(caller)?; + let request_digest = digest(request)?; + let _permit = self + .calls + .clone() + .try_acquire_owned() + .map_err(|_| Error::Unavailable)?; + let attempt_id = if let Some(saved) = self + .store + .lookup_command(id, &principal, "request", key, &request_digest) + .await? + { + saved + } else if let Some(saved) = self + .store + .find_bill( + &connection.institution_id, + &connection.service_id, + request.bill_id, + request.bill_version, + ) + .await? + { + Self::authorize(&saved, connection, &principal)?; + self.store + .claim_command(id, &principal, "request", key, &request_digest, saved.id) + .await?; + saved.id + } else { + let view = self + .registry + .read_bill(&connection.binding, request.bill_id) + .await?; + view.snapshot.validate_for(connection)?; + if view.snapshot.bill_version != request.bill_version + || view.state != BillState::DueUnbound + || view.attempt_id.is_some() + { + return Err(Error::Conflict); + } + let candidate = Attempt { + id: Uuid::new_v4(), + connection: id.to_owned(), + principal: principal.clone(), + bill_snapshot_digest: view.snapshot.digest()?, + binding: connection.binding.clone(), + binding_revision: connection + .binding + .revision() + .map_err(|_| Error::Unavailable)?, + provider_command: view.snapshot.provider_command(&connection.binding)?, + bill: view.snapshot, + bind_action: None, + bound: false, + first_send_at: None, + transfer_id: None, + observation: None, + report_action: None, + receipt_digest: None, + receipt: None, + }; + self.store + .reserve(&candidate, key, &request_digest) + .await? + .id + }; + let mut lock_client = self + .store + .pool + .get() + .await + .map_err(|_| Error::Unavailable)?; + let lock = lock_client + .transaction() + .await + .map_err(|_| Error::Unavailable)?; + self.lock_attempt(&lock, attempt_id).await?; + let mut attempt = self.store.get(attempt_id).await?; + Self::authorize(&attempt, connection, &principal)?; + if attempt.transfer_id.is_some() { + return Ok(attempt.acceptance()); + } + self.ensure_bound(&mut attempt).await?; + let bill = self + .registry + .read_bill(&attempt.binding, attempt.bill.bill_id) + .await?; + if !bill.matches_binding(&attempt) || bill.state != BillState::AttemptBound { + return Err(Error::Conflict); + } + let now = time::OffsetDateTime::now_utc().unix_timestamp(); + attempt.may_dispatch(now)?; + if attempt.first_send_at.is_none() { + attempt.first_send_at = Some(now); + } + self.store.save(&attempt, "provider.dispatching").await?; + let transfer = match self + .provider + .submit(&attempt.binding, &attempt.provider_command) + .await + { + Ok(transfer) => transfer, + Err(_) => { + self.store + .save(&attempt, "provider.unknown") + .await + .map_err(|_| Error::OutcomeUnknown)?; + return Err(Error::OutcomeUnknown); + } + }; + attempt.transfer_id = Some(transfer); + self.store + .save(&attempt, "provider.accepted") + .await + .map_err(|_| Error::OutcomeUnknown)?; + Ok(attempt.acceptance()) + } + + async fn ensure_bound(&self, attempt: &mut Attempt) -> Result<(), Error> { + if attempt.bound { + return Ok(()); + } + let view = self + .registry + .read_bill(&attempt.binding, attempt.bill.bill_id) + .await?; + if view.matches_binding(attempt) { + attempt.bound = true; + return self.store.save(attempt, "binding.recovered").await; + } + if view.snapshot != attempt.bill + || view.state != BillState::DueUnbound + || view.attempt_id.is_some() + { + return Err(Error::Conflict); + } + if attempt.bind_action.is_none() { + let inputs = binding_inputs(attempt)?; + let prepared = self + .registry + .prepare( + &attempt.binding, + false, + &format!("payment-bind-{}", attempt.id), + inputs, + ) + .await?; + attempt.bind_action = Some(prepared); + self.store.save(attempt, "binding.prepared").await?; + } + let result = self + .registry + .invoke( + &attempt.binding, + false, + attempt.bind_action.as_ref().ok_or(Error::Unavailable)?, + ) + .await; + let observed = self + .registry + .read_bill(&attempt.binding, attempt.bill.bill_id) + .await + .map_err(|_| Error::OutcomeUnknown)?; + if !observed.matches_binding(attempt) { + return Err(result.err().unwrap_or(Error::OutcomeUnknown)); + } + attempt.bound = true; + self.store + .save(attempt, "binding.verified") + .await + .map_err(|_| Error::OutcomeUnknown) + } + + /// Strictly local receipt lookup. It never binds, dispatches or records. + pub async fn request_receipt( + &self, + id: &str, + caller: &Caller, + key: &str, + request: &RequestCollection, + ) -> Result { + let connection = self.connection(id, caller)?; + validate_key(key)?; + request.validate().map_err(|_| Error::InvalidRequest)?; + let principal = principal(caller)?; + let saved = self + .store + .lookup_command(id, &principal, "request", key, &digest(request)?) + .await? + .ok_or(Error::ReceiptUnresolved)?; + let attempt = self.store.get(saved).await?; + Self::authorize(&attempt, connection, &principal)?; + if attempt.transfer_id.is_none() { + return Err(Error::ReceiptUnresolved); + } + Ok(attempt.acceptance()) + } + + pub async fn read( + &self, + id: &str, + caller: &Caller, + collection: Uuid, + ) -> Result { + let connection = self.connection(id, caller)?; + let principal = principal(caller)?; + let _permit = self + .calls + .clone() + .try_acquire_owned() + .map_err(|_| Error::Unavailable)?; + let initial = self.store.get(collection).await?; + Self::authorize(&initial, connection, &principal)?; + let mut lock_client = self + .store + .pool + .get() + .await + .map_err(|_| Error::Unavailable)?; + let lock = lock_client + .transaction() + .await + .map_err(|_| Error::Unavailable)?; + self.lock_attempt(&lock, collection).await?; + let mut attempt = self.store.get(collection).await?; + if matches!( + attempt.status().state, + CollectionState::Confirmed | CollectionState::Failed + ) { + return Ok(attempt.status()); + } + let Some(transfer) = &attempt.transfer_id else { + return Ok(attempt.status()); + }; + let observation = self + .provider + .observe(&attempt.binding, &attempt.provider_command, transfer) + .await + .map_err(|e| { + if e == ConnectorError::Protocol { + Error::ProviderProtocol + } else { + Error::Unavailable + } + })?; + if attempt + .observation + .as_ref() + .is_some_and(|old| observation.observed_at < old.observed_at) + { + return Err(Error::ProviderProtocol); + } + attempt.observation = Some(observation); + self.store.save(&attempt, "provider.observed").await?; + Ok(attempt.status()) + } + + pub async fn record_receipt( + &self, + id: &str, + caller: &Caller, + key: &str, + collection: Uuid, + ) -> Result { + let connection = self.connection(id, caller)?; + validate_key(key)?; + let principal = principal(caller)?; + let _permit = self + .calls + .clone() + .try_acquire_owned() + .map_err(|_| Error::Unavailable)?; + let initial = self.store.get(collection).await?; + Self::authorize(&initial, connection, &principal)?; + self.store + .claim_command( + id, + &principal, + "receipt", + key, + &digest(®istry_payment_protocol::RecordReceipt { + collection_id: collection, + })?, + collection, + ) + .await?; + let mut lock_client = self + .store + .pool + .get() + .await + .map_err(|_| Error::Unavailable)?; + let lock = lock_client + .transaction() + .await + .map_err(|_| Error::Unavailable)?; + self.lock_attempt(&lock, collection).await?; + let mut attempt = self.store.get(collection).await?; + if let Some(receipt) = &attempt.receipt { + return Ok(receipt.clone()); + } + let status = attempt.status(); + if status.state != CollectionState::Confirmed || !status.simulation { + return Err(Error::Conflict); + } + let reference = status.provider_reference.ok_or(Error::Conflict)?; + if !reference.starts_with("SIM-") { + return Err(Error::Conflict); + } + let receipt = RegistryReceipt { + collection_id: attempt.id, + bill_id: attempt.bill.bill_id, + bill_version: attempt.bill.bill_version, + binding_revision: attempt.binding_revision.clone(), + simulation: attempt.bill.simulation, + money: attempt.bill.money.clone(), + provider_reference: reference, + receipt_id: format!("payment-{}", attempt.id), + }; + receipt.validate().map_err(|_| Error::Unavailable)?; + let receipt_digest = digest(&receipt)? + .strip_prefix("sha256:") + .ok_or(Error::Unavailable)? + .to_owned(); + let view = self + .registry + .read_bill(&attempt.binding, attempt.bill.bill_id) + .await?; + if view.matches_receipt(&attempt, &receipt, &receipt_digest) { + attempt.receipt = Some(receipt.clone()); + attempt.receipt_digest = Some(receipt_digest); + self.store.save(&attempt, "receipt.recovered").await?; + return Ok(receipt); + } + if !view.matches_binding(&attempt) || view.state != BillState::AttemptBound { + return Err(Error::Conflict); + } + if attempt.report_action.is_none() { + let mut inputs = binding_inputs(&attempt)?; + inputs.insert( + "paymentReceiptId".into(), + serde_json::json!(receipt.receipt_id), + ); + inputs.insert( + "providerReference".into(), + serde_json::json!(receipt.provider_reference), + ); + inputs.insert("receiptDigest".into(), serde_json::json!(receipt_digest)); + attempt.report_action = Some( + self.registry + .prepare( + &attempt.binding, + true, + &format!("payment-receipt-{}", attempt.id), + inputs, + ) + .await?, + ); + attempt.receipt_digest = Some(receipt_digest.clone()); + self.store.save(&attempt, "receipt.prepared").await?; + } + if attempt.receipt_digest.as_ref() != Some(&receipt_digest) { + return Err(Error::RecoveryHeld); + } + let result = self + .registry + .invoke( + &attempt.binding, + true, + attempt.report_action.as_ref().ok_or(Error::Unavailable)?, + ) + .await; + let observed = self + .registry + .read_bill(&attempt.binding, attempt.bill.bill_id) + .await + .map_err(|_| Error::OutcomeUnknown)?; + if !observed.matches_receipt(&attempt, &receipt, &receipt_digest) { + return Err(result.err().unwrap_or(Error::OutcomeUnknown)); + } + attempt.receipt = Some(receipt.clone()); + self.store + .save(&attempt, "receipt.recorded") + .await + .map_err(|_| Error::OutcomeUnknown)?; + Ok(receipt) + } + + async fn lock_attempt( + &self, + tx: &tokio_postgres::Transaction<'_>, + id: Uuid, + ) -> Result<(), Error> { + let name = format!("adapter-payment/{}/{}", self.store.deployment, id); + let row = tx + .query_one( + "SELECT pg_try_advisory_xact_lock(hashtextextended($1, 0))", + &[&name], + ) + .await + .map_err(|_| Error::Unavailable)?; + if row.get::<_, bool>(0) { + Ok(()) + } else { + Err(Error::Unavailable) + } + } +} + +fn principal(caller: &Caller) -> Result { + digest(&[&caller.issuer, &caller.client_id, &caller.reference]) +} +fn validate_key(key: &str) -> Result<(), Error> { + if super::config::text(key, 128) { + Ok(()) + } else { + Err(Error::InvalidRequest) + } +} diff --git a/crates/registry-adapter/src/payments/store.rs b/crates/registry-adapter/src/payments/store.rs new file mode 100644 index 0000000000..3201d38097 --- /dev/null +++ b/crates/registry-adapter/src/payments/store.rs @@ -0,0 +1,293 @@ +// SPDX-License-Identifier: Apache-2.0 +//! PostgreSQL attempt custody, separate from generic record-facade idempotency. + +use super::model::Attempt; +use deadpool_postgres::Pool; +use registry_payment_protocol::PaymentProblemCode as Error; +use tokio_postgres::{Client, GenericClient}; +use uuid::Uuid; + +const SCHEMA: &str = r#" +CREATE TABLE IF NOT EXISTS adapter_payment_attempts ( + id uuid PRIMARY KEY, + deployment text NOT NULL, + connection text NOT NULL, + principal text NOT NULL, + institution text NOT NULL, + service text NOT NULL, + bill_id uuid NOT NULL, + bill_version bigint NOT NULL CHECK (bill_version > 0), + document jsonb NOT NULL CHECK (jsonb_typeof(document) = 'object'), + updated_at timestamptz NOT NULL DEFAULT clock_timestamp(), + UNIQUE (deployment, institution, service, bill_id, bill_version) +); +CREATE TABLE IF NOT EXISTS adapter_payment_commands ( + deployment text NOT NULL, + connection text NOT NULL, + principal text NOT NULL, + operation text NOT NULL, + command_key text NOT NULL, + request_digest text NOT NULL, + attempt_id uuid NOT NULL, + PRIMARY KEY (deployment, connection, principal, operation, command_key) +); +CREATE TABLE IF NOT EXISTS adapter_payment_events ( + sequence bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, + deployment text NOT NULL, + attempt_id uuid NOT NULL, + principal text NOT NULL, + kind text NOT NULL, + created_at timestamptz NOT NULL DEFAULT clock_timestamp() +); +"#; + +pub async fn migrate(client: &mut Client) -> Result<(), Error> { + let tx = client.transaction().await.map_err(|_| Error::Unavailable)?; + tx.execute("SELECT pg_advisory_xact_lock(1879751387, 1)", &[]) + .await + .map_err(|_| Error::Unavailable)?; + tx.batch_execute(SCHEMA) + .await + .map_err(|_| Error::Unavailable)?; + tx.commit().await.map_err(|_| Error::Unavailable) +} + +#[derive(Clone)] +pub struct PaymentStore { + pub(crate) pool: Pool, + pub(crate) deployment: String, +} + +impl PaymentStore { + pub fn new(pool: Pool, deployment: String) -> Self { + Self { pool, deployment } + } + + pub async fn audit_access( + &self, + principal: &str, + kind: &str, + id: Option, + ) -> Result<(), Error> { + let client = self.pool.get().await.map_err(|_| Error::Unavailable)?; + client.execute("INSERT INTO adapter_payment_events (deployment,attempt_id,principal,kind) VALUES ($1,$2,$3,$4)", + &[&self.deployment,&id.unwrap_or(Uuid::nil()),&principal,&kind]).await.map_err(|_| Error::Unavailable)?; + Ok(()) + } + + pub async fn check_privileges(&self) -> Result<(), Error> { + let client = self.pool.get().await.map_err(|_| Error::Unavailable)?; + for (table, privileges) in [ + ( + "adapter_payment_attempts", + &["SELECT", "INSERT", "UPDATE"][..], + ), + ("adapter_payment_commands", &["SELECT", "INSERT"][..]), + ("adapter_payment_events", &["SELECT", "INSERT"][..]), + ] { + if !crate::journal::missing_table_privileges(&client, table, privileges) + .await + .map_err(|_| Error::Unavailable)? + .is_empty() + { + return Err(Error::Unavailable); + } + } + let row = client + .query_one( + "SELECT has_sequence_privilege(current_user, $1, 'USAGE')", + &[&"adapter_payment_events_sequence_seq"], + ) + .await + .map_err(|_| Error::Unavailable)?; + if !row.get::<_, bool>(0) { + return Err(Error::Unavailable); + } + Ok(()) + } + + pub async fn lookup_command( + &self, + connection: &str, + principal: &str, + operation: &str, + key: &str, + digest: &str, + ) -> Result, Error> { + let client = self.pool.get().await.map_err(|_| Error::Unavailable)?; + command( + &**client, + &self.deployment, + connection, + principal, + operation, + key, + digest, + ) + .await + } + + pub async fn claim_command( + &self, + connection: &str, + principal: &str, + operation: &str, + key: &str, + digest: &str, + id: Uuid, + ) -> Result<(), Error> { + let mut client = self.pool.get().await.map_err(|_| Error::Unavailable)?; + let tx = client.transaction().await.map_err(|_| Error::Unavailable)?; + claim( + &*tx, + &self.deployment, + connection, + principal, + operation, + key, + digest, + id, + ) + .await?; + tx.commit().await.map_err(|_| Error::Unavailable) + } + + /// A bill is unique across command keys and workflow runs. Another admitted + /// key for the same caller/connection aliases the retained original attempt. + pub async fn reserve( + &self, + candidate: &Attempt, + key: &str, + request_digest: &str, + ) -> Result { + let mut client = self.pool.get().await.map_err(|_| Error::Unavailable)?; + let tx = client.transaction().await.map_err(|_| Error::Unavailable)?; + let document = serde_json::to_value(candidate).map_err(|_| Error::Unavailable)?; + let version = + i64::try_from(candidate.bill.bill_version).map_err(|_| Error::InvalidRequest)?; + let inserted=tx.execute( + "INSERT INTO adapter_payment_attempts (id,deployment,connection,principal,institution,service,bill_id,bill_version,document) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9) ON CONFLICT DO NOTHING", + &[&candidate.id,&self.deployment,&candidate.connection,&candidate.principal,&candidate.bill.institution_id,&candidate.bill.service_id,&candidate.bill.bill_id,&version,&document] + ).await.map_err(|_| Error::Unavailable)?; + let row=tx.query_one("SELECT document FROM adapter_payment_attempts WHERE deployment=$1 AND institution=$2 AND service=$3 AND bill_id=$4 AND bill_version=$5", + &[&self.deployment,&candidate.bill.institution_id,&candidate.bill.service_id,&candidate.bill.bill_id,&version]).await.map_err(|_| Error::Unavailable)?; + let saved: Attempt = serde_json::from_value(row.get(0)).map_err(|_| Error::Unavailable)?; + if saved.connection != candidate.connection || saved.principal != candidate.principal { + return Err(Error::Conflict); + } + claim( + &*tx, + &self.deployment, + &saved.connection, + &saved.principal, + "request", + key, + request_digest, + saved.id, + ) + .await?; + if inserted == 1 { + event(&*tx, &self.deployment, &saved, "attempt.reserved").await?; + } + tx.commit().await.map_err(|_| Error::Unavailable)?; + saved.validate_integrity()?; + Ok(saved) + } + + pub async fn find_bill( + &self, + institution: &str, + service: &str, + bill: Uuid, + version: u64, + ) -> Result, Error> { + let client = self.pool.get().await.map_err(|_| Error::Unavailable)?; + let version = i64::try_from(version).map_err(|_| Error::InvalidRequest)?; + let row=client.query_opt("SELECT document FROM adapter_payment_attempts WHERE deployment=$1 AND institution=$2 AND service=$3 AND bill_id=$4 AND bill_version=$5", + &[&self.deployment,&institution,&service,&bill,&version]).await.map_err(|_| Error::Unavailable)?; + row.map(|row| decode(row.get(0))).transpose() + } + + pub async fn get(&self, id: Uuid) -> Result { + let client = self.pool.get().await.map_err(|_| Error::Unavailable)?; + let row = client + .query_opt( + "SELECT document FROM adapter_payment_attempts WHERE deployment=$1 AND id=$2", + &[&self.deployment, &id], + ) + .await + .map_err(|_| Error::Unavailable)? + .ok_or(Error::NotFound)?; + decode(row.get(0)) + } + + /// Called under the attempt's transaction-scoped advisory lock. The write + /// and its audit event commit before any corresponding outbound mutation. + pub async fn save(&self, attempt: &Attempt, kind: &str) -> Result<(), Error> { + attempt.validate_integrity()?; + let document = serde_json::to_value(attempt).map_err(|_| Error::Unavailable)?; + let mut client = self.pool.get().await.map_err(|_| Error::Unavailable)?; + let tx = client.transaction().await.map_err(|_| Error::Unavailable)?; + let count=tx.execute("UPDATE adapter_payment_attempts SET document=$3,updated_at=clock_timestamp() WHERE deployment=$1 AND id=$2",&[&self.deployment,&attempt.id,&document]).await.map_err(|_| Error::Unavailable)?; + if count != 1 { + return Err(Error::Unavailable); + } + event(&*tx, &self.deployment, attempt, kind).await?; + tx.commit().await.map_err(|_| Error::Unavailable) + } +} + +fn decode(value: serde_json::Value) -> Result { + let attempt: Attempt = serde_json::from_value(value).map_err(|_| Error::Unavailable)?; + attempt.validate_integrity()?; + Ok(attempt) +} +async fn command( + client: &impl GenericClient, + deployment: &str, + connection: &str, + principal: &str, + operation: &str, + key: &str, + digest: &str, +) -> Result, Error> { + let row=client.query_opt("SELECT request_digest,attempt_id FROM adapter_payment_commands WHERE deployment=$1 AND connection=$2 AND principal=$3 AND operation=$4 AND command_key=$5", + &[&deployment,&connection,&principal,&operation,&key]).await.map_err(|_| Error::Unavailable)?; + match row { + Some(row) if row.get::<_, String>(0) != digest => Err(Error::Conflict), + Some(row) => Ok(Some(row.get(1))), + None => Ok(None), + } +} +#[allow(clippy::too_many_arguments)] +async fn claim( + client: &impl GenericClient, + deployment: &str, + connection: &str, + principal: &str, + operation: &str, + key: &str, + digest: &str, + id: Uuid, +) -> Result<(), Error> { + client.execute("INSERT INTO adapter_payment_commands (deployment,connection,principal,operation,command_key,request_digest,attempt_id) VALUES ($1,$2,$3,$4,$5,$6,$7) ON CONFLICT DO NOTHING", + &[&deployment,&connection,&principal,&operation,&key,&digest,&id]).await.map_err(|_| Error::Unavailable)?; + if command( + client, deployment, connection, principal, operation, key, digest, + ) + .await? + != Some(id) + { + return Err(Error::Conflict); + } + Ok(()) +} +async fn event( + client: &impl GenericClient, + deployment: &str, + attempt: &Attempt, + kind: &str, +) -> Result<(), Error> { + client.execute("INSERT INTO adapter_payment_events (deployment,attempt_id,principal,kind) VALUES ($1,$2,$3,$4)",&[&deployment,&attempt.id,&attempt.principal,&kind]).await.map_err(|_| Error::Unavailable)?; + Ok(()) +} diff --git a/crates/registry-adapter/src/serve.rs b/crates/registry-adapter/src/serve.rs index 686d8b4488..286e247df2 100644 --- a/crates/registry-adapter/src/serve.rs +++ b/crates/registry-adapter/src/serve.rs @@ -202,7 +202,7 @@ impl Authenticator { } } -async fn authenticator( +pub(crate) async fn authenticator( runtime: &AdapterRuntimeConfig, resolver: &SecretResolver, ) -> Result { @@ -300,7 +300,7 @@ fn codec( Ok(Some(ContinuationCodec::new(key(current)?, previous, ttl))) } -fn pool( +pub(crate) fn pool( config: &DatabaseConfig, resolver: &SecretResolver, migration: bool, @@ -405,7 +405,8 @@ fn accepted_algorithms() -> Vec { /// before anything is served, so a failure to install one refuses startup /// rather than leaving a runtime that SIGTERM would stop with sends in /// flight. -fn shutdown_signal() -> Result + Send, ServeError> { +pub(crate) fn shutdown_signal() -> Result + Send, ServeError> +{ shutdown_after(registry_platform_httpsec::shutdown_signal) } @@ -629,6 +630,44 @@ pub async fn run( profile_path: Option<&std::path::Path>, pack_path: Option<&std::path::Path>, runtime_path: &std::path::Path, +) -> Result<(), ServeError> { + run_facade( + project_directory, + profile_path, + pack_path, + runtime_path, + None, + ) + .await +} + +/// Host a record facade, typed payment routes, or both on one listener. +pub async fn run_configured( + project_directory: Option<&std::path::Path>, + profile_path: Option<&std::path::Path>, + pack_path: Option<&std::path::Path>, + runtime_path: &std::path::Path, + payments_path: Option<&std::path::Path>, +) -> Result<(), ServeError> { + match (project_directory, payments_path) { + (Some(project), payments) => { + run_facade(project, profile_path, pack_path, runtime_path, payments).await + } + (None, Some(payments)) if profile_path.is_none() && pack_path.is_none() => { + crate::payments::http::run_only(runtime_path, payments).await + } + _ => Err(ServeError::Configuration( + "a project or payment configuration is required".to_owned(), + )), + } +} + +async fn run_facade( + project_directory: &std::path::Path, + profile_path: Option<&std::path::Path>, + pack_path: Option<&std::path::Path>, + runtime_path: &std::path::Path, + payments_path: Option<&std::path::Path>, ) -> Result<(), ServeError> { let loaded = crate::engine::load::load_with_target( project_directory, @@ -801,6 +840,12 @@ pub async fn run( let async_recovery = async_recovery_admission(&loaded)?; let async_retention = idempotency.as_ref().map(|(_, retention)| *retention); let facade_idempotency = idempotency.as_ref().map(|(store, _)| store.clone()); + let payments_router = match payments_path { + Some(path) => { + Some(crate::payments::http::load_router(&loaded.runtime, path, journal.clone()).await?) + } + None => None, + }; let address: SocketAddr = loaded.runtime.listener.bind.0; let listener = TcpListener::bind(address) .await @@ -852,7 +897,11 @@ pub async fn run( }); let (shutdown_sender, shutdown_receiver) = watch::channel(false); let mut server_shutdown = shutdown_receiver.clone(); - let serving = axum::serve(listener, router(state)).with_graceful_shutdown(async move { + let routes = match payments_router { + Some(payments) => router(state).merge(payments), + None => router(state), + }; + let serving = axum::serve(listener, routes).with_graceful_shutdown(async move { let _closed = server_shutdown.changed().await; }); let mut metrics_shutdown = shutdown_receiver.clone(); diff --git a/crates/registry-adapter/tests/payment_config.rs b/crates/registry-adapter/tests/payment_config.rs new file mode 100644 index 0000000000..bb3a904dac --- /dev/null +++ b/crates/registry-adapter/tests/payment_config.rs @@ -0,0 +1,217 @@ +// SPDX-License-Identifier: Apache-2.0 +use registry_adapter::payments::config::PaymentsConfig; +use serde_json::{json, Value}; + +fn config() -> Value { + json!({ "connections": [{ "id":"fees", "institutionId":"ministry", "serviceId":"permit", + "allowedClients":["payment-coordinator"], "requiredScope":"payments:collections", + "binding": { "simulation":true, "currency":"USD", "currencyScale":2, "providerCredentialRef":"secret:env/SIMULATOR_TOKEN", + "providerCredentialIdentity":"synthetic-producer", "replayWindowSeconds":3600, + "provider": { "baseUrl":"http://127.0.0.1:8099/", "tenant":"pilot", "biller":"ministry", + "billerName":"Ministry", "callbackUrl":"https://programme.example.test/callback", "payerFiBic":"SIMBANK" }, + "registry": { "baseUrl":"http://127.0.0.1:8080/", "readProfile":"payment-adapter-reporter", "bindProfile":"payment-adapter-binder", "receiptProfile":"payment-adapter-reporter", "recordType":"service-fee-bill", "recordRoute":"service-fee-bills", + "bindAction":"bind-payment-attempt", "receiptAction":"record-payment-receipt", + "credentialRef":"secret:env/PAYMENT_REPORTER_TOKEN", "credentialIdentity":"payment-adapter" } + } + }] }) +} +#[test] +fn connections_are_explicit_scoped_and_synthetic() { + let valid: PaymentsConfig = serde_json::from_value(config()).unwrap(); + assert!(valid.validate().is_ok()); + for pointer in ["/connections/0/allowedClients", "/connections"] { + let mut value = config(); + *value.pointer_mut(pointer).unwrap() = json!([]); + assert!(serde_json::from_value::(value) + .unwrap() + .validate() + .is_err()); + } + let mut live = config(); + live["connections"][0]["binding"]["simulation"] = json!(false); + assert!(serde_json::from_value::(live) + .unwrap() + .validate() + .is_err()); + let mut unusable = config(); + unusable["connections"][0]["id"] = json!("MixedCase"); + assert!(serde_json::from_value::(unusable) + .unwrap() + .validate() + .is_err()); +} +#[test] +fn routing_or_credential_identity_changes_the_frozen_binding() { + let original: PaymentsConfig = serde_json::from_value(config()).unwrap(); + let digest = original.connections[0].binding.revision().unwrap(); + for pointer in [ + "/connections/0/binding/provider/tenant", + "/connections/0/binding/provider/biller", + "/connections/0/binding/providerCredentialIdentity", + "/connections/0/binding/registry/credentialIdentity", + ] { + let mut changed = config(); + *changed.pointer_mut(pointer).unwrap() = json!("changed"); + let parsed: PaymentsConfig = serde_json::from_value(changed).unwrap(); + assert_ne!(digest, parsed.connections[0].binding.revision().unwrap()); + } +} + +fn attempt() -> registry_adapter::payments::model::Attempt { + use registry_adapter::payments::model::{Attempt, BillSnapshot}; + use registry_payment_protocol::Money; + let config: PaymentsConfig = serde_json::from_value(config()).unwrap(); + let binding = config.connections[0].binding.clone(); + let bill = BillSnapshot { + bill_id: uuid::Uuid::new_v4(), + bill_version: 1, + bill_digest: "a".repeat(64), + institution_id: "ministry".into(), + service_id: "permit".into(), + request_id: "request-1".into(), + tariff_id: "permit-fee".into(), + tariff_version: 1, + tariff_digest: "b".repeat(64), + payer_id: "payer-1".into(), + payer_financial_address: "synthetic-payer".into(), + money: Money { + value: "25.00".into(), + currency: "USD".into(), + scale: 2, + }, + simulation: true, + }; + Attempt { + id: uuid::Uuid::new_v4(), + connection: "fees".into(), + principal: "caller".into(), + bill_snapshot_digest: bill.digest().unwrap(), + binding_revision: binding.revision().unwrap(), + provider_command: bill.provider_command(&binding).unwrap(), + bill, + binding, + bind_action: None, + bound: false, + first_send_at: None, + transfer_id: None, + observation: None, + report_action: None, + receipt_digest: None, + receipt: None, + } +} + +#[test] +fn provider_identity_is_stable_bounded_and_independent_of_store_or_credentials() { + let first = attempt(); + let mut independent = first.clone(); + independent.id = uuid::Uuid::new_v4(); + independent.connection = "other-connection".into(); + independent.binding.provider_credential_ref = + serde_json::from_value(json!("secret:env/ROTATED_TOKEN")).unwrap(); + independent.binding.replay_window_seconds = 1; + independent.binding.provider.base_url.pop(); // Equivalent root URL without its slash. + assert_eq!( + first.provider_command, + independent + .bill + .provider_command(&independent.binding) + .unwrap() + ); + assert_eq!(first.provider_command.request_id.len(), 12); + assert_eq!(first.provider_command.bill_id.len(), 10); + first.provider_command.validate().unwrap(); + let mut other_bill = first.bill.clone(); + other_bill.bill_id = uuid::Uuid::new_v4(); + assert_ne!( + first.provider_command, + other_bill.provider_command(&first.binding).unwrap() + ); +} + +#[test] +fn v1_provider_identity_matches_the_retained_command_golden_vector() { + let mut saved = attempt(); + saved.bill.bill_id = "9303e1c2-9c2c-4c1e-8ecb-06bfa02d70cf".parse().unwrap(); + let command = saved.bill.provider_command(&saved.binding).unwrap(); + assert_eq!(command.request_id, "90RVxEyflgHP"); + assert_eq!(command.bill_id, "emwUe0iT0w"); + assert_eq!(command.rtp_id, 1_364_251_476_903_812); + saved.binding.provider.base_url.pop(); + assert_eq!( + saved.bill.provider_command(&saved.binding).unwrap(), + command + ); +} + +#[test] +fn sequence_based_development_snapshots_are_held_without_rewriting_the_command() { + use registry_payment_protocol::PaymentProblemCode; + let mut saved = attempt(); + saved.provider_command.request_id = "p1".into(); + saved.provider_command.rtp_id = 1; + saved.provider_command.bill_id = "1".into(); + let prior = serde_json::to_value(&saved).unwrap(); + assert_eq!( + saved.validate_integrity(), + Err(PaymentProblemCode::Unavailable) + ); + assert_eq!(serde_json::to_value(&saved).unwrap(), prior); +} + +#[test] +fn persisted_command_cannot_be_borrowed_by_another_bill_or_provider_namespace() { + use registry_adapter::payments::model::Attempt; + use registry_payment_protocol::PaymentProblemCode; + let original = attempt(); + original.validate_integrity().unwrap(); + for (pointer, replacement) in [ + ("/bill/billId", json!(uuid::Uuid::new_v4())), + ("/bill/billVersion", json!(2)), + ("/bill/billDigest", json!("c".repeat(64))), + ("/bill/institutionId", json!("another-institution")), + ("/bill/serviceId", json!("another-service")), + ("/bill/requestId", json!("another-request")), + ("/bill/tariffDigest", json!("d".repeat(64))), + ("/binding/provider/tenant", json!("another-tenant")), + ("/binding/provider/biller", json!("another-biller")), + ( + "/binding/providerCredentialIdentity", + json!("another-producer"), + ), + ] { + let mut document = serde_json::to_value(&original).unwrap(); + *document.pointer_mut(pointer).unwrap() = replacement; + let mut changed: Attempt = serde_json::from_value(document).unwrap(); + changed.bill_snapshot_digest = changed.bill.digest().unwrap(); + changed.binding_revision = changed.binding.revision().unwrap(); + assert_eq!( + changed.validate_integrity(), + Err(PaymentProblemCode::Unavailable), + "{pointer}" + ); + } +} + +#[cfg(feature = "schema")] +#[test] +fn authored_connections_cannot_enable_live_mode_or_omit_scope() { + let schema = serde_json::to_value(schemars::schema_for!(PaymentsConfig)).unwrap(); + let compiled = jsonschema::JSONSchema::options() + .with_draft(jsonschema::Draft::Draft202012) + .compile(&schema) + .unwrap(); + assert!(compiled.is_valid(&config())); + let mut value = config(); + value["connections"][0]["binding"]["simulation"] = json!(false); + assert!(!compiled.is_valid(&value)); + let mut value = config(); + value["connections"][0] + .as_object_mut() + .unwrap() + .remove("requiredScope"); + assert!(!compiled.is_valid(&value)); + let mut value = config(); + value["connections"] = json!([]); + assert!(!compiled.is_valid(&value)); +} diff --git a/crates/registry-adapter/tests/payment_registry.rs b/crates/registry-adapter/tests/payment_registry.rs new file mode 100644 index 0000000000..f732a5f334 --- /dev/null +++ b/crates/registry-adapter/tests/payment_registry.rs @@ -0,0 +1,24 @@ +// SPDX-License-Identifier: Apache-2.0 +use registry_adapter::payments::registry::{BillState, BillView}; +use serde_json::json; + +#[test] +fn bill_projection_keeps_domain_version_and_exact_money() { + let id = uuid::Uuid::new_v4(); + let data = json!({"billVersion":7,"billDigest":"a".repeat(64),"institutionId":"ministry","serviceId":"permit", + "requestId":"req1","payerId":"payer1","payerFinancialAddress":"synthetic-payer", + "tariffId":"permit-v1","tariffVersion":1,"tariffDigest":"b".repeat(64), + "amountMinor":9007199254740991_u64,"currency":"USD","currencyScale":2,"simulation":true,"paymentState":"due-unbound"}); + let bill = BillView::decode(id, serde_json::from_value(data.clone()).unwrap()).unwrap(); + assert_eq!(bill.snapshot.bill_version, 7); + assert_eq!(bill.snapshot.money.value, "90071992547409.91"); + assert_eq!(bill.state, BillState::DueUnbound); + for field in ["billVersion", "amountMinor", "currencyScale"] { + let mut changed = data.clone(); + changed[field] = json!(1.5); + assert!(BillView::decode(id, serde_json::from_value(changed).unwrap()).is_err()); + } + let mut malformed = data; + malformed["paymentAttemptId"] = json!("not-a-uuid"); + assert!(BillView::decode(id, serde_json::from_value(malformed).unwrap()).is_err()); +} diff --git a/crates/registry-adapter/tests/payment_service.rs b/crates/registry-adapter/tests/payment_service.rs new file mode 100644 index 0000000000..180d242624 --- /dev/null +++ b/crates/registry-adapter/tests/payment_service.rs @@ -0,0 +1,504 @@ +// SPDX-License-Identifier: Apache-2.0 +#![cfg(feature = "postgres-test")] + +use async_trait::async_trait; +use registry_adapter::{ + payments::{ + config::{PaymentBinding, PaymentsConfig}, + model::{BillSnapshot, PreparedRegistryAction}, + registry::{BillState, BillView, RegistryPort}, + service::{PaymentService, ProviderPort}, + store::{migrate, PaymentStore}, + }, + serve::Caller, +}; +use registry_payment_protocol::{ + CollectionState, Money, PaymentProblemCode as Error, RequestCollection, +}; +use registry_payment_simulator_connector::{ConnectorError, Observation, ProviderCommand}; +use serde_json::{json, Map, Value}; +use std::{ + collections::HashMap, + sync::{ + atomic::{AtomicBool, AtomicUsize, Ordering}, + Arc, Mutex, + }, +}; +use uuid::Uuid; + +fn config() -> PaymentsConfig { + serde_json::from_value(json!({"connections":[{ + "id":"fees","institutionId":"ministry","serviceId":"permit","allowedClients":["coordinator"],"requiredScope":"payments:collections", + "binding":{"simulation":true,"currency":"USD","currencyScale":2,"providerCredentialRef":"secret:env/SIMULATOR_TOKEN","providerCredentialIdentity":"producer","replayWindowSeconds":3600, + "provider":{"baseUrl":"http://127.0.0.1:8099/","tenant":"pilot","biller":"ministry","billerName":"Ministry","callbackUrl":"https://programme.example.test/callback","payerFiBic":"SIMBANK"}, + "registry":{"baseUrl":"http://127.0.0.1:8080/","recordType":"service-fee-bill","recordRoute":"service-fee-bills","readProfile":"reporter","bindProfile":"binder","receiptProfile":"reporter","bindAction":"bind-payment-attempt","receiptAction":"record-payment-receipt","credentialRef":"secret:env/REPORTER_TOKEN","credentialIdentity":"payment-adapter"} + }}]})).unwrap() +} +fn caller() -> Caller { + Caller { + reference: "workflow-service".into(), + issuer: "https://issuer.example.test".into(), + client_id: "coordinator".into(), + scopes: vec!["payments:collections".into()], + } +} +fn bill() -> BillView { + BillView { + snapshot: BillSnapshot { + bill_id: Uuid::new_v4(), + bill_version: 1, + bill_digest: "a".repeat(64), + institution_id: "ministry".into(), + service_id: "permit".into(), + request_id: "request1".into(), + tariff_id: "permit-fee".into(), + tariff_version: 1, + tariff_digest: "b".repeat(64), + payer_id: "payer1".into(), + payer_financial_address: "synthetic-payer".into(), + money: Money { + value: "25.00".into(), + currency: "USD".into(), + scale: 2, + }, + simulation: true, + }, + state: BillState::DueUnbound, + attempt_id: None, + binding_revision: None, + receipt_id: None, + provider_reference: None, + receipt_digest: None, + } +} + +struct Registry { + bill: Mutex, + fail_read: AtomicBool, + lose_bind: AtomicBool, + lose_report: AtomicBool, + binds: AtomicUsize, + reports: AtomicUsize, +} +#[async_trait] +impl RegistryPort for Registry { + async fn read_bill(&self, _: &PaymentBinding, id: Uuid) -> Result { + if self.fail_read.swap(false, Ordering::SeqCst) { + return Err(Error::Unavailable); + } + let bill = self.bill.lock().unwrap().clone(); + assert_eq!(id, bill.snapshot.bill_id); + Ok(bill) + } + async fn prepare( + &self, + _: &PaymentBinding, + receipt: bool, + key: &str, + inputs: Map, + ) -> Result { + Ok(PreparedRegistryAction { + action: if receipt { "report" } else { "bind" }.into(), + key: key.into(), + evidence: serde_json::to_string(&inputs).unwrap(), + inputs, + }) + } + async fn invoke( + &self, + _: &PaymentBinding, + receipt: bool, + prepared: &PreparedRegistryAction, + ) -> Result<(), Error> { + assert_eq!( + serde_json::from_str::>(&prepared.evidence).unwrap(), + prepared.inputs + ); + let mut bill = self.bill.lock().unwrap(); + assert_eq!(prepared.inputs["billId"], json!(bill.snapshot.bill_id)); + assert_eq!(prepared.inputs["amountMinor"], json!(2500)); + if receipt { + self.reports.fetch_add(1, Ordering::SeqCst); + assert_eq!(bill.state, BillState::AttemptBound); + bill.state = BillState::Paid; + bill.receipt_id = Some(prepared.inputs["paymentReceiptId"].as_str().unwrap().into()); + bill.provider_reference = Some( + prepared.inputs["providerReference"] + .as_str() + .unwrap() + .into(), + ); + bill.receipt_digest = Some(prepared.inputs["receiptDigest"].as_str().unwrap().into()); + if self.lose_report.swap(false, Ordering::SeqCst) { + self.fail_read.store(true, Ordering::SeqCst); + return Err(Error::OutcomeUnknown); + } + } else { + self.binds.fetch_add(1, Ordering::SeqCst); + assert_eq!(bill.state, BillState::DueUnbound); + bill.state = BillState::AttemptBound; + bill.attempt_id = + Some(serde_json::from_value(prepared.inputs["paymentAttemptId"].clone()).unwrap()); + bill.binding_revision = Some( + prepared.inputs["providerBindingRevision"] + .as_str() + .unwrap() + .into(), + ); + if self.lose_bind.swap(false, Ordering::SeqCst) { + self.fail_read.store(true, Ordering::SeqCst); + return Err(Error::OutcomeUnknown); + } + } + Ok(()) + } +} +struct Provider { + registry: Arc, + commands: Mutex>, + tenants: Mutex>, + lose_ack: AtomicBool, + confirmed: AtomicBool, + failed: AtomicBool, + sends: AtomicUsize, +} +#[async_trait] +impl ProviderPort for Provider { + async fn submit( + &self, + binding: &PaymentBinding, + command: &ProviderCommand, + ) -> Result { + assert_eq!( + self.registry.bill.lock().unwrap().state, + BillState::AttemptBound, + "binding must commit before provider dispatch" + ); + self.sends.fetch_add(1, Ordering::SeqCst); + self.tenants + .lock() + .unwrap() + .push(binding.provider.tenant.clone()); + let mut commands = self.commands.lock().unwrap(); + if let Some(prior) = commands.get(&command.rtp_id) { + assert_eq!(prior, command); + } else { + commands.insert(command.rtp_id, command.clone()); + } + if self.lose_ack.swap(false, Ordering::SeqCst) { + return Err(ConnectorError::Unknown); + } + Ok(format!("transfer-{}", command.rtp_id)) + } + async fn observe( + &self, + binding: &PaymentBinding, + _: &ProviderCommand, + _: &str, + ) -> Result { + self.tenants + .lock() + .unwrap() + .push(binding.provider.tenant.clone()); + let confirmed = self.confirmed.load(Ordering::SeqCst); + let failed = self.failed.load(Ordering::SeqCst); + Ok(Observation { + state: if failed { + CollectionState::Failed + } else if confirmed { + CollectionState::Confirmed + } else { + CollectionState::Pending + }, + provider_reference: confirmed.then(|| "SIM-payment-1".into()), + failure_reason: failed.then(|| "payer-rejected".into()), + observed_at: 1, + }) + } +} +async fn setup() -> (PaymentStore, Arc, Arc) { + let url = std::env::var("ADAPTER_TEST_DATABASE_URL") + .expect("postgres-test requires ADAPTER_TEST_DATABASE_URL"); + let manager = deadpool_postgres::Manager::new(url.parse().unwrap(), tokio_postgres::NoTls); + let pool = deadpool_postgres::Pool::builder(manager) + .max_size(24) + .build() + .unwrap(); + { + let mut client = pool.get().await.unwrap(); + migrate(&mut client).await.unwrap(); + } + let store = PaymentStore::new(pool, format!("payment-service-{}", Uuid::new_v4())); + let registry = Arc::new(Registry { + bill: Mutex::new(bill()), + fail_read: AtomicBool::new(false), + lose_bind: AtomicBool::new(false), + lose_report: AtomicBool::new(false), + binds: AtomicUsize::new(0), + reports: AtomicUsize::new(0), + }); + let provider = Arc::new(Provider { + registry: registry.clone(), + commands: Mutex::new(HashMap::new()), + tenants: Mutex::new(Vec::new()), + lose_ack: AtomicBool::new(false), + confirmed: AtomicBool::new(false), + failed: AtomicBool::new(false), + sends: AtomicUsize::new(0), + }); + (store, registry, provider) +} + +#[tokio::test] +async fn definitive_failure_never_releases_the_bill_for_another_collection() { + let (store, registry, provider) = setup().await; + let request = RequestCollection { + bill_id: registry.bill.lock().unwrap().snapshot.bill_id, + bill_version: 1, + }; + let service = + PaymentService::new(config(), store.clone(), registry.clone(), provider.clone()).unwrap(); + let accepted = service + .request("fees", &caller(), "first", &request) + .await + .unwrap(); + provider.failed.store(true, Ordering::SeqCst); + assert_eq!( + service + .read("fees", &caller(), accepted.collection_id) + .await + .unwrap() + .state, + CollectionState::Failed + ); + drop(service); + let recovered = + PaymentService::new(config(), store, registry.clone(), provider.clone()).unwrap(); + for key in ["first", "different-workflow-key"] { + assert_eq!( + recovered + .request("fees", &caller(), key, &request) + .await + .unwrap(), + accepted + ); + } + assert!(recovered + .record_receipt("fees", &caller(), "report", accepted.collection_id) + .await + .is_err()); + assert_eq!(provider.sends.load(Ordering::SeqCst), 1); + assert_eq!(provider.commands.lock().unwrap().len(), 1); + assert_eq!(registry.binds.load(Ordering::SeqCst), 1); + assert_eq!(registry.reports.load(Ordering::SeqCst), 0); + assert_eq!(registry.bill.lock().unwrap().state, BillState::AttemptBound); +} + +#[tokio::test] +async fn lost_bind_provider_and_receipt_responses_recover_without_new_effects() { + let (store, registry, provider) = setup().await; + registry.lose_bind.store(true, Ordering::SeqCst); + provider.lose_ack.store(true, Ordering::SeqCst); + registry.lose_report.store(true, Ordering::SeqCst); + let request = RequestCollection { + bill_id: registry.bill.lock().unwrap().snapshot.bill_id, + bill_version: 1, + }; + let service = + PaymentService::new(config(), store.clone(), registry.clone(), provider.clone()).unwrap(); + assert_eq!( + service + .request("fees", &caller(), "request-key", &request) + .await + .unwrap_err(), + Error::OutcomeUnknown + ); + assert_eq!(provider.sends.load(Ordering::SeqCst), 0); + let id = store + .find_bill("ministry", "permit", request.bill_id, 1) + .await + .unwrap() + .unwrap() + .id; + assert_eq!( + service.read("fees", &caller(), id).await.unwrap().state, + CollectionState::Unknown + ); + assert_eq!( + service + .request_receipt("fees", &caller(), "request-key", &request) + .await + .unwrap_err(), + Error::ReceiptUnresolved + ); + assert_eq!(registry.binds.load(Ordering::SeqCst), 1); + assert_eq!( + provider.sends.load(Ordering::SeqCst), + 0, + "reads never dispatch" + ); + drop(service); + let mut changed = config(); + changed.connections[0].binding.provider.tenant = "new-tenant".into(); + let service = PaymentService::new( + changed.clone(), + store.clone(), + registry.clone(), + provider.clone(), + ) + .unwrap(); + assert_eq!( + service + .request("fees", &caller(), "request-key", &request) + .await + .unwrap_err(), + Error::OutcomeUnknown + ); + drop(service); + let service = PaymentService::new( + changed.clone(), + store.clone(), + registry.clone(), + provider.clone(), + ) + .unwrap(); + let accepted = service + .request("fees", &caller(), "request-key", &request) + .await + .unwrap(); + assert_eq!(accepted.collection_id, id); + assert_eq!(registry.binds.load(Ordering::SeqCst), 1); + assert_eq!(provider.sends.load(Ordering::SeqCst), 2); + assert_eq!(provider.commands.lock().unwrap().len(), 1); + assert_eq!( + service + .request("fees", &caller(), "another-run", &request) + .await + .unwrap(), + accepted + ); + assert_eq!(provider.sends.load(Ordering::SeqCst), 2); + assert_eq!( + service + .request_receipt("fees", &caller(), "request-key", &request) + .await + .unwrap(), + accepted + ); + assert_eq!( + service.read("fees", &caller(), id).await.unwrap().state, + CollectionState::Pending + ); + assert_eq!( + service + .record_receipt("fees", &caller(), "receipt-key", id) + .await + .unwrap_err(), + Error::Conflict + ); + assert_eq!(registry.reports.load(Ordering::SeqCst), 0); + provider.confirmed.store(true, Ordering::SeqCst); + assert_eq!( + service.read("fees", &caller(), id).await.unwrap().state, + CollectionState::Confirmed + ); + assert_eq!( + service + .record_receipt("fees", &caller(), "receipt-key", id) + .await + .unwrap_err(), + Error::OutcomeUnknown + ); + drop(service); + let service = + PaymentService::new(changed, store.clone(), registry.clone(), provider.clone()).unwrap(); + let receipt = service + .record_receipt("fees", &caller(), "receipt-key", id) + .await + .unwrap(); + assert!(receipt.simulation); + assert_eq!(receipt.provider_reference, "SIM-payment-1"); + assert_eq!(registry.reports.load(Ordering::SeqCst), 1); + assert_eq!( + service + .record_receipt("fees", &caller(), "another-report-key", id) + .await + .unwrap(), + receipt + ); + assert_eq!(registry.reports.load(Ordering::SeqCst), 1); + assert!( + provider + .tenants + .lock() + .unwrap() + .iter() + .all(|s| s == "pilot"), + "old attempts use the original tenant after config change" + ); + let mut other = caller(); + other.reference = "different-service".into(); + assert_eq!( + service.read("fees", &other, id).await.unwrap_err(), + Error::NotFound + ); + other = caller(); + other.scopes.clear(); + assert_eq!( + service.read("fees", &other, id).await.unwrap_err(), + Error::Forbidden + ); + let changed_request = RequestCollection { + bill_id: Uuid::new_v4(), + bill_version: 1, + }; + assert_eq!( + service + .request("fees", &caller(), "request-key", &changed_request) + .await + .unwrap_err(), + Error::Conflict + ); +} + +#[tokio::test] +async fn uncertain_attempt_is_held_after_its_original_replay_window() { + let (store, registry, provider) = setup().await; + provider.lose_ack.store(true, Ordering::SeqCst); + let request = RequestCollection { + bill_id: registry.bill.lock().unwrap().snapshot.bill_id, + bill_version: 1, + }; + let service = + PaymentService::new(config(), store.clone(), registry.clone(), provider.clone()).unwrap(); + assert_eq!( + service + .request("fees", &caller(), "key", &request) + .await + .unwrap_err(), + Error::OutcomeUnknown + ); + let mut saved = store + .find_bill("ministry", "permit", request.bill_id, 1) + .await + .unwrap() + .unwrap(); + saved.first_send_at = Some(time::OffsetDateTime::now_utc().unix_timestamp() - 3601); + store.save(&saved, "test.clock-advanced").await.unwrap(); + assert_eq!( + service + .request("fees", &caller(), "key", &request) + .await + .unwrap_err(), + Error::RecoveryHeld + ); + assert_eq!( + service + .request("fees", &caller(), "fresh-run", &request) + .await + .unwrap_err(), + Error::RecoveryHeld + ); + assert_eq!(provider.sends.load(Ordering::SeqCst), 1); + assert_eq!(provider.commands.lock().unwrap().len(), 1); +} diff --git a/crates/registry-adapter/tests/payment_store.rs b/crates/registry-adapter/tests/payment_store.rs new file mode 100644 index 0000000000..7f247597dd --- /dev/null +++ b/crates/registry-adapter/tests/payment_store.rs @@ -0,0 +1,46 @@ +// SPDX-License-Identifier: Apache-2.0 +#![cfg(feature = "postgres-test")] + +use registry_adapter::payments::store::{migrate, PaymentStore}; +use registry_payment_protocol::PaymentProblemCode; + +#[tokio::test] +async fn same_key_different_body_never_aliases_a_command() { + let url = std::env::var("ADAPTER_TEST_DATABASE_URL") + .expect("postgres-test requires ADAPTER_TEST_DATABASE_URL"); + let config = url.parse().unwrap(); + let manager = deadpool_postgres::Manager::new(config, tokio_postgres::NoTls); + let pool = deadpool_postgres::Pool::builder(manager) + .max_size(4) + .build() + .unwrap(); + let mut client = pool.get().await.unwrap(); + migrate(&mut client).await.unwrap(); + let store = PaymentStore::new(pool, format!("payment-test-{}", uuid::Uuid::new_v4())); + let id = uuid::Uuid::new_v4(); + store + .claim_command("fees", "caller", "receipt", "key", "digest-1", id) + .await + .unwrap(); + assert_eq!( + store + .lookup_command("fees", "caller", "receipt", "key", "digest-1") + .await + .unwrap(), + Some(id) + ); + assert_eq!( + store + .lookup_command("fees", "caller", "receipt", "key", "digest-2") + .await + .unwrap_err(), + PaymentProblemCode::Conflict + ); + assert_eq!( + store + .lookup_command("fees", "other-caller", "receipt", "key", "digest-1") + .await + .unwrap(), + None + ); +} diff --git a/crates/registry-adapterctl/Cargo.toml b/crates/registry-adapterctl/Cargo.toml index 3a971c4c4b..c57382f2c1 100644 --- a/crates/registry-adapterctl/Cargo.toml +++ b/crates/registry-adapterctl/Cargo.toml @@ -31,7 +31,7 @@ graphql-parser.workspace = true # test` over both) compiles registry-adapter, its facade binary and its # tests with both gates on. The facade serves no job either way; the # lane that tests the gates off must build registry-adapter alone. -registry-adapter = { workspace = true, features = ["job-file", "job-postgres"] } +registry-adapter = { workspace = true, features = ["job-file", "job-postgres", "schema"] } registry-adapter-core = { workspace = true, features = ["schema"] } registry-platform-buildinfo.workspace = true registry-platform-config = { workspace = true, features = ["schema"] } diff --git a/crates/registry-adapterctl/src/lib.rs b/crates/registry-adapterctl/src/lib.rs index b877039a3e..53e0299a93 100644 --- a/crates/registry-adapterctl/src/lib.rs +++ b/crates/registry-adapterctl/src/lib.rs @@ -22,6 +22,7 @@ mod fixtures; mod job; mod job_runtime; mod mapping; +mod payments; mod project; mod report; mod schemas; @@ -66,6 +67,8 @@ enum Command { Mapping(mapping::MappingArgs), /// Operate one authored adapter project. Project(project::ProjectArgs), + /// Check typed payment connections or export their fixed operation contract. + Payments(payments::PaymentsArgs), /// Write the generated JSON Schemas of every Adapter format, or /// check the committed ones for drift. Schemas(schemas::SchemasArgs), @@ -151,6 +154,7 @@ where project::ProjectCommand::Lock(_) => "project lock", }, Command::Schemas(_) => "schemas", + Command::Payments(args) => payments::command_name(&args.command), Command::Compile(_) => "compile", Command::Fixtures(fixtures) => match fixtures.command { fixtures::FixturesCommand::Replay(_) => "fixtures replay", @@ -168,6 +172,7 @@ where Command::Mapping(args) => mapping_command(args, format, command_name, stdout, stderr), Command::Project(args) => project_command(args, format, command_name, stdout, stderr), Command::Schemas(args) => schemas_command(args, format, command_name, stdout, stderr), + Command::Payments(args) => payments_command(args, format, command_name, stdout, stderr), Command::Compile(args) => compile_command(args, format, command_name, stdout, stderr), Command::Fixtures(args) => fixtures_command(args, format, command_name, stdout, stderr), Command::Verify(args) => verify_command(args, format, command_name, stdout, stderr), @@ -193,6 +198,39 @@ fn usage_failure(message: String) -> Value { ) } +fn payments_command( + args: payments::PaymentsArgs, + format: OutputFormat, + command_name: &'static str, + stdout: &mut dyn io::Write, + stderr: &mut dyn io::Write, +) -> Result { + let run = payments::run(&args.command); + let exit = if run.unavailable { + OPERATIONAL_FAILURE_EXIT + } else if refused(run.checked.diagnostics(), run.deny_warnings) { + DOMAIN_REFUSAL_EXIT + } else { + 0 + }; + let mut value = run.value; + value["ok"] = json!(exit == 0); + value["status"] = json!(if exit == 0 { + "complete" + } else { + failure_status(exit) + }); + value["command"] = json!(command_name); + value["diagnostics"] = run.checked.to_json_value(); + value["filesChecked"] = json!(1); + if exit == 0 { + write_success(&value, &run.checked, format, stdout) + } else { + write_configuration_report(&run.checked, command_name, format, value, stdout, stderr) + .map(|()| ExitCode::from(exit)) + } +} + /// Whether the check verdict refuses: any error always refuses, and with /// `--deny-warnings` a warning refuses too. fn refused(diagnostics: &[registry_platform_yaml::Diagnostic], deny_warnings: bool) -> bool { diff --git a/crates/registry-adapterctl/src/payments.rs b/crates/registry-adapterctl/src/payments.rs new file mode 100644 index 0000000000..a2dac6a3f0 --- /dev/null +++ b/crates/registry-adapterctl/src/payments.rs @@ -0,0 +1,95 @@ +// SPDX-License-Identifier: Apache-2.0 +//! Offline payment configuration checks; neither command resolves credentials. +use clap::{Args, Subcommand}; +use registry_adapter::payments::config::{PaymentsConfig, API_VERSION, KIND}; +use registry_platform_config::{RuntimeConfigLoader, RuntimeEnvelope, DEFAULT_STAND_IN}; +use registry_platform_yaml::{Diagnostic, Report}; +use serde_json::{json, Value}; +use std::path::PathBuf; + +#[derive(Debug, Args)] +pub struct PaymentsArgs { + #[command(subcommand)] + pub command: PaymentsCommand, +} +#[derive(Debug, Subcommand)] +pub enum PaymentsCommand { + /// Validate one AdapterPayments file without fetching credentials or services. + Check { + /// AdapterPayments configuration file to validate. + #[arg(value_name = "FILE")] + file: PathBuf, + /// Refuse warnings as well as errors. + #[arg(long)] + deny_warnings: bool, + }, + /// Export fixed payment routes, authority and schemas for configured connections. + Contract { + /// AdapterPayments configuration file whose contract is exported. + #[arg(value_name = "FILE")] + file: PathBuf, + }, +} +pub fn command_name(command: &PaymentsCommand) -> &'static str { + match command { + PaymentsCommand::Check { .. } => "payments check", + PaymentsCommand::Contract { .. } => "payments contract", + } +} +pub struct PaymentCheck { + pub value: Value, + pub checked: Report, + pub unavailable: bool, + pub deny_warnings: bool, +} + +pub fn run(command: &PaymentsCommand) -> PaymentCheck { + let (file, deny_warnings) = match command { + PaymentsCommand::Check { + file, + deny_warnings, + } => (file, *deny_warnings), + PaymentsCommand::Contract { file } => (file, false), + }; + let absolute = match std::fs::canonicalize(file) { + Ok(path) => path, + Err(_) => { + return PaymentCheck { + value: json!({}), + checked: Report::new(vec![Diagnostic::error( + "adapterctl.io-failure", + "", + "The payment configuration could not be read.", + "Correct the file path or permissions, then retry.", + )]), + unavailable: true, + deny_warnings, + } + } + }; + let check = RuntimeConfigLoader::new(RuntimeEnvelope { + api_version: API_VERSION, + kind: KIND, + }) + .check_offline::(&absolute, true, |_| DEFAULT_STAND_IN); + let mut additional = Vec::new(); + let mut value = json!({}); + if let Some(loaded) = &check.loaded { + if loaded.config.validate().is_err() { + additional.push(check.error_at(KIND, "adapter.payment.configuration", "/connections", + "The payment connections were refused.", + "Check connection scopes, unique caller identities, currency and synthetic provider bindings; then retry.")); + } else { + value["connectionCount"] = json!(loaded.config.connections.len()); + if matches!(command, PaymentsCommand::Contract { .. }) { + value["contract"] = registry_adapter::payments::http::contract(&loaded.config); + } + } + } + PaymentCheck { + value, + checked: check.report_with(KIND, additional), + unavailable: check.unavailable, + deny_warnings, + } +} diff --git a/crates/registry-adapterctl/src/schemas.rs b/crates/registry-adapterctl/src/schemas.rs index 1efbccf375..c68e2c7073 100644 --- a/crates/registry-adapterctl/src/schemas.rs +++ b/crates/registry-adapterctl/src/schemas.rs @@ -1,8 +1,8 @@ // SPDX-License-Identifier: Apache-2.0 -//! The generated JSON Schemas of the ten Adapter formats, derived from the +//! The generated JSON Schemas of the Adapter formats, derived from the //! source-neutral model in `registry-adapter-core` with `schemars` or from -//! the runtime's pure effective-contract projection, and +//! the runtime's pure effective-contract projection and payment connection model, and //! written to `products/adapter/schemas/`. The committed files are generated outputs: never //! hand-edited, held to their sources by `adapterctl schemas --check`. @@ -76,6 +76,16 @@ fn entries() -> Result, serde_json::Error> { AdapterProject, AdapterRuntimeConfig, }; Ok(vec![ + Entry { + file: "payments.v1alpha1.schema.json", + derived: serde_json::to_value(schemars::schema_for!( + registry_adapter::payments::config::PaymentsConfig + ))?, + title: "Registry Adapter payment connections", + schema_id: registry_adapter::payments::config::SCHEMA_ID, + api_version: registry_adapter::payments::config::API_VERSION, + kind: registry_adapter::payments::config::KIND, + }, Entry { file: "job.v1alpha1.schema.json", derived: serde_json::to_value(schemars::schema_for!(AdapterJob))?, @@ -153,7 +163,7 @@ fn entries() -> Result, serde_json::Error> { ]) } -/// The ten generated schema documents, keyed by file name. Deterministic: +/// The generated schema documents, keyed by file name. Deterministic: /// the same workspace state renders the same bytes. pub fn documents() -> Result, serde_json::Error> { let shared: Value = @@ -582,7 +592,7 @@ mod tests { fn documents_are_deterministic_and_versioned() { let first = documents().unwrap(); assert_eq!(documents().unwrap(), first); - assert_eq!(first.len(), 10); + assert_eq!(first.len(), 11); let effective: Value = serde_json::from_str(&first["effective-contract.v1alpha1.schema.json"]) .expect("the effective contract schema is JSON"); diff --git a/crates/registry-adapterctl/tests/check.rs b/crates/registry-adapterctl/tests/check.rs index 6319ddf45c..eb3c83015c 100644 --- a/crates/registry-adapterctl/tests/check.rs +++ b/crates/registry-adapterctl/tests/check.rs @@ -713,10 +713,10 @@ fn check_refuses_a_missing_explicit_fixture_path() { ); } -/// `schemas` writes the closed set of ten generated files into any +/// `schemas` writes the closed set of eleven generated files into any /// directory it is given. #[test] -fn schemas_writes_ten_files_into_the_given_directory() { +fn schemas_writes_eleven_files_into_the_given_directory() { let root = tempfile::tempdir().unwrap(); let output = root.path().join("schemas").to_str().unwrap().to_owned(); let (exit, report, stderr) = run_json(&["schemas", "--output-dir", &output]); @@ -731,6 +731,7 @@ fn schemas_writes_ten_files_into_the_given_directory() { "effective-contract.v1alpha1.schema.json".to_owned(), "fixture.v1alpha1.schema.json".to_owned(), "pack.v1alpha1.schema.json".to_owned(), + "payments.v1alpha1.schema.json".to_owned(), "profile.v1alpha1.schema.json".to_owned(), "project.v1alpha1.schema.json".to_owned(), "runtime.v1alpha1.schema.json".to_owned(), diff --git a/crates/registry-adapterctl/tests/payments.rs b/crates/registry-adapterctl/tests/payments.rs new file mode 100644 index 0000000000..7ff0913971 --- /dev/null +++ b/crates/registry-adapterctl/tests/payments.rs @@ -0,0 +1,65 @@ +// SPDX-License-Identifier: Apache-2.0 +use std::{path::PathBuf, process::ExitCode}; + +#[test] +fn payment_connections_can_be_checked_without_secrets_a_registry_project_or_network() { + let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("../../products/adapter/examples/payment-collections/payments.example.yaml"); + let mut stdout = Vec::new(); + let mut stderr = Vec::new(); + let code = registry_adapterctl::main_entry_from( + [ + "adapterctl", + "--format", + "json", + "payments", + "check", + path.to_str().unwrap(), + ], + &mut stdout, + &mut stderr, + ); + assert_eq!( + code, + ExitCode::SUCCESS, + "{}", + String::from_utf8_lossy(&stderr) + ); + let report: serde_json::Value = serde_json::from_slice(&stdout).unwrap(); + assert_eq!(report["ok"], true); + assert_eq!(report["connectionCount"], 1); + assert_eq!(report["diagnostics"], serde_json::json!([])); + assert!(stderr.is_empty()); + assert!(!String::from_utf8(stdout) + .unwrap() + .contains("PAYMENT_SIMULATOR_TOKEN")); +} + +#[test] +fn payment_check_keeps_the_shared_reader_diagnostic_and_position() { + let directory = tempfile::tempdir().unwrap(); + let file = directory.path().join("payments.yaml"); + std::fs::write(&file, "apiVersion: [\n").unwrap(); + let mut stdout = Vec::new(); + let mut stderr = Vec::new(); + let code = registry_adapterctl::main_entry_from( + [ + "adapterctl", + "--format", + "json", + "payments", + "check", + file.to_str().unwrap(), + ], + &mut stdout, + &mut stderr, + ); + assert_eq!(code, ExitCode::from(1)); + let report: serde_json::Value = serde_json::from_slice(&stdout).unwrap(); + assert!(report["diagnostics"][0]["code"] + .as_str() + .unwrap() + .starts_with("yaml.")); + assert!(report["diagnostics"][0]["source"]["line"].is_number()); + assert!(stderr.is_empty()); +} diff --git a/crates/registry-breg/src/postgres/config.rs b/crates/registry-breg/src/postgres/config.rs index fb7cabee11..1d1ae4f3de 100644 --- a/crates/registry-breg/src/postgres/config.rs +++ b/crates/registry-breg/src/postgres/config.rs @@ -305,6 +305,17 @@ impl ConnectionConfig { } } + /// Classify one refused direct connection without retaining its error or + /// any connection value. Schema-test tooling connects without a pool, but + /// must expose the same closed operational causes as runtime startup. + #[cfg(all(feature = "runtime", feature = "tooling"))] + pub(crate) fn connection_cause( + &self, + error: &tokio_postgres::Error, + ) -> DatabaseConnectionCause { + postgres_connection_cause(error, &self.transport) + } + pub fn build_pool(&self) -> Result { let manager_config = ManagerConfig { recycling_method: RecyclingMethod::Verified, @@ -500,46 +511,50 @@ fn connection_cause( match error { PoolError::Timeout(_) => DatabaseConnectionCause::Timeout, - PoolError::Backend(error) => { - if let Some(database) = error.as_db_error() { - return database_error_cause(database.code()); - } - let mut source = error.source(); - let mut io_kinds = Vec::new(); - while let Some(cause) = source { - if cause.downcast_ref::().is_some() { - return DatabaseConnectionCause::Tls; - } - if let Some(error) = cause.downcast_ref::() { - io_kinds.push(error.kind()); - } - source = cause.source(); - } - if matches!(transport, Transport::Tls { .. }) - && io_kinds.contains(&std::io::ErrorKind::InvalidData) - { - // rustls certificate and server-name refusals are surfaced by - // tokio-rustls as InvalidData I/O errors. - DatabaseConnectionCause::Tls - } else if !io_kinds.is_empty() { - DatabaseConnectionCause::Unreachable - } else if matches!(transport, Transport::Tls { .. }) { - // tokio-postgres represents protocol-level TLS refusals, such - // as a plaintext server rejecting the TLS request, with a - // private TLS error kind and an opaque source. Once database - // and I/O failures are excluded, the required transport is the - // remaining value-free classification boundary. - DatabaseConnectionCause::Tls - } else { - DatabaseConnectionCause::Unreachable - } - } + PoolError::Backend(error) => postgres_connection_cause(error, transport), PoolError::Closed | PoolError::NoRuntimeSpecified | PoolError::PostCreateHook(_) => { DatabaseConnectionCause::Configuration } } } +fn postgres_connection_cause( + error: &tokio_postgres::Error, + transport: &Transport, +) -> DatabaseConnectionCause { + if let Some(database) = error.as_db_error() { + return database_error_cause(database.code()); + } + let mut source = error.source(); + let mut io_kinds = Vec::new(); + while let Some(cause) = source { + if cause.downcast_ref::().is_some() { + return DatabaseConnectionCause::Tls; + } + if let Some(error) = cause.downcast_ref::() { + io_kinds.push(error.kind()); + } + source = cause.source(); + } + if matches!(transport, Transport::Tls { .. }) + && io_kinds.contains(&std::io::ErrorKind::InvalidData) + { + // rustls certificate and server-name refusals are surfaced by + // tokio-rustls as InvalidData I/O errors. + DatabaseConnectionCause::Tls + } else if !io_kinds.is_empty() { + DatabaseConnectionCause::Unreachable + } else if matches!(transport, Transport::Tls { .. }) { + // tokio-postgres represents protocol-level TLS refusals, such as a + // plaintext server rejecting the TLS request, with a private TLS error + // kind and an opaque source. Once database and I/O failures are + // excluded, the required transport is the remaining value-free class. + DatabaseConnectionCause::Tls + } else { + DatabaseConnectionCause::Unreachable + } +} + fn database_error_cause(code: &tokio_postgres::error::SqlState) -> DatabaseConnectionCause { use tokio_postgres::error::SqlState; diff --git a/crates/registry-breg/src/postgres/mod.rs b/crates/registry-breg/src/postgres/mod.rs index 6266a17f6a..6d946e771e 100644 --- a/crates/registry-breg/src/postgres/mod.rs +++ b/crates/registry-breg/src/postgres/mod.rs @@ -233,8 +233,6 @@ pub use schema::install_compiled_schema; #[cfg(feature = "postgres-test")] #[doc(hidden)] pub use schema::reconcile_compiled_runtime_acl_for_test; -#[cfg(all(feature = "runtime", feature = "tooling"))] -pub(crate) use schema::rehearse_schema_fingerprint_with_connection; pub(crate) use schema::verify_postgres_17_or_newer; #[cfg(all(feature = "runtime", feature = "tooling"))] pub(crate) use schema::PreparedSchemaTestCatalogVerifier; @@ -243,6 +241,8 @@ pub use schema::{ prepare_schema_test_database_with_connections, PreparedSchemaTestDatabase, SchemaTestDatabaseIdentity, }; +#[cfg(all(feature = "runtime", feature = "tooling"))] +pub(crate) use schema::{rehearse_schema_fingerprint_with_connection, SchemaRehearsalError}; pub use statistics::{ PostgresStatisticsService, StatisticsDryRunOutcome, StatisticsDryRunRequest, StatisticsExactRequest, StatisticsLiveRequest, StatisticsMutationOutcome, diff --git a/crates/registry-breg/src/postgres/schema.rs b/crates/registry-breg/src/postgres/schema.rs index c143199fe1..77b2d39321 100644 --- a/crates/registry-breg/src/postgres/schema.rs +++ b/crates/registry-breg/src/postgres/schema.rs @@ -31,7 +31,7 @@ use super::{ managed_schema_fingerprint, verify_catalog_identity_for_catalog, ExpectedManagedCatalog, ExpectedRegistryIdentity, }, - verify_migration_role, ConnectionConfig, RegistryLockKey, RuntimePool, + verify_migration_role, ConnectionConfig, DatabaseConnectionCause, RegistryLockKey, RuntimePool, }; #[cfg(any(feature = "tooling", feature = "postgres-test"))] use crate::history_store::retain_descriptor; @@ -944,8 +944,10 @@ pub(crate) async fn rehearse_schema_fingerprint_with_connection( migration_role: &SqlIdentifier, runtime_role: &SqlIdentifier, registry: &CompiledRegistry, -) -> Result { - let (mut migration, migration_task) = connect_schema_test(migration_connection).await?; +) -> std::result::Result { + let (mut migration, migration_task) = connect_schema_test_with_cause(migration_connection) + .await + .map_err(SchemaRehearsalError::Connection)?; let migration_result: Result = async { verify_migration_role(&migration, migration_role).await?; let transaction = migration.transaction().await?; @@ -962,16 +964,37 @@ pub(crate) async fn rehearse_schema_fingerprint_with_connection( } .await; migration_task.abort(); - migration_result + migration_result.map_err(SchemaRehearsalError::Kernel) +} + +/// One schema rehearsal refusal, retaining a closed connection class only for +/// the initial connect and the existing value-free kernel error thereafter. +#[cfg(all(feature = "runtime", feature = "tooling"))] +pub(crate) enum SchemaRehearsalError { + Connection(DatabaseConnectionCause), + Kernel(PostgresKernelError), } #[cfg(all(feature = "runtime", feature = "tooling"))] pub(super) async fn connect_schema_test( config: &ConnectionConfig, ) -> Result<(Client, tokio::task::JoinHandle<()>)> { + connect_schema_test_with_cause(config) + .await + .map_err(|_| PostgresKernelError::Connection) +} + +#[cfg(all(feature = "runtime", feature = "tooling"))] +async fn connect_schema_test_with_cause( + config: &ConnectionConfig, +) -> std::result::Result<(Client, tokio::task::JoinHandle<()>), DatabaseConnectionCause> { match config.tls_connector() { ConnectionTls::Rustls(connector) => { - let (client, connection) = config.postgres().connect(connector).await?; + let (client, connection) = config + .postgres() + .connect(connector) + .await + .map_err(|error| config.connection_cause(&error))?; let task = tokio::spawn(async move { let _ = connection.await; }); @@ -979,7 +1002,11 @@ pub(super) async fn connect_schema_test( } #[cfg(feature = "postgres-test")] ConnectionTls::TestOnlyPlaintext => { - let (client, connection) = config.postgres().connect(NoTls).await?; + let (client, connection) = config + .postgres() + .connect(NoTls) + .await + .map_err(|error| config.connection_cause(&error))?; let task = tokio::spawn(async move { let _ = connection.await; }); diff --git a/crates/registry-breg/src/startup.rs b/crates/registry-breg/src/startup.rs index 4145ab8e77..0036acf531 100644 --- a/crates/registry-breg/src/startup.rs +++ b/crates/registry-breg/src/startup.rs @@ -1301,7 +1301,17 @@ async fn rehearse_schema_fingerprint_with_connection_config( registry, ) .await - .map_err(schema_preparation_error) + .map_err(schema_rehearsal_error) +} + +#[cfg(all(feature = "runtime", feature = "tooling"))] +fn schema_rehearsal_error(error: crate::postgres::SchemaRehearsalError) -> StartupError { + match error { + crate::postgres::SchemaRehearsalError::Connection(cause) => { + StartupError::DatabaseConnection(cause) + } + crate::postgres::SchemaRehearsalError::Kernel(error) => schema_preparation_error(error), + } } #[cfg(all(feature = "runtime", feature = "tooling", feature = "postgres-test"))] @@ -3323,6 +3333,25 @@ mod schema_preparation_error_tests { ); } + #[test] + fn classified_connection_refusals_keep_their_value_free_cause() { + for cause in [ + DatabaseConnectionCause::Unreachable, + DatabaseConnectionCause::Capacity, + DatabaseConnectionCause::Tls, + DatabaseConnectionCause::Authentication, + DatabaseConnectionCause::DatabaseMissing, + DatabaseConnectionCause::Timeout, + DatabaseConnectionCause::Configuration, + DatabaseConnectionCause::Secret, + ] { + assert_eq!( + schema_rehearsal_error(crate::postgres::SchemaRehearsalError::Connection(cause)), + StartupError::DatabaseConnection(cause) + ); + } + } + #[test] fn legacy_timer_store_packages_name_the_governed_upgrade_path() { for cause in [ diff --git a/crates/registry-bregctl/src/lib.rs b/crates/registry-bregctl/src/lib.rs index e9ef6754d4..5c5f704f4c 100644 --- a/crates/registry-bregctl/src/lib.rs +++ b/crates/registry-bregctl/src/lib.rs @@ -6800,6 +6800,9 @@ fn test_lifecycle_failure(error: TestLifecycleError) -> FailureReport { TestLifecycleError::RuntimeConfig(error) => { return runtime_config_failure("test", error); } + TestLifecycleError::DatabaseConnection(cause) => { + return schema_test_database_connection_failure(cause); + } TestLifecycleError::Journeys { message } => { return FailureReport { ok: false, @@ -6879,6 +6882,7 @@ fn test_lifecycle_failure(error: TestLifecycleError) -> FailureReport { TestLifecycleError::Candidate { .. } => unreachable!("handled before match"), TestLifecycleError::ReviewFingerprint { .. } => unreachable!("handled before match"), TestLifecycleError::FieldPatternSyntax { .. } => unreachable!("handled before match"), + TestLifecycleError::DatabaseConnection(_) => unreachable!("handled before match"), TestLifecycleError::Database => ( "test.database.unavailable", "database", @@ -6943,6 +6947,64 @@ fn test_lifecycle_failure(error: TestLifecycleError) -> FailureReport { } } +fn schema_test_database_connection_failure( + cause: registry_breg::postgres::DatabaseConnectionCause, +) -> FailureReport { + use registry_breg::postgres::DatabaseConnectionCause; + + let (code, message, action) = match cause { + DatabaseConnectionCause::Unreachable => ( + "test.database.unreachable", + "the schema-test database could not be reached; verify its address, network path, and availability", + SuggestedAction::PrepareSchemaTestDatabase, + ), + DatabaseConnectionCause::Capacity => ( + "test.database.capacity-exhausted", + "the schema-test database connection capacity is exhausted; free connections or increase PostgreSQL connection capacity", + SuggestedAction::PrepareSchemaTestDatabase, + ), + DatabaseConnectionCause::Tls => ( + "test.database.tls-refused", + "the schema-test database TLS connection was refused; verify the server certificate, name, and database.trustedRootCertificateRef", + SuggestedAction::PrepareSchemaTestDatabase, + ), + DatabaseConnectionCause::Authentication => ( + "test.database.authentication-refused", + "the schema-test database rejected authentication; verify database.roles.migration and its referenced credential", + SuggestedAction::PrepareSchemaTestDatabase, + ), + DatabaseConnectionCause::DatabaseMissing => ( + "test.database.missing", + "the schema-test database does not exist; create it or correct the referenced connection configuration", + SuggestedAction::PrepareSchemaTestDatabase, + ), + DatabaseConnectionCause::Timeout => ( + "test.database.timeout", + "the schema-test database connection timed out; verify availability and the configured pool timeouts", + SuggestedAction::PrepareSchemaTestDatabase, + ), + DatabaseConnectionCause::Configuration => ( + "test.database.configuration-refused", + "the schema-test database connection configuration was refused; correct the runtime database settings", + SuggestedAction::CorrectRuntimeConfiguration, + ), + DatabaseConnectionCause::Secret => ( + "test.database.secret-refused", + "a schema-test database connection secret could not be resolved; verify database.runtimeUrlRef, database.migrationUrlRef, database.trustedRootCertificateRef, and the enabled secret provider", + SuggestedAction::CorrectRuntimeConfiguration, + ), + }; + FailureReport { + ok: false, + command: "test", + diagnostics: vec![tool_diagnostic( + diagnostic(code, "database", message), + DiagnosticArtifact::SchemaTestDatabase, + action, + )], + } +} + /// Report a refused successor-migration rehearsal. Every message is built from /// authored identifiers and PostgreSQL's value-free error fields, never from a /// server message or detail. diff --git a/crates/registry-bregctl/src/test_lifecycle.rs b/crates/registry-bregctl/src/test_lifecycle.rs index fd2edafe15..8b19d5136a 100644 --- a/crates/registry-bregctl/src/test_lifecycle.rs +++ b/crates/registry-bregctl/src/test_lifecycle.rs @@ -14,7 +14,8 @@ use registry_breg::fixtures::{ use registry_breg::literal_text::{LiteralText, WRITE_THE_VALUE_OR_A_SECRET_REFERENCE}; use registry_breg::package::PackageError; use registry_breg::postgres::{ - BaselineFingerprintDrift, MigrationRehearsalError, SuccessorMigrationRehearsal, + BaselineFingerprintDrift, DatabaseConnectionCause, MigrationRehearsalError, + SuccessorMigrationRehearsal, }; use registry_breg::runtime_config::{load_runtime_config, RuntimeConfig, RuntimeConfigError}; use registry_breg::startup; @@ -111,6 +112,9 @@ pub(crate) enum TestLifecycleError { }, CredentialsDocument(Report), Database, + /// The fixed, value-free reason the schema-test database connection was + /// refused. The originating error and connection values are discarded. + DatabaseConnection(DatabaseConnectionCause), /// The fixed, value-free role or catalog invariant that schema-test /// preparation refused. DatabaseSetupRefused(&'static str), @@ -590,6 +594,9 @@ fn schema_preparation_error(error: startup::StartupError) -> TestLifecycleError startup::StartupError::SchemaTestSetupRefused(invariant) => { TestLifecycleError::DatabaseSetupRefused(invariant) } + startup::StartupError::DatabaseConnection(cause) => { + TestLifecycleError::DatabaseConnection(cause) + } _ => TestLifecycleError::Database, } } @@ -1253,6 +1260,70 @@ bindings: ); } + #[test] + fn classified_database_connection_refusals_keep_only_their_closed_cause() { + for (cause, code, action) in [ + ( + DatabaseConnectionCause::Unreachable, + "test.database.unreachable", + "prepare-schema-test-database", + ), + ( + DatabaseConnectionCause::Capacity, + "test.database.capacity-exhausted", + "prepare-schema-test-database", + ), + ( + DatabaseConnectionCause::Tls, + "test.database.tls-refused", + "prepare-schema-test-database", + ), + ( + DatabaseConnectionCause::Authentication, + "test.database.authentication-refused", + "prepare-schema-test-database", + ), + ( + DatabaseConnectionCause::DatabaseMissing, + "test.database.missing", + "prepare-schema-test-database", + ), + ( + DatabaseConnectionCause::Timeout, + "test.database.timeout", + "prepare-schema-test-database", + ), + ( + DatabaseConnectionCause::Configuration, + "test.database.configuration-refused", + "correct-runtime-configuration", + ), + ( + DatabaseConnectionCause::Secret, + "test.database.secret-refused", + "correct-runtime-configuration", + ), + ] { + let error = schema_preparation_error(startup::StartupError::DatabaseConnection(cause)); + let report = serde_json::to_value(crate::test_lifecycle_failure(error)) + .expect("connection refusal report serializes"); + let diagnostic = &report["diagnostics"][0]; + assert_eq!(diagnostic["code"], code); + assert_eq!(diagnostic["path"], "database"); + assert_eq!(diagnostic["artifact"], "schema-test-database"); + assert_eq!(diagnostic["suggestedAction"], action); + let serialized = report.to_string(); + for canary in [ + "postgresql://connection-canary", + "role-canary", + "secret-canary", + "certificate-canary", + ] { + assert!(!serialized.contains(canary), "{code} disclosed {canary}"); + } + } + } + #[test] fn a_refused_rehearsal_step_names_the_step_and_postgres_class_only() { use registry_breg::postgres::PostgresFailure; diff --git a/crates/registry-cli-docs/catalog.json b/crates/registry-cli-docs/catalog.json index 5e9863e843..8ccc617887 100644 --- a/crates/registry-cli-docs/catalog.json +++ b/crates/registry-cli-docs/catalog.json @@ -33,9 +33,9 @@ { "name": "serve", "invocation": "adapter serve", - "about": "Serve the governed facade", + "about": "Serve the governed record facade, typed payment connections, or both", "long_about": null, - "usage": "adapter serve [OPTIONS] --runtime-config --project ", + "usage": "adapter serve [OPTIONS] --runtime-config ", "arguments": [], "options": [ { @@ -50,7 +50,16 @@ { "display": "--project ", "description": "The directory holding project.yaml", - "always_required": true, + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--payments-config ", + "description": "Typed payment connections hosted on this listener", + "always_required": false, "repeatable": false, "default_values": [], "possible_values": [], @@ -90,7 +99,7 @@ { "name": "effective-contract", "invocation": "adapter effective-contract", - "about": "Export the loaded gateway contract without binding a listener", + "about": "Export the record-facade contract without binding a listener", "long_about": null, "usage": "adapter effective-contract [OPTIONS] --runtime-config --project ", "arguments": [], @@ -1412,6 +1421,141 @@ } ] }, + { + "name": "payments", + "invocation": "adapterctl payments", + "about": "Check typed payment connections or export their fixed operation contract", + "long_about": null, + "usage": "adapterctl payments [OPTIONS] ", + "arguments": [], + "options": [ + { + "display": "--format ", + "description": "Emit the selected command's report in this format", + "always_required": false, + "repeatable": false, + "default_values": [ + "human" + ], + "possible_values": [ + "human", + "json" + ], + "environment": null + }, + { + "display": "-h, --help", + "description": "Print help", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + } + ], + "constraints": [], + "subcommands": [ + { + "name": "check", + "invocation": "adapterctl payments check", + "about": "Validate one AdapterPayments file without fetching credentials or services", + "long_about": null, + "usage": "adapterctl payments check [OPTIONS] ", + "arguments": [ + { + "display": "", + "description": "AdapterPayments configuration file to validate", + "always_required": true, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + } + ], + "options": [ + { + "display": "--deny-warnings", + "description": "Refuse warnings as well as errors", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--format ", + "description": "Emit the selected command's report in this format", + "always_required": false, + "repeatable": false, + "default_values": [ + "human" + ], + "possible_values": [ + "human", + "json" + ], + "environment": null + }, + { + "display": "-h, --help", + "description": "Print help", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + } + ], + "constraints": [], + "subcommands": [] + }, + { + "name": "contract", + "invocation": "adapterctl payments contract", + "about": "Export fixed payment routes, authority and schemas for configured connections", + "long_about": null, + "usage": "adapterctl payments contract [OPTIONS] ", + "arguments": [ + { + "display": "", + "description": "AdapterPayments configuration file whose contract is exported", + "always_required": true, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + } + ], + "options": [ + { + "display": "--format ", + "description": "Emit the selected command's report in this format", + "always_required": false, + "repeatable": false, + "default_values": [ + "human" + ], + "possible_values": [ + "human", + "json" + ], + "environment": null + }, + { + "display": "-h, --help", + "description": "Print help", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + } + ], + "constraints": [], + "subcommands": [] + } + ] + }, { "name": "schemas", "invocation": "adapterctl schemas", diff --git a/crates/registry-coordinator/Cargo.toml b/crates/registry-coordinator/Cargo.toml index dbe1d3b491..06f1149aa4 100644 --- a/crates/registry-coordinator/Cargo.toml +++ b/crates/registry-coordinator/Cargo.toml @@ -28,7 +28,7 @@ workspace = true default = [] # Database suites opt in locally; downstream services are separate executables. postgres-test = [] -schema = ["dep:schemars", "registry-platform-config/schema", "registry-platform-yaml/schema", "registry-platform-audit/schema", "registry-platform-hooks/schema", "registry-breg-client/schema", "registry-messaging-core/schema", "registry-scheduling-core/schema", "registry-review-protocol/schema"] +schema = ["dep:schemars", "registry-platform-config/schema", "registry-platform-yaml/schema", "registry-platform-audit/schema", "registry-platform-hooks/schema", "registry-breg-client/schema", "registry-messaging-core/schema", "registry-payment-client/schema", "registry-scheduling-core/schema", "registry-review-protocol/schema"] [[example]] name = "problem-catalog" @@ -142,6 +142,7 @@ registry-breg-client.workspace = true registry-casework-client.workspace = true registry-messaging-client.workspace = true registry-messaging-core.workspace = true +registry-payment-client.workspace = true registry-platform-activation.workspace = true registry-platform-audit.workspace = true registry-platform-oidc.workspace = true diff --git a/crates/registry-coordinator/src/adapters.rs b/crates/registry-coordinator/src/adapters.rs index c072f6fda8..6277ae3a8c 100644 --- a/crates/registry-coordinator/src/adapters.rs +++ b/crates/registry-coordinator/src/adapters.rs @@ -12,6 +12,11 @@ use registry_casework_client::{CaseworkClient, CaseworkClientConfig, CaseworkTas use registry_messaging_client::{ MessagingClient, MessagingClientConfig, MessagingClientError, ProblemCode, SubmitMessageRequest, }; +use registry_payment_client::{ + CollectionAccepted, CollectionState, CollectionStatus, PaymentClient, PaymentClientConfig, + PaymentClientError, PaymentProblemCode, PaymentProtocolFailure, ReadCollection, RecordReceipt, + RequestCollection, +}; use registry_platform_crypto::PrivateJwk; use registry_platform_httputil::{ client::{PrivateKeyJwt, PrivateKeyJwtConfig, TokenError, TokenProvider}, @@ -55,6 +60,7 @@ enum Connection { client: MessagingClient, tokens: Arc, }, + Payments(Box), Casework(Box), External(Box), Decision(Box), @@ -68,6 +74,12 @@ struct SchedulingConnection { observation: Option>, } +struct PaymentConnection { + client: PaymentClient, + tokens: Arc, + result_check_seconds: u32, +} + struct TaskConnection { base_url: Url, options: BRegRecordOptions, @@ -289,6 +301,34 @@ impl HttpAdapters { .map_err(|_| config_error())?; Connection::Messaging { client, tokens } } + Product::Payments => { + let tokens = Arc::new( + tokens(&auth, key, &auth.resource, &auth.scopes) + .map_err(|_| config_error())?, + ); + let payment_connection = binding + .payment_connection + .cloned() + .ok_or_else(config_error)?; + let client = PaymentClient::new( + PaymentClientConfig::new(binding.base_url.clone(), payment_connection) + .with_maximum_mutation_retries(crate::operations::HTTP_MUTATION_RETRIES) + .with_attempt_timeout(REQUEST_TIMEOUT) + .with_connect_timeout(Duration::from_millis( + crate::operations::HTTP_CONNECT_TIMEOUT_MILLISECONDS, + )) + .with_maximum_response_bytes(FILE_BOUND), + ) + .map_err(|_| config_error())?; + Connection::Payments(Box::new(PaymentConnection { + client, + tokens, + result_check_seconds: binding.result_check_seconds.map_or( + crate::runtime::DEFAULT_RESULT_CHECK_SECONDS, + registry_platform_yaml::BoundedU32::get, + ), + })) + } Product::Casework => { let result_check_seconds = binding.result_check_seconds.map_or( crate::runtime::DEFAULT_RESULT_CHECK_SECONDS, @@ -384,6 +424,237 @@ pub(crate) fn token_failure(error: &TokenError) -> CallOutcome { } } +async fn payment_token( + connection: &PaymentConnection, +) -> std::result::Result { + connection + .tokens + .bearer_token() + .await + .map_err(|error| token_failure(&error)) +} + +fn payment_failure(error: PaymentClientError, operation: Operation) -> CallOutcome { + if matches!( + &error, + PaymentClientError::Problem { + code: PaymentProblemCode::ReceiptExpired, + .. + } + ) && operation == Operation::RequestCollection + { + return CallOutcome::ReceiptExpired; + } + if operation.has_dispatch_risk() && error.is_outcome_unknown() { + return CallOutcome::Uncertain { + code: match error { + PaymentClientError::Protocol { + failure: PaymentProtocolFailure::Correlation, + .. + } => "payment-correlation-mismatch", + PaymentClientError::Problem { + code: + PaymentProblemCode::ReceiptUnresolved + | PaymentProblemCode::RecoveryHeld + | PaymentProblemCode::OutcomeUnknown, + .. + } => "payment-unknown", + PaymentClientError::Problem { + code: PaymentProblemCode::ProviderProtocol, + .. + } => "payment-invalid-response", + PaymentClientError::Protocol { .. } => "payment-invalid-response", + _ => "transport-uncertain", + } + .into(), + }; + } + match error { + PaymentClientError::Transport { .. } + | PaymentClientError::Problem { + code: PaymentProblemCode::Unavailable, + .. + } => retryable("transport-unavailable"), + PaymentClientError::Problem { + code: PaymentProblemCode::Unauthenticated | PaymentProblemCode::Forbidden, + .. + } => refused("product-forbidden"), + PaymentClientError::Problem { + code: PaymentProblemCode::NotFound, + .. + } => refused("product-not-found"), + PaymentClientError::Problem { + code: + PaymentProblemCode::ReceiptUnresolved + | PaymentProblemCode::RecoveryHeld + | PaymentProblemCode::OutcomeUnknown, + .. + } => refused("payment-unknown"), + PaymentClientError::Protocol { + failure: PaymentProtocolFailure::Correlation, + .. + } => refused("payment-correlation-mismatch"), + PaymentClientError::InvalidRequest { .. } => refused("invalid-command"), + PaymentClientError::Protocol { .. } + | PaymentClientError::Problem { + code: PaymentProblemCode::ProviderProtocol, + .. + } => refused("payment-invalid-response"), + PaymentClientError::Configuration { .. } + | PaymentClientError::Problem { + code: + PaymentProblemCode::InvalidRequest + | PaymentProblemCode::Conflict + | PaymentProblemCode::ReceiptExpired, + .. + } => refused("product-refused"), + _ if operation.has_dispatch_risk() => CallOutcome::Uncertain { + code: "payment-unknown".into(), + }, + _ => refused("payment-unknown"), + } +} + +fn payment_success(value: T, operation: Operation) -> CallOutcome { + match serde_json::to_value(value) { + Ok(value) => CallOutcome::Success(value), + Err(_) if operation.has_dispatch_risk() => CallOutcome::Uncertain { + code: "payment-invalid-response".into(), + }, + Err(_) => refused("payment-invalid-response"), + } +} + +async fn payment_call(connection: &PaymentConnection, request: &CallRequest) -> CallOutcome { + let token = match payment_token(connection).await { + Ok(token) => token, + Err(outcome) => return outcome, + }; + match request.operation { + Operation::RequestCollection => { + let input: RequestCollection = match serde_json::from_value(request.input.clone()) { + Ok(input) => input, + Err(_) => return refused("invalid-command"), + }; + let Some(key) = request.idempotency_key.as_deref() else { + return refused("invalid-command"); + }; + match connection + .client + .request_collection(&token, key, &input) + .await + { + Ok(answer) => payment_success(answer.value, request.operation), + Err(error) => payment_failure(error, request.operation), + } + } + Operation::ReadCollection => { + let input: ReadCollection = match serde_json::from_value(request.input.clone()) { + Ok(input) => input, + Err(_) => return refused("invalid-command"), + }; + if request.idempotency_key.is_some() { + return refused("invalid-command"); + } + match connection.client.read_collection(&token, &input).await { + Ok(answer) => payment_success(answer.value, request.operation), + Err(error) => payment_failure(error, request.operation), + } + } + Operation::RecordReceipt => { + let input: RecordReceipt = match serde_json::from_value(request.input.clone()) { + Ok(input) => input, + Err(_) => return refused("invalid-command"), + }; + let Some(key) = request.idempotency_key.as_deref() else { + return refused("invalid-command"); + }; + match connection.client.record_receipt(&token, key, &input).await { + Ok(answer) => payment_success(answer.value, request.operation), + Err(error) => payment_failure(error, request.operation), + } + } + _ => refused("operation-unbound"), + } +} + +fn payment_accepted(operation: Operation, value: &serde_json::Value) -> Option { + match operation { + Operation::RequestCollection => serde_json::from_value(value.clone()).ok(), + Operation::ReadCollection => serde_json::from_value::(value.clone()) + .ok() + .map(|status| status.acceptance()), + _ => None, + } +} + +async fn payment_observe( + connection: &PaymentConnection, + request: &CallRequest, + accepted: &serde_json::Value, +) -> CompletionObservation { + let Some(expected) = payment_accepted(request.operation, accepted) + .filter(|accepted| accepted.validate().is_ok()) + else { + return CompletionObservation::Hold { + code: "payment-invalid-response".into(), + }; + }; + let token = match connection.tokens.bearer_token().await { + Ok(token) => token, + Err(_) => { + return CompletionObservation::Retryable { + code: "completion-unavailable".into(), + retry_after: None, + } + } + }; + match connection + .client + .read_collection( + &token, + &ReadCollection { + collection_id: expected.collection_id, + }, + ) + .await + { + Ok(answer) if answer.value.acceptance() != expected => CompletionObservation::Hold { + code: "payment-correlation-mismatch".into(), + }, + Ok(answer) => match answer.value.state { + CollectionState::Accepted | CollectionState::Pending | CollectionState::Unknown => { + CompletionObservation::Pending { retry_after: None } + } + CollectionState::Confirmed | CollectionState::Failed => { + match serde_json::to_value(answer.value) { + Ok(value) => CompletionObservation::Settled(value), + Err(_) => CompletionObservation::Hold { + code: "payment-invalid-response".into(), + }, + } + } + }, + Err(PaymentClientError::Transport { .. }) + | Err(PaymentClientError::Problem { + code: PaymentProblemCode::Unavailable, + .. + }) => CompletionObservation::Retryable { + code: "completion-unavailable".into(), + retry_after: None, + }, + Err(PaymentClientError::Protocol { + failure: PaymentProtocolFailure::Correlation, + .. + }) => CompletionObservation::Hold { + code: "payment-correlation-mismatch".into(), + }, + Err(_) => CompletionObservation::Hold { + code: "payment-unknown".into(), + }, + } +} + #[derive(Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] #[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] @@ -801,6 +1072,11 @@ impl AdapterSet for HttpAdapters { Err(_) => refused("product-refused"), } } + (Some(Connection::Payments(connection)), operation) + if operation.product() == "payments" => + { + payment_call(connection, request).await + } _ => refused("operation-unbound"), } } @@ -826,6 +1102,11 @@ impl AdapterSet for HttpAdapters { ) if request.operation.follows_proposal() => { crate::breg_proposal::observe(client, profile, request, accepted).await } + (CompletionKind::PaymentCollection {}, Some(Connection::Payments(connection))) + if request.operation.follows_collection() => + { + payment_observe(connection, request, accepted).await + } _ => CompletionObservation::Hold { code: "operation-unbound".into(), }, @@ -847,6 +1128,7 @@ impl AdapterSet for HttpAdapters { crate::runtime::DEFAULT_RESULT_CHECK_SECONDS, crate::runtime::ConnectionConfig::result_check_seconds, ), + Some(Connection::Payments(connection)) => connection.result_check_seconds, _ => crate::runtime::DEFAULT_RESULT_CHECK_SECONDS, }, }; @@ -862,6 +1144,7 @@ impl AdapterSet for HttpAdapters { completion.kind, crate::definition::CompletionKind::CaseworkResult {} | crate::definition::CompletionKind::BregProposal {} + | crate::definition::CompletionKind::PaymentCollection {} ) { self.config.minimum_observation_interval_seconds.get() } else { @@ -927,6 +1210,35 @@ impl AdapterSet for HttpAdapters { Err(_) => unresolved("observation-unavailable"), } } + (Some(Connection::Payments(connection)), Operation::RequestCollection) => { + let input: RequestCollection = match serde_json::from_value(request.input.clone()) { + Ok(input) => input, + Err(_) => return unresolved("invalid-command"), + }; + let token = match connection.tokens.bearer_token().await { + Ok(token) => token, + Err(_) => return unresolved("observation-unavailable"), + }; + match connection + .client + .collection_receipt(&token, idempotency_key, &input) + .await + { + Ok(answer) => match serde_json::to_value(answer.value) { + Ok(value) => ReconciliationOutcome::Confirmed(value), + Err(_) => unresolved("invalid-observation"), + }, + Err(PaymentClientError::Problem { + code: + PaymentProblemCode::ReceiptUnresolved + | PaymentProblemCode::ReceiptExpired + | PaymentProblemCode::RecoveryHeld + | PaymentProblemCode::OutcomeUnknown, + .. + }) => unresolved("receipt-unresolved"), + Err(_) => unresolved("observation-unavailable"), + } + } ( Some(Connection::Scheduling(connection)), Operation::CreateAppointment | Operation::ConfirmHold, diff --git a/crates/registry-coordinator/src/authoring.rs b/crates/registry-coordinator/src/authoring.rs index cc6b79dc93..04f331d3f8 100644 --- a/crates/registry-coordinator/src/authoring.rs +++ b/crates/registry-coordinator/src/authoring.rs @@ -1325,6 +1325,16 @@ fn compile(project: CoordinatorProject, path: &Path) -> Result { }, ); } + if uses.follows_collection() { + completions.insert( + "collection".into(), + CompletionDefinition { + kind: CompletionKind::PaymentCollection {}, + output: crate::contracts::payment_completion_schema().clone(), + revision: String::new(), + }, + ); + } authored_completions.insert(id.clone(), operation.completions); operations.insert( id, diff --git a/crates/registry-coordinator/src/contracts.rs b/crates/registry-coordinator/src/contracts.rs index b4d0d5dd17..4d489bf82c 100644 --- a/crates/registry-coordinator/src/contracts.rs +++ b/crates/registry-coordinator/src/contracts.rs @@ -824,6 +824,27 @@ pub fn casework_completion_schema() -> &'static Value { }) } +/// Authoritative state observed for the exact payment collection a call +/// accepted. Pending and unknown values remain observations, not completion. +pub fn payment_completion_schema() -> &'static Value { + static SCHEMA: OnceLock = OnceLock::new(); + SCHEMA.get_or_init(|| { + #[cfg(feature = "schema")] + { + let mut schema = derived::output::(); + derived::finish(&mut schema, "Payment collection completion"); + schema + } + #[cfg(not(feature = "schema"))] + { + serde_json::from_str(include_str!( + "../../../products/coordinator/generated/operations/payments.collection.completion.schema.json" + )) + .expect("generated payment completion schema") + } + }) +} + /// Shared Review and event wire schemas, generated from their owning types. pub fn admission_schemas() -> &'static Value { static SCHEMAS: OnceLock = OnceLock::new(); @@ -982,6 +1003,11 @@ pub fn generate() -> Result, serde_json::Error> { "casework.submit-review-request.v1.result.completion.schema.json".into(), text, ); + let mut payment = derived::output::(); + derived::finish(&mut payment, "Payment collection completion"); + let mut text = serde_json::to_string_pretty(&payment)?; + text.push('\n'); + files.insert("payments.collection.completion.schema.json".into(), text); for descriptor in crate::operations::descriptors() { let Some(refusal) = derived_declared_refusal(descriptor) else { continue; @@ -1241,6 +1267,27 @@ mod derived { ) } + pub(super) fn request_collection() -> (Value, Value) { + ( + input::(), + output::(), + ) + } + + pub(super) fn read_collection() -> (Value, Value) { + ( + input::(), + output::(), + ) + } + + pub(super) fn record_receipt() -> (Value, Value) { + ( + input::(), + output::(), + ) + } + /// What the adapter accepts: the deserialization contract of its input type. pub(super) fn input() -> Value { let generator = SchemaSettings::draft2020_12() diff --git a/crates/registry-coordinator/src/definition.rs b/crates/registry-coordinator/src/definition.rs index 9e355edefa..cfcafcbc1c 100644 --- a/crates/registry-coordinator/src/definition.rs +++ b/crates/registry-coordinator/src/definition.rs @@ -410,6 +410,8 @@ pub enum CompletionKind { /// The decision on a BReg Proposal the run started, submitted or read, /// settled only from the current Proposal Get. BregProposal {}, + /// The authoritative status of the exact collection this call accepted. + PaymentCollection {}, BoundedPoll { interpret: String, interval_seconds: u32, @@ -1761,6 +1763,10 @@ fn workflow_findings(flow: &Workflow) -> Vec { &completion.output, ) } + CompletionKind::PaymentCollection {} => { + operation.uses.follows_collection() + && completion.output == *crate::contracts::payment_completion_schema() + } CompletionKind::BoundedPoll { interpret, interval_seconds, diff --git a/crates/registry-coordinator/src/operations.rs b/crates/registry-coordinator/src/operations.rs index 40f7fb7e7d..88582f0f86 100644 --- a/crates/registry-coordinator/src/operations.rs +++ b/crates/registry-coordinator/src/operations.rs @@ -101,6 +101,17 @@ impl OperationDescriptor { "authenticatedWake":false, "defaultIntervalSeconds":crate::runtime::DEFAULT_RESULT_CHECK_SECONDS }), + id if Operation::parse(id).is_some_and(Operation::follows_collection) => json!({ + "name":"collection", "profile":"payment-collection", + "acceptedBinding":["collectionId","billId","billVersion","bindingRevision","simulation"], + "authority":"current-bound-payment-connection", + "terminalEvidence":"validated-authoritative-collection-read", + "pendingStates":["accepted","pending","unknown"], + "settledStates":["confirmed","failed"], + "paymentSuccessState":"confirmed", + "authenticatedWake":false, + "defaultIntervalSeconds":crate::runtime::DEFAULT_RESULT_CHECK_SECONDS + }), _ => serde_json::Value::Null, }; if let Some(fields) = observation.as_object_mut() { @@ -311,6 +322,9 @@ macro_rules! operation_catalog { CancelProposal => "breg.cancel-proposal/v1", mutation("breg", false, true), cancel_proposal; LookupRecord => "breg.lookup-record/v1", declared_read("breg"), lookup_record; ReadRecordV2 => "breg.read-record/v2", read_v2("breg"), read_record_v2; + RequestCollection => "payments.request-collection/v1", mutation("payments", true, false), request_collection; + ReadCollection => "payments.read-collection/v1", read("payments"), read_collection; + RecordReceipt => "payments.record-receipt/v1", mutation("payments", false, false), record_receipt; } }; } @@ -370,6 +384,9 @@ pub fn failure_code(code: &str) -> Option<&'static str> { "in-force-ambiguous" => Some("in-force-ambiguous"), "proposal-unreadable" => Some("proposal-unreadable"), "proposal-handoff-refused" => Some("proposal-handoff-refused"), + "payment-invalid-response" => Some("payment-invalid-response"), + "payment-correlation-mismatch" => Some("payment-correlation-mismatch"), + "payment-unknown" => Some("payment-unknown"), _ => None, } } @@ -429,6 +446,12 @@ mod tests { (Operation::CancelProposal, "breg.cancel-proposal/v1"), (Operation::LookupRecord, "breg.lookup-record/v1"), (Operation::ReadRecordV2, "breg.read-record/v2"), + ( + Operation::RequestCollection, + "payments.request-collection/v1", + ), + (Operation::ReadCollection, "payments.read-collection/v1"), + (Operation::RecordReceipt, "payments.record-receipt/v1"), ]; assert_eq!( descriptors() @@ -578,6 +601,8 @@ mod tests { Operation::StartProposal, Operation::SubmitProposal, Operation::ExternalCommand, + Operation::RequestCollection, + Operation::RecordReceipt, ]; let allowed_mutations = [ Operation::SubmitMessage, @@ -634,6 +659,33 @@ mod tests { assert!(!review.supports_read_receipt()); assert_eq!(review.recovery(), RecoverySemantics::SameCommand); } + assert_eq!(Operation::RequestCollection.product(), "payments"); + assert!(Operation::RequestCollection.requires_key()); + assert!(Operation::RequestCollection.supports_read_receipt()); + assert_eq!( + Operation::RequestCollection.recovery(), + RecoverySemantics::SameCommandAndReceipt + ); + assert!(Operation::RequestCollection.follows_collection()); + let completion = + &Operation::RequestCollection.descriptor().host_contract()["completionObservation"]; + assert_eq!( + completion["pendingStates"], + serde_json::json!(["accepted", "pending", "unknown"]) + ); + assert_eq!( + completion["settledStates"], + serde_json::json!(["confirmed", "failed"]) + ); + assert_eq!(completion["paymentSuccessState"], "confirmed"); + assert!(Operation::ReadCollection.is_read()); + assert!(Operation::ReadCollection.follows_collection()); + assert!(Operation::RecordReceipt.requires_key()); + assert_eq!( + Operation::RecordReceipt.recovery(), + RecoverySemantics::SameCommand + ); + assert!(!Operation::RecordReceipt.follows_collection()); } #[test] diff --git a/crates/registry-coordinator/src/protocol.rs b/crates/registry-coordinator/src/protocol.rs index 9e12b84027..fd370d5fd4 100644 --- a/crates/registry-coordinator/src/protocol.rs +++ b/crates/registry-coordinator/src/protocol.rs @@ -71,6 +71,8 @@ impl Operation { | Self::StartProposal | Self::SubmitProposal | Self::ExternalCommand + | Self::RequestCollection + | Self::RecordReceipt ) } @@ -131,6 +133,12 @@ impl Operation { Self::ReadProposal | Self::StartProposal | Self::SubmitProposal ) } + + /// Payment operations whose accepted output fixes the authoritative + /// collection read a named completion observes. + pub fn follows_collection(self) -> bool { + matches!(self, Self::RequestCollection | Self::ReadCollection) + } } impl Serialize for Operation { @@ -434,6 +442,7 @@ pub trait AdapterSet: Send + Sync { completion.kind, crate::definition::CompletionKind::CaseworkResult {} | crate::definition::CompletionKind::BregProposal {} + | crate::definition::CompletionKind::PaymentCollection {} ) { crate::store::WAIT_READ_SPACING_SECONDS } else { diff --git a/crates/registry-coordinator/src/runtime.rs b/crates/registry-coordinator/src/runtime.rs index 57d48ddb43..11203b81c4 100644 --- a/crates/registry-coordinator/src/runtime.rs +++ b/crates/registry-coordinator/src/runtime.rs @@ -31,6 +31,7 @@ pub enum Product { Breg, Casework, Messaging, + Payments, Scheduling, } @@ -184,6 +185,7 @@ pub enum ConnectionConfig { Breg(BregConnectionConfig), CaseworkReviewProducer(CaseworkConnectionConfig), Messaging(MessagingConnectionConfig), + Payments(PaymentConnectionConfig), Scheduling(Box), ExternalHttp(crate::external_http::ExternalHttpConfig), Evaluation(crate::decision::DecisionConfig), @@ -233,6 +235,24 @@ pub struct MessagingConnectionConfig { pub authorization: AuthorizationConfig, } +#[derive(Clone, Serialize, Deserialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct PaymentConnectionConfig { + #[serde(deserialize_with = "endpoint")] + #[cfg_attr(feature = "schema", schemars(with = "registry_platform_yaml::Url"))] + pub base_url: Url, + /// The Adapter payment connection selected by this Coordinator binding. + #[serde(deserialize_with = "local")] + #[cfg_attr(feature = "schema", schemars(with = "registry_platform_yaml::LocalId"))] + pub payment_connection: String, + pub authorization: AuthorizationConfig, + /// Spacing between authoritative payment status observations. + #[serde(default, skip_serializing_if = "Option::is_none")] + #[cfg_attr(feature = "schema", schemars(extend("default" = DEFAULT_RESULT_CHECK_SECONDS)))] + pub result_check_seconds: Option>, +} + #[derive(Clone, Serialize, Deserialize)] #[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] #[serde(rename_all = "camelCase", deny_unknown_fields)] @@ -280,6 +300,7 @@ pub struct ProductBinding<'a> { pub authorization: &'a AuthorizationConfig, pub observation_authorization: Option<&'a AuthorizationConfig>, pub profile: Option<&'a String>, + pub payment_connection: Option<&'a String>, pub producer: Option<&'a String>, pub completion: Option<&'a ReviewCompletionConfig>, pub result_check_seconds: Option>, @@ -293,6 +314,7 @@ impl ConnectionConfig { authorization, observation_authorization, profile, + payment_connection, producer, completion, result_check_seconds, @@ -305,6 +327,7 @@ impl ConnectionConfig { Some(&c.profile), None, None, + None, c.result_check_seconds, ), Self::Messaging(c) => ( @@ -316,6 +339,7 @@ impl ConnectionConfig { None, None, None, + None, ), Self::Scheduling(c) => ( Product::Scheduling, @@ -326,6 +350,7 @@ impl ConnectionConfig { None, None, None, + None, ), Self::CaseworkReviewProducer(c) => ( Product::Casework, @@ -333,10 +358,22 @@ impl ConnectionConfig { &c.authorization, None, Some(&c.profile), + None, Some(&c.producer), c.completion.as_ref(), c.result_check_seconds, ), + Self::Payments(c) => ( + Product::Payments, + &c.base_url, + &c.authorization, + None, + None, + Some(&c.payment_connection), + None, + None, + c.result_check_seconds, + ), Self::ExternalHttp(_) | Self::Evaluation(_) => return None, }; Some(ProductBinding { @@ -345,6 +382,7 @@ impl ConnectionConfig { authorization, observation_authorization, profile, + payment_connection, producer, completion, result_check_seconds, @@ -373,6 +411,7 @@ impl ConnectionConfig { match self { Self::Breg(c) => Some(&mut c.authorization), Self::Messaging(c) => Some(&mut c.authorization), + Self::Payments(c) => Some(&mut c.authorization), Self::Scheduling(c) => Some(&mut c.authorization), Self::CaseworkReviewProducer(c) => Some(&mut c.authorization), Self::ExternalHttp(_) | Self::Evaluation(_) => None, @@ -405,6 +444,7 @@ impl ConnectionConfig { Self::Breg(_) => "breg", Self::CaseworkReviewProducer(_) => "casework", Self::Messaging(_) => "messaging", + Self::Payments(_) => "payments", Self::Scheduling(_) => "scheduling", Self::ExternalHttp(_) => "external-http", Self::Evaluation(_) => "evaluation", @@ -423,6 +463,7 @@ impl Serialize for ConnectionConfig { ("casework-review-producer", serde_json::to_value(c)) } Self::Messaging(c) => ("messaging", serde_json::to_value(c)), + Self::Payments(c) => ("payments", serde_json::to_value(c)), Self::Scheduling(c) => ("scheduling", serde_json::to_value(c)), Self::ExternalHttp(c) => ("external-http", serde_json::to_value(c)), Self::Evaluation(c) => ("evaluation", serde_json::to_value(c)), @@ -1027,6 +1068,9 @@ impl RuntimeConfig { if binding.product == Product::Casework { identity["producer"] = json!(binding.producer); } + if binding.product == Product::Payments { + identity["paymentConnection"] = json!(binding.payment_connection); + } identities.insert(name, identity); } let value = json!({"connections":identities,"minimumObservationIntervalSeconds":self.minimum_observation_interval_seconds}); diff --git a/crates/registry-coordinator/src/scenarios.rs b/crates/registry-coordinator/src/scenarios.rs index 77b3175c26..4671de3a57 100644 --- a/crates/registry-coordinator/src/scenarios.rs +++ b/crates/registry-coordinator/src/scenarios.rs @@ -1435,9 +1435,45 @@ fn check_event( .map_err(|_| broken("its members do not form a review result".into()))?; result.check().map_err(|rule| broken(rule.to_string()))?; } + if matches!(completion.kind, CompletionKind::PaymentCollection {}) { + let status = + serde_json::from_value::(value.clone()) + .map_err(|_| { + error( + "scenario.wait-event", + pointer.clone(), + format!("the payment status stated for step {step} is malformed"), + "Correct the stated payment status so the payment protocol accepts it.", + ) + })?; + status.validate().map_err(|_| { + error( + "scenario.wait-event", + pointer.clone(), + format!("the payment status stated for step {step} carries inconsistent evidence"), + "Keep providerReference only on confirmed and failureReason only on failed status.", + ) + })?; + if !payment_completion_settles(status.state) { + return Err(error( + "scenario.wait-event", + pointer, + format!("the payment status stated for step {step} is not terminal"), + "Use confirmed or failed for an event that settles the wait, or state an explicit timeout.", + )); + } + } Ok(()) } +fn payment_completion_settles(state: registry_payment_client::CollectionState) -> bool { + matches!( + state, + registry_payment_client::CollectionState::Confirmed + | registry_payment_client::CollectionState::Failed + ) +} + /// A stated event belongs to the request its wait names. A review result /// carries the request identifier, subject, policy and submission digest /// the request step accepted, as the producer client requires of every @@ -1500,10 +1536,45 @@ fn correlate( format!("Copy proposalId from the success reply to step {request}."), )) } + CompletionKind::PaymentCollection {} => { + let accepted = outputs.get(request).and_then(payment_acceptance); + let observed = + serde_json::from_value::(value.clone()) + .ok() + .map(|status| status.acceptance()); + let (Some(accepted), Some(observed)) = (accepted, observed) else { + return Err(error( + "scenario.wait-event", + format!("/waits/{step}/value"), + format!("the payment status stated for step {step} cannot be matched to step {request}"), + format!("Give step {request} a success reply that satisfies its payment operation output."), + )); + }; + if observed == accepted { + Ok(()) + } else { + Err(error( + "scenario.wait-event", + format!("/waits/{step}/value/collectionId"), + format!("the payment status stated for step {step} does not retain the exact collection binding step {request} accepted"), + format!("Copy collectionId, billId, billVersion, bindingRevision and simulation from step {request}."), + )) + } + } CompletionKind::BoundedPoll { .. } => Ok(()), } } +fn payment_acceptance(value: &Value) -> Option { + serde_json::from_value::(value.clone()) + .ok() + .or_else(|| { + serde_json::from_value::(value.clone()) + .ok() + .map(|status| status.acceptance()) + }) +} + /// The differences one case lists before it counts the rest. const MISMATCHES_LISTED: usize = 20; @@ -1976,3 +2047,23 @@ fn error( .at(SCENARIOS_FILE, pointer) .suggest(action) } + +#[cfg(test)] +mod payment_tests { + use super::*; + use registry_payment_client::CollectionState; + + #[test] + fn only_terminal_payment_states_settle_a_scenario_wait() { + for state in [ + CollectionState::Accepted, + CollectionState::Pending, + CollectionState::Unknown, + ] { + assert!(!payment_completion_settles(state)); + } + for state in [CollectionState::Confirmed, CollectionState::Failed] { + assert!(payment_completion_settles(state)); + } + } +} diff --git a/crates/registry-coordinator/tests/payment_adapter.rs b/crates/registry-coordinator/tests/payment_adapter.rs new file mode 100644 index 0000000000..c37f0d96db --- /dev/null +++ b/crates/registry-coordinator/tests/payment_adapter.rs @@ -0,0 +1,285 @@ +// SPDX-License-Identifier: Apache-2.0 +//! Native payment calls, original-command recovery, and authoritative named +//! completion observations through the configured Adapter connection. +mod support; + +use registry_coordinator::{ + adapters::{ConnectionConfig, HttpAdapters}, + definition::{CompletionDefinition, CompletionKind}, + protocol::{ + AdapterSet, CallOutcome, CallRequest, CompletionObservation, Operation, + ReconciliationOutcome, + }, + runtime::PaymentConnectionConfig, +}; +use registry_payment_client::PaymentProblemCode; +use serde_json::{json, Value}; +use uuid::Uuid; +use wiremock::{ + matchers::{body_json, header, method, path}, + Mock, MockServer, ResponseTemplate, +}; + +const KEY: &str = "service-payment-attempt-1"; + +fn accepted(collection_id: Uuid, bill_id: Uuid) -> Value { + json!({ + "collectionId": collection_id, + "billId": bill_id, + "billVersion": 3, + "bindingRevision": "sha256:synthetic-binding", + "simulation": true + }) +} + +fn status(collection_id: Uuid, bill_id: Uuid, state: &str) -> Value { + let mut value = json!({ + "collectionId": collection_id, + "billId": bill_id, + "billVersion": 3, + "bindingRevision": "sha256:synthetic-binding", + "simulation": true, + "state": state, + "money": {"value": "25.00", "currency": "USD", "scale": 2} + }); + if state == "confirmed" { + value["providerReference"] = json!("SIM-confirmed-1"); + } + if state == "failed" { + value["failureReason"] = json!("payer-rejected"); + } + value +} + +fn json_answer(status: u16, body: Value) -> ResponseTemplate { + ResponseTemplate::new(status) + .insert_header("traceparent", support::TRACE) + .set_body_raw(body.to_string(), "application/json") +} + +fn problem(code: PaymentProblemCode) -> ResponseTemplate { + ResponseTemplate::new(code.status()) + .insert_header("traceparent", support::TRACE) + .set_body_raw( + json!({ + "type": code.type_uri(), + "title": code.as_str(), + "status": code.status(), + "code": code + }) + .to_string(), + "application/problem+json", + ) +} + +fn request(bill_id: Uuid) -> CallRequest { + CallRequest { + connection: "payments".into(), + operation: Operation::RequestCollection, + input: json!({"billId": bill_id, "billVersion": 3}), + idempotency_key: Some(KEY.into()), + operation_contract: None, + } +} + +fn completion() -> CompletionDefinition { + CompletionDefinition { + kind: CompletionKind::PaymentCollection {}, + output: registry_coordinator::contracts::payment_completion_schema().clone(), + revision: String::new(), + } +} + +struct Fixture { + adapters: HttpAdapters, + payment: MockServer, + _token: MockServer, + _root: tempfile::TempDir, +} + +async fn fixture() -> Fixture { + let token = MockServer::start().await; + let payment = MockServer::start().await; + let root = tempfile::tempdir().unwrap(); + let issuer = support::issuer().await; + let mut config = support::config(root.path(), &issuer, &payment.uri(), &payment.uri()); + let mut authorization = config.connections["applications"] + .authorization() + .unwrap() + .clone(); + authorization.token_endpoint = format!("{}/token", token.uri()).parse().unwrap(); + authorization.resource = "urn:example:payments".into(); + authorization.scopes = vec!["payments:collect".into()]; + config.connections.insert( + "payments".into(), + ConnectionConfig::Payments(PaymentConnectionConfig { + base_url: payment.uri().parse().unwrap(), + payment_connection: "service-fees".into(), + authorization, + result_check_seconds: None, + }), + ); + Mock::given(method("POST")) + .and(path("/token")) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({ + "access_token": "fixture-token", + "token_type": "Bearer", + "expires_in": 40, + "issued_token_type": "urn:ietf:params:oauth:token-type:access_token" + }))) + .mount(&token) + .await; + let adapters = HttpAdapters::new(&config).unwrap(); + issuer.stop().await; + Fixture { + adapters, + payment, + _token: token, + _root: root, + } +} + +#[tokio::test] +async fn collection_request_and_recovery_use_the_exact_original_command() { + let fixture = fixture().await; + let collection_id = Uuid::new_v4(); + let bill_id = Uuid::new_v4(); + let command = request(bill_id); + let acceptance = accepted(collection_id, bill_id); + Mock::given(method("POST")) + .and(path("/v1/payments/service-fees/collections")) + .and(header("authorization", "Bearer fixture-token")) + .and(header("idempotency-key", KEY)) + .and(body_json(json!({"billId": bill_id, "billVersion": 3}))) + .respond_with(json_answer(202, acceptance.clone())) + .expect(1) + .mount(&fixture.payment) + .await; + Mock::given(method("POST")) + .and(path("/v1/payments/service-fees/collections/receipt")) + .and(header("authorization", "Bearer fixture-token")) + .and(header("idempotency-key", KEY)) + .and(body_json(json!({"billId": bill_id, "billVersion": 3}))) + .respond_with(json_answer(200, acceptance.clone())) + .expect(1) + .mount(&fixture.payment) + .await; + + assert!(matches!( + fixture.adapters.call(&command).await, + CallOutcome::Success(value) if value == acceptance + )); + assert!(matches!( + fixture.adapters.reconcile(&command, None).await, + ReconciliationOutcome::Confirmed(value) if value == acceptance + )); +} + +#[tokio::test] +async fn ambiguous_mutation_response_holds_until_read_only_recovery_resolves() { + let fixture = fixture().await; + let bill_id = Uuid::new_v4(); + let command = request(bill_id); + Mock::given(method("POST")) + .and(path("/v1/payments/service-fees/collections")) + .respond_with(problem(PaymentProblemCode::ProviderProtocol)) + .expect(1) + .mount(&fixture.payment) + .await; + Mock::given(method("POST")) + .and(path("/v1/payments/service-fees/collections/receipt")) + .respond_with(problem(PaymentProblemCode::ReceiptUnresolved)) + .expect(1) + .mount(&fixture.payment) + .await; + + assert!(matches!( + fixture.adapters.call(&command).await, + CallOutcome::Uncertain { code } if code == "payment-invalid-response" + )); + assert!(matches!( + fixture.adapters.reconcile(&command, None).await, + ReconciliationOutcome::Unresolved { code } if code == "receipt-unresolved" + )); +} + +#[tokio::test] +async fn payment_authentication_failure_is_a_value_free_refusal() { + let fixture = fixture().await; + Mock::given(method("POST")) + .and(path("/v1/payments/service-fees/collections")) + .respond_with(problem(PaymentProblemCode::Unauthenticated)) + .expect(1) + .mount(&fixture.payment) + .await; + + assert!(matches!( + fixture.adapters.call(&request(Uuid::new_v4())).await, + CallOutcome::Refused { code } if code == "product-forbidden" + )); +} + +#[tokio::test] +async fn payment_completion_settles_only_terminal_exactly_bound_state() { + for (state, settles) in [ + ("accepted", false), + ("pending", false), + ("unknown", false), + ("confirmed", true), + ("failed", true), + ] { + let fixture = fixture().await; + let collection_id = Uuid::new_v4(); + let bill_id = Uuid::new_v4(); + let command = request(bill_id); + let acceptance = accepted(collection_id, bill_id); + Mock::given(method("GET")) + .and(path(format!( + "/v1/payments/service-fees/collections/{collection_id}" + ))) + .respond_with(json_answer(200, status(collection_id, bill_id, state))) + .expect(1) + .mount(&fixture.payment) + .await; + + let observed = fixture + .adapters + .observe_completion(&command, &acceptance, &completion()) + .await; + assert_eq!( + matches!(&observed, CompletionObservation::Settled(_)), + settles + ); + if !settles { + assert!(matches!(&observed, CompletionObservation::Pending { .. })); + } + } + + let fixture = fixture().await; + let collection_id = Uuid::new_v4(); + let bill_id = Uuid::new_v4(); + let other_bill_id = Uuid::new_v4(); + Mock::given(method("GET")) + .and(path(format!( + "/v1/payments/service-fees/collections/{collection_id}" + ))) + .respond_with(json_answer( + 200, + status(collection_id, other_bill_id, "confirmed"), + )) + .expect(1) + .mount(&fixture.payment) + .await; + let observed = fixture + .adapters + .observe_completion( + &request(bill_id), + &accepted(collection_id, bill_id), + &completion(), + ) + .await; + assert!(matches!( + observed, + CompletionObservation::Hold { code } if code == "payment-correlation-mismatch" + )); +} diff --git a/crates/registry-language-server/tests/coordinator_navigation.rs b/crates/registry-language-server/tests/coordinator_navigation.rs index a1f722ec7b..866a1bf7c1 100644 --- a/crates/registry-language-server/tests/coordinator_navigation.rs +++ b/crates/registry-language-server/tests/coordinator_navigation.rs @@ -190,8 +190,8 @@ fn every_maintained_coordinator_workflow_has_no_invented_missing_local_reference count += 1; } assert_eq!( - count, 11, - "cover every maintained native and Review workflow" + count, 12, + "cover every maintained Coordinator workflow, including payments" ); } diff --git a/crates/registry-payment-client/Cargo.toml b/crates/registry-payment-client/Cargo.toml new file mode 100644 index 0000000000..6bc60a1170 --- /dev/null +++ b/crates/registry-payment-client/Cargo.toml @@ -0,0 +1,31 @@ +[package] +name = "registry-payment-client" +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +description = "Bounded Rust client for the Adapter payment collection capability." +repository.workspace = true +publish = false + +[lints] +workspace = true + +[features] +schema = ["registry-payment-protocol/schema"] + +[dependencies] +registry-payment-protocol.workspace = true +registry-platform-canonical-json.workspace = true +registry-platform-httpsec.workspace = true +registry-platform-httputil.workspace = true +reqwest.workspace = true +serde.workspace = true +serde_json.workspace = true +thiserror.workspace = true +url.workspace = true +uuid = { workspace = true, features = ["serde"] } + +[dev-dependencies] +axum.workspace = true +tokio = { workspace = true, features = ["io-util"] } diff --git a/crates/registry-payment-client/src/client.rs b/crates/registry-payment-client/src/client.rs new file mode 100644 index 0000000000..65c0459225 --- /dev/null +++ b/crates/registry-payment-client/src/client.rs @@ -0,0 +1,414 @@ +// SPDX-License-Identifier: Apache-2.0 + +use std::fmt; + +use registry_payment_protocol::{ + CollectionAccepted, CollectionStatus, PaymentProblem, ReadCollection, RecordReceipt, + RegistryReceipt, RequestCollection, +}; +use registry_platform_httpsec::response_trace_id; +use registry_platform_httputil::client::{ + build_client, classify_keyed_attempt, read_failure_kind, retry_keyed_mutation, + send_failure_kind, BearerToken, KeyedMutationAttempt, OutboundOptions, RetryAfter, + ServiceBaseUrl, +}; +use registry_platform_httputil::{ + read_bounded, retry_after_seconds, url::append_path_segments, validate_response_headers, +}; +use reqwest::header::{ACCEPT, AUTHORIZATION, CONTENT_TYPE}; +use reqwest::{Response, StatusCode, Url}; +use serde::de::DeserializeOwned; +use uuid::Uuid; + +use crate::{PaymentClientConfig, PaymentClientError, PaymentProtocolFailure}; + +const JSON_MEDIA_TYPE: &str = "application/json"; +const PROBLEM_MEDIA_TYPE: &str = "application/problem+json"; +const IDEMPOTENCY_KEY_HEADER: &str = "Idempotency-Key"; +const MAXIMUM_PROBLEM_BYTES: u64 = 8 * 1024; +const MAXIMUM_RETRY_AFTER_SECONDS: u64 = 86_400; + +/// One completed call with its validated response trace identifier. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct PaymentComplete { + pub value: T, + pub trace_id: String, +} + +pub struct PaymentClient { + http: reqwest::Client, + base_url: ServiceBaseUrl, + connection: String, + maximum_response_bytes: u64, + maximum_mutation_retries: u8, +} + +impl fmt::Debug for PaymentClient { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter + .debug_struct("PaymentClient") + .field("base_url", &"") + .field("connection", &"") + .field("maximum_response_bytes", &self.maximum_response_bytes) + .field("maximum_mutation_retries", &self.maximum_mutation_retries) + .finish_non_exhaustive() + } +} + +impl PaymentClient { + pub fn new(config: PaymentClientConfig) -> Result { + let base_url = config.validate()?; + let http = build_client(OutboundOptions { + request_timeout: config.attempt_timeout, + connect_timeout: config.connect_timeout, + user_agent: config.user_agent.as_deref(), + trusted_root_certificates: config.trusted_root_certificates.as_deref(), + }) + .map_err(|_| PaymentClientError::configuration("the HTTP client could not be built"))?; + Ok(Self { + http, + base_url, + connection: config.connection, + maximum_response_bytes: config.maximum_response_bytes, + maximum_mutation_retries: config.maximum_mutation_retries, + }) + } + + /// Request one collection attempt for the exact authoritative bill. + pub async fn request_collection( + &self, + token: &BearerToken, + idempotency_key: &str, + request: &RequestCollection, + ) -> Result, PaymentClientError> { + validate_key(idempotency_key)?; + request + .validate() + .map_err(|_| PaymentClientError::invalid_request("the bill identity is invalid"))?; + let builder = self + .http + .post(self.collections_url()?) + .header(AUTHORIZATION, token.authorization_header_value()) + .header(ACCEPT, JSON_MEDIA_TYPE) + .header(CONTENT_TYPE, JSON_MEDIA_TYPE) + .header(IDEMPOTENCY_KEY_HEADER, idempotency_key) + .json(request); + let answer: PaymentComplete = + self.send_keyed_json(builder, StatusCode::ACCEPTED).await?; + validate_acceptance( + &answer.value, + request, + StatusCode::ACCEPTED, + &answer.trace_id, + )?; + Ok(answer) + } + + /// Read the retained acceptance for the exact original key and request. + /// This is one read-only exchange and is never retried automatically. + pub async fn collection_receipt( + &self, + token: &BearerToken, + idempotency_key: &str, + request: &RequestCollection, + ) -> Result, PaymentClientError> { + validate_key(idempotency_key)?; + request + .validate() + .map_err(|_| PaymentClientError::invalid_request("the bill identity is invalid"))?; + let builder = self + .http + .post(self.path_url(&["collections", "receipt"])?) + .header(AUTHORIZATION, token.authorization_header_value()) + .header(ACCEPT, JSON_MEDIA_TYPE) + .header(CONTENT_TYPE, JSON_MEDIA_TYPE) + .header(IDEMPOTENCY_KEY_HEADER, idempotency_key) + .json(request); + let answer = self.json_answer(builder, StatusCode::OK).await?; + validate_acceptance(&answer.value, request, StatusCode::OK, &answer.trace_id)?; + Ok(answer) + } + + /// Read current provider state for one accepted collection. + pub async fn read_collection( + &self, + token: &BearerToken, + request: &ReadCollection, + ) -> Result, PaymentClientError> { + validate_collection_id(request.collection_id)?; + let builder = self + .http + .get(self.path_url(&["collections", &request.collection_id.to_string()])?) + .header(AUTHORIZATION, token.authorization_header_value()) + .header(ACCEPT, JSON_MEDIA_TYPE); + let answer: PaymentComplete = + self.json_answer(builder, StatusCode::OK).await?; + answer + .value + .validate() + .map_err(|_| body_protocol(StatusCode::OK, Some(answer.trace_id.clone())))?; + if answer.value.collection_id != request.collection_id { + return Err(correlation_protocol(StatusCode::OK, Some(answer.trace_id))); + } + Ok(answer) + } + + /// Record the confirmed provider receipt under a separate keyed command. + pub async fn record_receipt( + &self, + token: &BearerToken, + idempotency_key: &str, + request: &RecordReceipt, + ) -> Result, PaymentClientError> { + validate_key(idempotency_key)?; + validate_collection_id(request.collection_id)?; + let builder = self + .http + .post(self.path_url(&[ + "collections", + &request.collection_id.to_string(), + "record-receipt", + ])?) + .header(AUTHORIZATION, token.authorization_header_value()) + .header(ACCEPT, JSON_MEDIA_TYPE) + .header(CONTENT_TYPE, JSON_MEDIA_TYPE) + .header(IDEMPOTENCY_KEY_HEADER, idempotency_key) + .json(request); + let answer: PaymentComplete = + self.send_keyed_json(builder, StatusCode::OK).await?; + answer + .value + .validate() + .map_err(|_| body_protocol(StatusCode::OK, Some(answer.trace_id.clone())))?; + if answer.value.collection_id != request.collection_id { + return Err(correlation_protocol(StatusCode::OK, Some(answer.trace_id))); + } + Ok(answer) + } + + fn collections_url(&self) -> Result { + self.path_url(&["collections"]) + } + + fn path_url(&self, suffix: &[&str]) -> Result { + let mut segments = vec!["v1", "payments", self.connection.as_str()]; + segments.extend_from_slice(suffix); + append_path_segments(self.base_url.as_url(), &segments) + .map_err(|_| PaymentClientError::configuration("the service base URL is not usable")) + } + + async fn json_answer( + &self, + request: reqwest::RequestBuilder, + expected: StatusCode, + ) -> Result, PaymentClientError> { + let response = self.send(request).await?; + self.json_response(response, expected).await + } + + async fn send_keyed_json( + &self, + request: reqwest::RequestBuilder, + expected: StatusCode, + ) -> Result, PaymentClientError> { + let request = &request; + retry_keyed_mutation(self.maximum_mutation_retries, || async move { + let Some(attempt) = request.try_clone() else { + return KeyedMutationAttempt::Settled(Err(PaymentClientError::invalid_request( + "the request could not be prepared for sending", + ))); + }; + let response = match self.send(attempt).await { + Ok(response) => response, + Err(error) => return keyed_attempt(Err(error), None, RetryAfter::Absent), + }; + let status = response.status(); + let retry_after = RetryAfter::from_headers(response.headers()); + keyed_attempt( + self.json_response(response, expected).await, + Some(status), + retry_after, + ) + }) + .await + } + + async fn json_response( + &self, + response: Response, + expected: StatusCode, + ) -> Result, PaymentClientError> { + let status = response.status(); + if status != expected { + return Err(self.problem_or_status(response).await); + } + let trace_id = response_trace(status, response.headers())?; + if !exact_media_type(response.headers(), JSON_MEDIA_TYPE) { + return Err(protocol( + status, + PaymentProtocolFailure::MediaType, + Some(trace_id), + )); + } + let body = read_bounded(response, self.maximum_response_bytes) + .await + .map_err(|error| PaymentClientError::Transport { + kind: read_failure_kind(&error), + })?; + let value = registry_platform_canonical_json::parse_json_strict(&body) + .ok() + .and_then(|value| serde_json::from_value(value).ok()) + .ok_or_else(|| body_protocol(status, Some(trace_id.clone())))?; + Ok(PaymentComplete { value, trace_id }) + } + + async fn send(&self, request: reqwest::RequestBuilder) -> Result { + let response = request + .send() + .await + .map_err(|error| PaymentClientError::Transport { + kind: send_failure_kind(&error), + })?; + validate_response_headers(response.headers()).map_err(|_| { + protocol( + response.status(), + PaymentProtocolFailure::HeaderBounds, + None, + ) + })?; + Ok(response) + } + + async fn problem_or_status(&self, response: Response) -> PaymentClientError { + let status = response.status(); + let trace = response_trace(status, response.headers()).ok(); + let retry_after = (status == StatusCode::TOO_MANY_REQUESTS) + .then(|| retry_after_seconds(response.headers(), MAXIMUM_RETRY_AFTER_SECONDS)) + .flatten(); + if !exact_media_type(response.headers(), PROBLEM_MEDIA_TYPE) { + return protocol(status, PaymentProtocolFailure::Status, trace); + } + let body = match read_bounded(response, MAXIMUM_PROBLEM_BYTES).await { + Ok(value) => value, + Err(error) => { + return PaymentClientError::Transport { + kind: read_failure_kind(&error), + } + } + }; + let document = registry_platform_canonical_json::parse_json_strict(&body) + .ok() + .and_then(|value| serde_json::from_value::(value).ok()); + match document { + Some(document) => domain_problem(status, trace, document, retry_after), + None => protocol(status, PaymentProtocolFailure::Problem, trace), + } + } +} + +fn validate_acceptance( + answer: &CollectionAccepted, + request: &RequestCollection, + status: StatusCode, + trace_id: &str, +) -> Result<(), PaymentClientError> { + answer + .validate() + .map_err(|_| body_protocol(status, Some(trace_id.to_owned())))?; + if answer.bill_id != request.bill_id || answer.bill_version != request.bill_version { + return Err(correlation_protocol(status, Some(trace_id.to_owned()))); + } + Ok(()) +} + +fn validate_collection_id(value: Uuid) -> Result<(), PaymentClientError> { + if value.is_nil() { + Err(PaymentClientError::invalid_request( + "the collection identifier is nil", + )) + } else { + Ok(()) + } +} + +fn validate_key(value: &str) -> Result<(), PaymentClientError> { + if (1..=128).contains(&value.len()) && value.bytes().all(|byte| (0x21..=0x7e).contains(&byte)) { + Ok(()) + } else { + Err(PaymentClientError::invalid_request( + "the idempotency key is not 1 to 128 visible ASCII characters", + )) + } +} + +fn keyed_attempt( + result: Result, + status: Option, + retry_after: RetryAfter, +) -> KeyedMutationAttempt { + classify_keyed_attempt( + result, + status, + retry_after, + PaymentClientError::is_outcome_unknown, + PaymentClientError::resend_may_settle, + ) +} + +fn domain_problem( + status: StatusCode, + trace_id: Option, + document: PaymentProblem, + retry_after: Option, +) -> PaymentClientError { + if document.status != status.as_u16() + || document.code.status() != status.as_u16() + || document.type_uri != document.code.type_uri() + || document.title != document.code.as_str() + { + return protocol(status, PaymentProtocolFailure::Problem, trace_id); + } + PaymentClientError::Problem { + status: status.as_u16(), + code: document.code, + trace_id, + retry_after_seconds: retry_after.filter(|_| status == StatusCode::TOO_MANY_REQUESTS), + } +} + +fn response_trace( + status: StatusCode, + headers: &reqwest::header::HeaderMap, +) -> Result { + response_trace_id(headers) + .map(|value| value.as_str().to_owned()) + .map_err(|_| protocol(status, PaymentProtocolFailure::TraceContext, None)) +} + +fn exact_media_type(headers: &reqwest::header::HeaderMap, expected: &str) -> bool { + let mut values = headers.get_all(CONTENT_TYPE).iter(); + matches!( + (values.next(), values.next()), + (Some(value), None) if value.as_bytes() == expected.as_bytes() + ) +} + +fn body_protocol(status: StatusCode, trace_id: Option) -> PaymentClientError { + protocol(status, PaymentProtocolFailure::Body, trace_id) +} + +fn correlation_protocol(status: StatusCode, trace_id: Option) -> PaymentClientError { + protocol(status, PaymentProtocolFailure::Correlation, trace_id) +} + +fn protocol( + status: StatusCode, + failure: PaymentProtocolFailure, + trace_id: Option, +) -> PaymentClientError { + PaymentClientError::Protocol { + status: status.as_u16(), + failure, + trace_id, + } +} diff --git a/crates/registry-payment-client/src/config.rs b/crates/registry-payment-client/src/config.rs new file mode 100644 index 0000000000..17d7f95cfc --- /dev/null +++ b/crates/registry-payment-client/src/config.rs @@ -0,0 +1,170 @@ +// SPDX-License-Identifier: Apache-2.0 + +use std::{fmt, time::Duration}; + +use registry_platform_httputil::client::{ + ServiceBaseUrl, DEFAULT_CONNECT_TIMEOUT, DEFAULT_MUTATION_RETRIES, DEFAULT_REQUEST_TIMEOUT, + MAXIMUM_MUTATION_RETRIES, MAXIMUM_TRUSTED_ROOT_CERTIFICATE_BUNDLE_BYTES, +}; +use url::Url; + +use crate::PaymentClientError; + +const DEFAULT_MAXIMUM_RESPONSE_BYTES: u64 = 1024 * 1024; +const MAXIMUM_RESPONSE_BYTES: u64 = 4 * 1024 * 1024; + +/// One Adapter origin and one operator-selected payment connection. +#[derive(Clone)] +pub struct PaymentClientConfig { + pub(crate) base_url: Url, + pub(crate) connection: String, + pub(crate) attempt_timeout: Duration, + pub(crate) connect_timeout: Duration, + pub(crate) maximum_response_bytes: u64, + pub(crate) user_agent: Option, + pub(crate) trusted_root_certificates: Option>, + pub(crate) maximum_mutation_retries: u8, +} + +impl PaymentClientConfig { + #[must_use] + pub fn new(base_url: Url, connection: impl Into) -> Self { + Self { + base_url, + connection: connection.into(), + attempt_timeout: DEFAULT_REQUEST_TIMEOUT, + connect_timeout: DEFAULT_CONNECT_TIMEOUT, + maximum_response_bytes: DEFAULT_MAXIMUM_RESPONSE_BYTES, + user_agent: None, + trusted_root_certificates: None, + maximum_mutation_retries: DEFAULT_MUTATION_RETRIES, + } + } + + #[must_use] + pub fn with_attempt_timeout(mut self, value: Duration) -> Self { + self.attempt_timeout = value; + self + } + + #[must_use] + pub fn with_connect_timeout(mut self, value: Duration) -> Self { + self.connect_timeout = value; + self + } + + #[must_use] + pub fn with_maximum_response_bytes(mut self, value: u64) -> Self { + self.maximum_response_bytes = value; + self + } + + #[must_use] + pub fn with_user_agent(mut self, value: impl Into) -> Self { + self.user_agent = Some(value.into()); + self + } + + #[must_use] + pub fn with_trusted_root_certificates(mut self, value: Vec) -> Self { + self.trusted_root_certificates = Some(value); + self + } + + /// Maximum identical same-key resends after an unknown keyed mutation. + /// Coordinator sets this to zero because its durable worker owns retries. + #[must_use] + pub fn with_maximum_mutation_retries(mut self, value: u8) -> Self { + self.maximum_mutation_retries = value; + self + } + + pub(crate) fn validate(&self) -> Result { + let base_url = ServiceBaseUrl::new(self.base_url.clone()) + .map_err(|_| PaymentClientError::configuration("the service base URL is not usable"))?; + if !valid_connection(&self.connection) { + return Err(PaymentClientError::configuration( + "the payment connection is not a local identifier", + )); + } + if self.attempt_timeout.is_zero() || self.connect_timeout.is_zero() { + return Err(PaymentClientError::configuration( + "client timeouts must be greater than zero", + )); + } + if self.maximum_response_bytes == 0 || self.maximum_response_bytes > MAXIMUM_RESPONSE_BYTES + { + return Err(PaymentClientError::configuration( + "the response body bound is outside the accepted range", + )); + } + if self + .trusted_root_certificates + .as_ref() + .is_some_and(|value| value.len() > MAXIMUM_TRUSTED_ROOT_CERTIFICATE_BUNDLE_BYTES) + { + return Err(PaymentClientError::configuration( + "the trusted root certificate bundle exceeds the accepted bound", + )); + } + if self.maximum_mutation_retries > MAXIMUM_MUTATION_RETRIES { + return Err(PaymentClientError::configuration( + "the mutation retry count exceeds the accepted bound", + )); + } + Ok(base_url) + } +} + +fn valid_connection(value: &str) -> bool { + (1..=64).contains(&value.len()) + && value.bytes().enumerate().all(|(index, byte)| { + byte.is_ascii_lowercase() + || byte.is_ascii_digit() + || (index > 0 && matches!(byte, b'-' | b'_')) + }) +} + +impl fmt::Debug for PaymentClientConfig { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter + .debug_struct("PaymentClientConfig") + .field("base_url", &"") + .field("connection", &"") + .field("attempt_timeout", &self.attempt_timeout) + .field("connect_timeout", &self.connect_timeout) + .field("maximum_response_bytes", &self.maximum_response_bytes) + .field("user_agent_present", &self.user_agent.is_some()) + .field( + "trusted_root_certificates_present", + &self.trusted_root_certificates.is_some(), + ) + .field("maximum_mutation_retries", &self.maximum_mutation_retries) + .finish_non_exhaustive() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn debug_withholds_destination_and_connection() { + let config = PaymentClientConfig::new( + Url::parse("https://secret.example.invalid/private").unwrap(), + "secret-connection", + ) + .with_user_agent("secret-agent") + .with_trusted_root_certificates(b"secret-certificate".to_vec()); + let debug = format!("{config:?}"); + for secret in [ + "secret.example", + "private", + "secret-connection", + "secret-agent", + "secret-certificate", + ] { + assert!(!debug.contains(secret)); + } + } +} diff --git a/crates/registry-payment-client/src/error.rs b/crates/registry-payment-client/src/error.rs new file mode 100644 index 0000000000..4b55f04f52 --- /dev/null +++ b/crates/registry-payment-client/src/error.rs @@ -0,0 +1,82 @@ +// SPDX-License-Identifier: Apache-2.0 + +use registry_payment_protocol::PaymentProblemCode; +use registry_platform_httputil::client::TransportKind; +use thiserror::Error; + +/// The response boundary that failed before a payment outcome could be used. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +#[non_exhaustive] +pub enum PaymentProtocolFailure { + HeaderBounds, + TraceContext, + Body, + MediaType, + Problem, + Status, + /// A valid payment document belonged to another command or collection. + Correlation, +} + +/// Every failure a payment capability call can produce. +#[derive(Debug, Error)] +#[non_exhaustive] +pub enum PaymentClientError { + #[error("payment client configuration is invalid: {reason}")] + Configuration { reason: &'static str }, + #[error("payment client request is invalid: {reason}")] + InvalidRequest { reason: &'static str }, + #[error("payment exchange did not complete: {kind}")] + Transport { kind: TransportKind }, + #[error("payment capability refused the request (HTTP {status}, problem {code:?})")] + Problem { + status: u16, + code: PaymentProblemCode, + trace_id: Option, + retry_after_seconds: Option, + }, + #[error("payment capability returned an invalid response")] + Protocol { + status: u16, + failure: PaymentProtocolFailure, + trace_id: Option, + }, +} + +impl PaymentClientError { + pub(crate) fn configuration(reason: &'static str) -> Self { + Self::Configuration { reason } + } + + pub(crate) fn invalid_request(reason: &'static str) -> Self { + Self::InvalidRequest { reason } + } + + /// Whether a keyed mutation might have taken effect despite this error. + #[must_use] + pub fn is_outcome_unknown(&self) -> bool { + match self { + Self::Configuration { .. } | Self::InvalidRequest { .. } => false, + Self::Transport { kind } => !matches!(kind, TransportKind::Connect), + Self::Problem { code, .. } => matches!( + code, + PaymentProblemCode::ReceiptUnresolved + | PaymentProblemCode::ReceiptExpired + | PaymentProblemCode::RecoveryHeld + | PaymentProblemCode::OutcomeUnknown + | PaymentProblemCode::ProviderProtocol + ), + Self::Protocol { status, .. } => !(400..500).contains(status), + } + } + + pub(crate) fn resend_may_settle(&self) -> bool { + match self { + Self::Transport { kind } => { + matches!(kind, TransportKind::Timeout | TransportKind::Exchange) + } + Self::Problem { status, .. } | Self::Protocol { status, .. } => *status >= 500, + Self::Configuration { .. } | Self::InvalidRequest { .. } => false, + } + } +} diff --git a/crates/registry-payment-client/src/lib.rs b/crates/registry-payment-client/src/lib.rs new file mode 100644 index 0000000000..04747289fd --- /dev/null +++ b/crates/registry-payment-client/src/lib.rs @@ -0,0 +1,25 @@ +// SPDX-License-Identifier: Apache-2.0 + +//! Bounded client for the Adapter payment collection capability. +//! +//! The client sends only the authoritative bill identifier and version a +//! service workflow supplies. Amount, provider state, and receipt evidence +//! are decoded from the Adapter's typed responses and validated before they +//! leave this crate. Reads are single exchanges. Keyed mutations may resend +//! only the exact request under the caller's original key, within the bounded +//! retry policy selected in [`PaymentClientConfig`]. + +#![deny(unsafe_code)] + +mod client; +mod config; +mod error; + +pub use client::{PaymentClient, PaymentComplete}; +pub use config::PaymentClientConfig; +pub use error::{PaymentClientError, PaymentProtocolFailure}; +pub use registry_payment_protocol::{ + CollectionAccepted, CollectionState, CollectionStatus, Money, PaymentProblem, + PaymentProblemCode, ReadCollection, RecordReceipt, RegistryReceipt, RequestCollection, +}; +pub use registry_platform_httputil::client::{BearerToken, TransportKind}; diff --git a/crates/registry-payment-client/tests/http_boundary.rs b/crates/registry-payment-client/tests/http_boundary.rs new file mode 100644 index 0000000000..8150aef5b9 --- /dev/null +++ b/crates/registry-payment-client/tests/http_boundary.rs @@ -0,0 +1,510 @@ +// SPDX-License-Identifier: Apache-2.0 + +use std::sync::{Arc, Mutex}; + +use axum::body::Bytes; +use axum::extract::State; +use axum::http::{HeaderMap, Method, StatusCode, Uri}; +use axum::response::IntoResponse; +use axum::routing::{get, post}; +use axum::Router; +use registry_payment_client::{ + BearerToken, CollectionState, PaymentClient, PaymentClientConfig, PaymentClientError, + PaymentProblemCode, PaymentProtocolFailure, ReadCollection, RecordReceipt, RequestCollection, +}; +use serde_json::json; +use url::Url; +use uuid::Uuid; + +const TRACEPARENT: &str = "00-0123456789abcdef0123456789abcdef-0123456789abcdef-01"; +const TRACE_ID: &str = "0123456789abcdef0123456789abcdef"; +const KEY: &str = "service-attempt-1"; + +#[derive(Clone, Debug)] +struct Captured { + method: Method, + uri: Uri, + headers: HeaderMap, + body: Bytes, +} + +#[derive(Clone)] +struct Fixture { + observations: Arc>>, + status: StatusCode, + content_type: &'static str, + body: String, +} + +async fn answer( + State(fixture): State, + method: Method, + uri: Uri, + headers: HeaderMap, + body: Bytes, +) -> impl IntoResponse { + fixture + .observations + .lock() + .expect("observations") + .push(Captured { + method, + uri, + headers, + body, + }); + ( + fixture.status, + [ + ("content-type", fixture.content_type), + ("traceparent", TRACEPARENT), + ], + fixture.body, + ) +} + +async fn serve(status: StatusCode, body: serde_json::Value) -> (PaymentClient, Fixture) { + serve_text(status, body.to_string()).await +} + +async fn serve_text(status: StatusCode, body: String) -> (PaymentClient, Fixture) { + serve_fixture(status, "application/json", body).await +} + +async fn serve_problem(status: StatusCode, code: PaymentProblemCode) -> (PaymentClient, Fixture) { + serve_fixture( + status, + "application/problem+json", + code_problem(code).to_string(), + ) + .await +} + +async fn serve_fixture( + status: StatusCode, + content_type: &'static str, + body: String, +) -> (PaymentClient, Fixture) { + let fixture = Fixture { + observations: Arc::new(Mutex::new(Vec::new())), + status, + content_type, + body, + }; + let app = Router::new() + .route( + "/adapter/v1/payments/bill-payments/collections", + post(answer), + ) + .route( + "/adapter/v1/payments/bill-payments/collections/receipt", + post(answer), + ) + .route( + "/adapter/v1/payments/bill-payments/collections/{collection_id}", + get(answer), + ) + .route( + "/adapter/v1/payments/bill-payments/collections/{collection_id}/record-receipt", + post(answer), + ) + .with_state(fixture.clone()); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0") + .await + .expect("fixture listener"); + let address = listener.local_addr().expect("fixture address"); + tokio::spawn(async move { + axum::serve(listener, app).await.expect("serve fixture"); + }); + let config = PaymentClientConfig::new( + Url::parse(&format!("http://{address}/adapter")).expect("fixture URL"), + "bill-payments", + ); + (PaymentClient::new(config).expect("payment client"), fixture) +} + +fn code_problem(code: PaymentProblemCode) -> serde_json::Value { + json!({ + "type": code.type_uri(), + "title": code.as_str(), + "status": code.status(), + "code": code + }) +} + +fn token() -> BearerToken { + BearerToken::new("synthetic-payment-token").expect("fixture token") +} + +fn acceptance(collection_id: Uuid, bill_id: Uuid) -> serde_json::Value { + json!({ + "collectionId": collection_id, + "billId": bill_id, + "billVersion": 3, + "bindingRevision": "sha256:synthetic-binding", + "simulation": true + }) +} + +fn status(collection_id: Uuid, bill_id: Uuid, state: &str) -> serde_json::Value { + let mut value = json!({ + "collectionId": collection_id, + "billId": bill_id, + "billVersion": 3, + "bindingRevision": "sha256:synthetic-binding", + "simulation": true, + "state": state, + "money": {"value": "25.00", "currency": "USD", "scale": 2} + }); + if state == "confirmed" { + value["providerReference"] = json!("SIM-confirmed-1"); + } + if state == "failed" { + value["failureReason"] = json!("payer-rejected"); + } + value +} + +#[tokio::test] +async fn collection_request_sends_only_authoritative_bill_identity() { + let collection_id = Uuid::new_v4(); + let bill_id = Uuid::new_v4(); + let (client, fixture) = serve(StatusCode::ACCEPTED, acceptance(collection_id, bill_id)).await; + let request = RequestCollection { + bill_id, + bill_version: 3, + }; + + let completed = client + .request_collection(&token(), KEY, &request) + .await + .expect("accepted collection"); + + assert_eq!(completed.trace_id, TRACE_ID); + assert_eq!(completed.value.collection_id, collection_id); + let observations = fixture.observations.lock().expect("observations"); + assert_eq!(observations.len(), 1); + let sent = &observations[0]; + assert_eq!(sent.method, Method::POST); + assert_eq!( + sent.uri.path(), + "/adapter/v1/payments/bill-payments/collections" + ); + assert_eq!(sent.headers["idempotency-key"], KEY); + assert_eq!( + serde_json::from_slice::(&sent.body).unwrap(), + json!({"billId": bill_id, "billVersion": 3}) + ); +} + +#[tokio::test] +async fn original_request_receipt_is_a_read_with_the_exact_key_and_body() { + let collection_id = Uuid::new_v4(); + let bill_id = Uuid::new_v4(); + let (client, fixture) = serve(StatusCode::OK, acceptance(collection_id, bill_id)).await; + let request = RequestCollection { + bill_id, + bill_version: 3, + }; + + client + .collection_receipt(&token(), KEY, &request) + .await + .expect("retained original acceptance"); + + let observations = fixture.observations.lock().expect("observations"); + assert_eq!(observations.len(), 1); + assert_eq!( + observations[0].uri.path(), + "/adapter/v1/payments/bill-payments/collections/receipt" + ); + assert_eq!(observations[0].headers["idempotency-key"], KEY); + assert_eq!( + serde_json::from_slice::(&observations[0].body).unwrap(), + json!({"billId": bill_id, "billVersion": 3}) + ); +} + +#[tokio::test] +async fn collection_reads_preserve_pending_unknown_and_confirmed_as_distinct_states() { + for (wire, expected) in [ + ("pending", CollectionState::Pending), + ("unknown", CollectionState::Unknown), + ("confirmed", CollectionState::Confirmed), + ] { + let collection_id = Uuid::new_v4(); + let bill_id = Uuid::new_v4(); + let (client, _) = serve(StatusCode::OK, status(collection_id, bill_id, wire)).await; + let completed = client + .read_collection(&token(), &ReadCollection { collection_id }) + .await + .expect("authoritative collection observation"); + assert_eq!(completed.value.state, expected); + } +} + +#[tokio::test] +async fn a_response_for_another_command_or_collection_is_a_protocol_failure() { + let collection_id = Uuid::new_v4(); + let requested_bill = Uuid::new_v4(); + let other_bill = Uuid::new_v4(); + let (client, _) = serve(StatusCode::ACCEPTED, acceptance(collection_id, other_bill)).await; + let error = client + .request_collection( + &token(), + KEY, + &RequestCollection { + bill_id: requested_bill, + bill_version: 3, + }, + ) + .await + .expect_err("another bill cannot settle this command"); + assert!(matches!( + &error, + PaymentClientError::Protocol { + failure: PaymentProtocolFailure::Correlation, + .. + } + )); + + let requested_collection = Uuid::new_v4(); + let (client, _) = serve( + StatusCode::OK, + status(collection_id, requested_bill, "pending"), + ) + .await; + let error = client + .read_collection( + &token(), + &ReadCollection { + collection_id: requested_collection, + }, + ) + .await + .expect_err("another collection cannot settle this observation"); + assert!(matches!( + &error, + PaymentClientError::Protocol { + failure: PaymentProtocolFailure::Correlation, + .. + } + )); +} + +#[tokio::test] +async fn malformed_or_duplicate_payment_evidence_fails_visibly() { + let collection_id = Uuid::new_v4(); + let bill_id = Uuid::new_v4(); + let malformed = status(collection_id, bill_id, "pending") + .to_string() + .replace("\"state\":\"pending\"", "\"state\":\"confirmed\""); + let (client, _) = serve_text(StatusCode::OK, malformed).await; + assert!(matches!( + client + .read_collection(&token(), &ReadCollection { collection_id }) + .await, + Err(PaymentClientError::Protocol { + failure: PaymentProtocolFailure::Body, + .. + }) + )); + + let duplicated = acceptance(collection_id, bill_id).to_string().replacen( + "{", + &format!("{{\"billId\":\"{bill_id}\","), + 1, + ); + let (client, _) = serve_text(StatusCode::ACCEPTED, duplicated).await; + assert!(matches!( + client + .request_collection( + &token(), + KEY, + &RequestCollection { + bill_id, + bill_version: 3 + } + ) + .await, + Err(PaymentClientError::Protocol { + failure: PaymentProtocolFailure::Body, + .. + }) + )); +} + +#[tokio::test] +async fn record_receipt_requires_confirmed_exactly_correlated_evidence() { + let collection_id = Uuid::new_v4(); + let bill_id = Uuid::new_v4(); + let receipt = json!({ + "collectionId": collection_id, + "billId": bill_id, + "billVersion": 3, + "bindingRevision": "sha256:synthetic-binding", + "simulation": true, + "money": {"value": "25.00", "currency": "USD", "scale": 2}, + "providerReference": "SIM-confirmed-1", + "receiptId": "bill-receipt-1" + }); + let (client, fixture) = serve(StatusCode::OK, receipt).await; + let completed = client + .record_receipt(&token(), KEY, &RecordReceipt { collection_id }) + .await + .expect("recorded receipt"); + assert_eq!(completed.value.collection_id, collection_id); + let observations = fixture.observations.lock().expect("observations"); + assert_eq!(observations[0].headers["idempotency-key"], KEY); + assert_eq!( + observations[0].uri.path(), + format!("/adapter/v1/payments/bill-payments/collections/{collection_id}/record-receipt") + ); + assert_eq!( + serde_json::from_slice::(&observations[0].body).unwrap(), + json!({"collectionId": collection_id}) + ); +} + +#[tokio::test] +async fn typed_problem_codes_preserve_authentication_and_uncertainty_semantics() { + let bill_id = Uuid::new_v4(); + let request = RequestCollection { + bill_id, + bill_version: 3, + }; + let (client, _) = serve_problem( + StatusCode::UNAUTHORIZED, + PaymentProblemCode::Unauthenticated, + ) + .await; + let error = client + .request_collection(&token(), KEY, &request) + .await + .expect_err("authentication failure"); + assert!(matches!( + &error, + PaymentClientError::Problem { + status: 401, + code: PaymentProblemCode::Unauthenticated, + .. + } + )); + assert!(!error.is_outcome_unknown()); + + let (client, _) = serve_problem( + StatusCode::SERVICE_UNAVAILABLE, + PaymentProblemCode::OutcomeUnknown, + ) + .await; + let error = client + .request_collection(&token(), KEY, &request) + .await + .expect_err("provider outcome stays unknown"); + assert!(matches!( + &error, + PaymentClientError::Problem { + code: PaymentProblemCode::OutcomeUnknown, + .. + } + )); + assert!(error.is_outcome_unknown()); + + let (client, _) = serve_problem( + StatusCode::BAD_GATEWAY, + PaymentProblemCode::ProviderProtocol, + ) + .await; + let error = client + .request_collection(&token(), KEY, &request) + .await + .expect_err("malformed provider acknowledgement stays unknown"); + assert!(matches!( + &error, + PaymentClientError::Problem { + code: PaymentProblemCode::ProviderProtocol, + .. + } + )); + assert!(error.is_outcome_unknown()); + + let (client, _) = serve_problem( + StatusCode::SERVICE_UNAVAILABLE, + PaymentProblemCode::Unavailable, + ) + .await; + let error = client + .request_collection(&token(), KEY, &request) + .await + .expect_err("explicit availability refusal"); + assert!(!error.is_outcome_unknown()); + + for code in [ + PaymentProblemCode::ReceiptUnresolved, + PaymentProblemCode::ReceiptExpired, + PaymentProblemCode::RecoveryHeld, + ] { + let error = PaymentClientError::Problem { + status: code.status(), + code, + trace_id: None, + retry_after_seconds: None, + }; + assert!(error.is_outcome_unknown(), "{}", code.as_str()); + } + + let malformed_authentication_refusal = PaymentClientError::Protocol { + status: 401, + failure: PaymentProtocolFailure::Problem, + trace_id: None, + }; + assert!(!malformed_authentication_refusal.is_outcome_unknown()); +} + +#[tokio::test] +async fn inconsistent_problem_document_is_a_protocol_failure() { + let bill_id = Uuid::new_v4(); + let body = json!({ + "type": PaymentProblemCode::Unavailable.type_uri(), + "title": PaymentProblemCode::Unavailable.as_str(), + "status": PaymentProblemCode::Unavailable.status(), + "code": PaymentProblemCode::Unavailable + }); + let (client, _) = serve_fixture( + StatusCode::BAD_GATEWAY, + "application/problem+json", + body.to_string(), + ) + .await; + let error = client + .request_collection( + &token(), + KEY, + &RequestCollection { + bill_id, + bill_version: 3, + }, + ) + .await + .expect_err("problem status mismatch"); + assert!(matches!( + &error, + PaymentClientError::Protocol { + status: 502, + failure: PaymentProtocolFailure::Problem, + .. + } + )); + assert!(error.is_outcome_unknown()); +} + +#[test] +fn connection_and_request_values_are_rejected_before_io() { + let base = Url::parse("https://adapter.example.invalid/root").unwrap(); + for connection in ["", "UPPER", "two/segments", ".", &"a".repeat(65)] { + assert!(matches!( + PaymentClient::new(PaymentClientConfig::new(base.clone(), connection)), + Err(PaymentClientError::Configuration { .. }) + )); + } +} diff --git a/crates/registry-payment-protocol/Cargo.toml b/crates/registry-payment-protocol/Cargo.toml new file mode 100644 index 0000000000..d6ea9111e8 --- /dev/null +++ b/crates/registry-payment-protocol/Cargo.toml @@ -0,0 +1,25 @@ +[package] +name = "registry-payment-protocol" +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +description = "Typed collection and receipt contract for the Adapter payment capability." +repository.workspace = true +publish = false + +[lints] +workspace = true + +[features] +schema = ["dep:schemars"] + +[dependencies] +schemars = { workspace = true, optional = true, features = ["uuid1"] } +serde.workspace = true +serde_json.workspace = true +thiserror.workspace = true +uuid = { workspace = true, features = ["serde"] } + +[dev-dependencies] +jsonschema.workspace = true diff --git a/crates/registry-payment-protocol/src/lib.rs b/crates/registry-payment-protocol/src/lib.rs new file mode 100644 index 0000000000..df6c66f9b0 --- /dev/null +++ b/crates/registry-payment-protocol/src/lib.rs @@ -0,0 +1,397 @@ +// SPDX-License-Identifier: Apache-2.0 +//! Runtime-free payment collection wire contract. Financial authority stays +//! with the configured provider and receipt authority with the owning registry. + +use serde::{Deserialize, Serialize}; +use uuid::Uuid; + +/// Maximum exact integer shared with JSON consumers and the synthetic provider. +pub const MAX_MINOR_UNITS: u64 = 9_007_199_254_740_991; + +/// Closed problem codes shared by the payment host and native clients. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +pub enum PaymentProblemCode { + #[serde(rename = "adapter.payment.authentication-required")] + Unauthenticated, + #[serde(rename = "adapter.payment.forbidden")] + Forbidden, + #[serde(rename = "adapter.payment.invalid-request")] + InvalidRequest, + #[serde(rename = "adapter.payment.conflict")] + Conflict, + #[serde(rename = "adapter.payment.not-found")] + NotFound, + #[serde(rename = "adapter.payment.receipt-unresolved")] + ReceiptUnresolved, + #[serde(rename = "adapter.payment.receipt-expired")] + ReceiptExpired, + #[serde(rename = "adapter.payment.recovery-held")] + RecoveryHeld, + #[serde(rename = "adapter.payment.outcome-unknown")] + OutcomeUnknown, + #[serde(rename = "adapter.payment.unavailable")] + Unavailable, + #[serde(rename = "adapter.payment.provider-protocol")] + ProviderProtocol, +} + +impl PaymentProblemCode { + #[must_use] + pub const fn as_str(self) -> &'static str { + match self { + Self::Unauthenticated => "adapter.payment.authentication-required", + Self::Forbidden => "adapter.payment.forbidden", + Self::InvalidRequest => "adapter.payment.invalid-request", + Self::Conflict => "adapter.payment.conflict", + Self::NotFound => "adapter.payment.not-found", + Self::ReceiptUnresolved => "adapter.payment.receipt-unresolved", + Self::ReceiptExpired => "adapter.payment.receipt-expired", + Self::RecoveryHeld => "adapter.payment.recovery-held", + Self::OutcomeUnknown => "adapter.payment.outcome-unknown", + Self::Unavailable => "adapter.payment.unavailable", + Self::ProviderProtocol => "adapter.payment.provider-protocol", + } + } + + #[must_use] + pub const fn status(self) -> u16 { + match self { + Self::Unauthenticated => 401, + Self::Forbidden => 403, + Self::InvalidRequest => 422, + Self::Conflict | Self::RecoveryHeld => 409, + Self::NotFound | Self::ReceiptUnresolved => 404, + Self::ReceiptExpired => 410, + Self::ProviderProtocol => 502, + Self::OutcomeUnknown | Self::Unavailable => 503, + } + } + + #[must_use] + pub fn type_uri(self) -> String { + format!("urn:registry:problem:{}", self.as_str()) + } +} + +/// Value-free problem details. Recovery outcomes are named even when the +/// transport completed: no uncertain result grants a new payment attempt. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct PaymentProblem { + #[serde(rename = "type")] + pub type_uri: String, + pub title: String, + pub status: u16, + pub code: PaymentProblemCode, +} + +impl From for PaymentProblem { + fn from(code: PaymentProblemCode) -> Self { + Self { + type_uri: code.type_uri(), + title: code.as_str().to_owned(), + status: code.status(), + code, + } + } +} + +/// A refused wire value. Messages never contain caller or provider values. +#[derive(Debug, thiserror::Error, PartialEq, Eq)] +#[error("payment contract: {0}")] +pub struct ContractError(&'static str); + +/// An exact positive decimal amount. Scale belongs to the configured currency +/// policy; wire amounts are strings so no binary floating-point rounding occurs. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct Money { + #[cfg_attr(feature = "schema", schemars(length(min = 1, max = 24), pattern(r"^(0|[1-9][0-9]*)(\.[0-9]{1,6})?$"), extend("not" = serde_json::json!({"pattern": r"^0(\.0{1,6})?$"}))))] + pub value: String, + #[cfg_attr(feature = "schema", schemars(pattern("^[A-Z]{3}$")))] + pub currency: String, + #[cfg_attr(feature = "schema", schemars(range(min = 0, max = 6)))] + pub scale: u8, +} + +impl Money { + /// Parse bounded decimal text into exact minor units. + /// + /// # Errors + /// Refuses noncanonical decimal syntax, excess precision, unsupported + /// currency/scale, zero, and amounts outside the portable integer range. + pub fn minor_units(&self) -> Result { + if self.scale > 6 + || self.currency.len() != 3 + || !self.currency.bytes().all(|b| b.is_ascii_uppercase()) + || self.value.len() > 24 + { + return Err(ContractError("invalid currency or precision")); + } + let (whole, fraction) = match self.value.split_once('.') { + Some((whole, fraction)) if !fraction.is_empty() => (whole, fraction), + Some(_) => return Err(ContractError("invalid decimal")), + None => (self.value.as_str(), ""), + }; + if whole.is_empty() + || (whole.len() > 1 && whole.starts_with('0')) + || !whole.bytes().all(|b| b.is_ascii_digit()) + || !fraction.bytes().all(|b| b.is_ascii_digit()) + || fraction.len() > usize::from(self.scale) + { + return Err(ContractError("invalid decimal")); + } + let factor = 10_u64.pow(u32::from(self.scale)); + let whole = whole + .parse::() + .map_err(|_| ContractError("amount overflow"))?; + let fractional = if fraction.is_empty() { + 0 + } else { + fraction + .parse::() + .map_err(|_| ContractError("invalid decimal"))? + * 10_u64.pow( + u32::from(self.scale) + - u32::try_from(fraction.len()) + .map_err(|_| ContractError("invalid decimal"))?, + ) + }; + let amount = whole + .checked_mul(factor) + .and_then(|v| v.checked_add(fractional)) + .filter(|v| *v > 0 && *v <= MAX_MINOR_UNITS) + .ok_or(ContractError("amount outside positive portable range"))?; + Ok(amount) + } + + /// Canonical decimal representation with the currency's configured scale. + /// + /// # Errors + /// Uses the same bounds as [`Self::minor_units`]. + pub fn canonical(&self) -> Result { + let minor = self.minor_units()?; + let factor = 10_u64.pow(u32::from(self.scale)); + let value = if self.scale == 0 { + minor.to_string() + } else { + format!( + "{}.{:0width$}", + minor / factor, + minor % factor, + width = usize::from(self.scale) + ) + }; + Ok(Self { + value, + currency: self.currency.clone(), + scale: self.scale, + }) + } +} + +/// Caller intent names a bill, never financial facts or provider routing. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct RequestCollection { + #[cfg_attr(feature = "schema", schemars(schema_with = "non_nil_uuid_schema"))] + pub bill_id: Uuid, + #[cfg_attr( + feature = "schema", + schemars(range(min = 1, max = 9_007_199_254_740_991_u64)) + )] + pub bill_version: u64, +} + +impl RequestCollection { + /// # Errors + /// Refuses a nil identifier or a nonportable/nonpositive bill version. + pub fn validate(&self) -> Result<(), ContractError> { + validate_bill(self.bill_id, self.bill_version) + } +} + +/// Input for an authoritative provider observation through the bound module. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct ReadCollection { + #[cfg_attr(feature = "schema", schemars(schema_with = "non_nil_uuid_schema"))] + pub collection_id: Uuid, +} + +/// Input for the restricted receipt operation. An identifier is a lookup key, +/// not receipt evidence and not authorization. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct RecordReceipt { + #[cfg_attr(feature = "schema", schemars(schema_with = "non_nil_uuid_schema"))] + pub collection_id: Uuid, +} + +/// Returned only after the provider's durable acceptance is established. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct CollectionAccepted { + #[cfg_attr(feature = "schema", schemars(schema_with = "non_nil_uuid_schema"))] + pub collection_id: Uuid, + #[cfg_attr(feature = "schema", schemars(schema_with = "non_nil_uuid_schema"))] + pub bill_id: Uuid, + #[cfg_attr( + feature = "schema", + schemars(range(min = 1, max = 9_007_199_254_740_991_u64)) + )] + pub bill_version: u64, + pub binding_revision: String, + pub simulation: bool, +} + +impl CollectionAccepted { + /// # Errors + /// Refuses missing or malformed durable identity. + pub fn validate(&self) -> Result<(), ContractError> { + validate_bill(self.bill_id, self.bill_version)?; + if self.collection_id.is_nil() || !bounded_text(&self.binding_revision, 128) { + return Err(ContractError("invalid collection binding")); + } + Ok(()) + } +} + +/// Provider state. Unknown is unresolved and never authorizes a replacement. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[serde(rename_all = "camelCase")] +pub enum CollectionState { + Accepted, + Pending, + Confirmed, + Failed, + Unknown, +} + +/// Verified observation, retaining the attempt's original binding and provenance. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct CollectionStatus { + #[cfg_attr(feature = "schema", schemars(schema_with = "non_nil_uuid_schema"))] + pub collection_id: Uuid, + #[cfg_attr(feature = "schema", schemars(schema_with = "non_nil_uuid_schema"))] + pub bill_id: Uuid, + #[cfg_attr( + feature = "schema", + schemars(range(min = 1, max = 9_007_199_254_740_991_u64)) + )] + pub bill_version: u64, + pub binding_revision: String, + pub simulation: bool, + pub state: CollectionState, + pub money: Money, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub provider_reference: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub failure_reason: Option, +} + +impl CollectionStatus { + #[must_use] + pub fn acceptance(&self) -> CollectionAccepted { + CollectionAccepted { + collection_id: self.collection_id, + bill_id: self.bill_id, + bill_version: self.bill_version, + binding_revision: self.binding_revision.clone(), + simulation: self.simulation, + } + } + + /// # Errors + /// Refuses inconsistent evidence/state, malformed identity or money. + pub fn validate(&self) -> Result<(), ContractError> { + self.acceptance().validate()?; + self.money.minor_units()?; + if (self.state == CollectionState::Confirmed) + != self + .provider_reference + .as_ref() + .is_some_and(|s| bounded_text(s, 128)) + || (self.state != CollectionState::Confirmed && self.provider_reference.is_some()) + || (self.state == CollectionState::Failed) + != self + .failure_reason + .as_ref() + .is_some_and(|s| bounded_text(s, 128)) + || (self.state != CollectionState::Failed && self.failure_reason.is_some()) + { + return Err(ContractError("state and evidence disagree")); + } + Ok(()) + } +} + +/// Exact receipt recorded by the service-owned registry Action. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct RegistryReceipt { + #[cfg_attr(feature = "schema", schemars(schema_with = "non_nil_uuid_schema"))] + pub collection_id: Uuid, + #[cfg_attr(feature = "schema", schemars(schema_with = "non_nil_uuid_schema"))] + pub bill_id: Uuid, + #[cfg_attr( + feature = "schema", + schemars(range(min = 1, max = 9_007_199_254_740_991_u64)) + )] + pub bill_version: u64, + pub binding_revision: String, + pub simulation: bool, + pub money: Money, + pub provider_reference: String, + pub receipt_id: String, +} + +impl RegistryReceipt { + /// # Errors + /// Refuses a receipt without exact binding, amount or reference. + pub fn validate(&self) -> Result<(), ContractError> { + let status = CollectionStatus { + collection_id: self.collection_id, + bill_id: self.bill_id, + bill_version: self.bill_version, + binding_revision: self.binding_revision.clone(), + simulation: self.simulation, + state: CollectionState::Confirmed, + money: self.money.clone(), + provider_reference: Some(self.provider_reference.clone()), + failure_reason: None, + }; + status.validate()?; + if !bounded_text(&self.receipt_id, 128) { + return Err(ContractError("invalid receipt identity")); + } + Ok(()) + } +} + +fn validate_bill(id: Uuid, version: u64) -> Result<(), ContractError> { + if id.is_nil() || version == 0 || version > MAX_MINOR_UNITS { + return Err(ContractError("invalid bill identity")); + } + Ok(()) +} + +fn bounded_text(value: &str, max: usize) -> bool { + !value.is_empty() && value.len() <= max && !value.chars().any(char::is_control) +} + +#[cfg(feature = "schema")] +fn non_nil_uuid_schema(_: &mut schemars::SchemaGenerator) -> schemars::Schema { + schemars::json_schema!({"type":"string","format":"uuid","not":{"const":"00000000-0000-0000-0000-000000000000"}}) +} diff --git a/crates/registry-payment-protocol/tests/contract.rs b/crates/registry-payment-protocol/tests/contract.rs new file mode 100644 index 0000000000..6ebdc8a986 --- /dev/null +++ b/crates/registry-payment-protocol/tests/contract.rs @@ -0,0 +1,143 @@ +// SPDX-License-Identifier: Apache-2.0 +use registry_payment_protocol::{CollectionState, CollectionStatus, Money, RequestCollection}; +use serde_json::json; +use uuid::Uuid; + +#[test] +fn collection_intent_names_only_the_authoritative_bill() { + let bill = Uuid::new_v4(); + let intent: RequestCollection = serde_json::from_value(json!({ + "billId": bill, "billVersion": 1 + })) + .unwrap(); + assert!(intent.validate().is_ok()); + for extra in [ + "amount", + "paid", + "providerUrl", + "tenant", + "biller", + "receiptAction", + ] { + let mut value = serde_json::to_value(&intent).unwrap(); + value[extra] = json!("caller-owned"); + assert!( + serde_json::from_value::(value).is_err(), + "{extra}" + ); + } + assert!(RequestCollection { + bill_id: bill, + bill_version: 0 + } + .validate() + .is_err()); +} + +#[test] +fn money_is_exact_positive_bounded_decimal_text() { + for (value, scale, expected) in [ + ("0.10", 2, 10), + ("1000000.01", 2, 100_000_001), + ("25.5", 2, 2550), + ("250", 0, 250), + ] { + let money = Money { + value: value.to_owned(), + currency: "USD".into(), + scale, + }; + assert_eq!(money.minor_units().unwrap(), expected); + assert!(serde_json::to_value(&money).unwrap()["value"].is_string()); + } + for value in [ + "0", + "-1", + "+1", + "1e2", + "NaN", + "0.001", + "01.00", + "1.", + ".1", + "90071992547409.92", + ] { + assert!( + Money { + value: value.into(), + currency: "USD".into(), + scale: 2 + } + .minor_units() + .is_err(), + "{value}" + ); + } + assert!( + serde_json::from_value::(json!({"value": 25.5, "currency": "USD", "scale": 2})) + .is_err() + ); +} + +#[test] +fn only_confirmed_collections_carry_payment_evidence() { + let mut status = CollectionStatus { + collection_id: Uuid::new_v4(), + bill_id: Uuid::new_v4(), + bill_version: 1, + binding_revision: "synthetic-v1".into(), + simulation: true, + state: CollectionState::Pending, + money: Money { + value: "25.00".into(), + currency: "USD".into(), + scale: 2, + }, + provider_reference: None, + failure_reason: None, + }; + assert!(status.validate().is_ok()); + status.provider_reference = Some("SIM-confirmed-1".into()); + assert!(status.validate().is_err()); + status.state = CollectionState::Confirmed; + assert!(status.validate().is_ok()); + status.provider_reference = Some("".into()); + assert!(status.validate().is_err()); + status.state = CollectionState::Failed; + status.provider_reference = None; + assert!(status.validate().is_err()); + status.failure_reason = Some("payer-rejected".into()); + assert!(status.validate().is_ok()); +} + +#[cfg(feature = "schema")] +#[test] +fn authored_bill_references_obey_the_runtime_identity_bounds() { + let schema = serde_json::to_value(schemars::schema_for!(RequestCollection)).unwrap(); + let compiled = jsonschema::JSONSchema::options() + .with_draft(jsonschema::Draft::Draft202012) + .compile(&schema) + .unwrap(); + let id = Uuid::new_v4(); + assert!(compiled.is_valid(&json!({"billId":id,"billVersion":1}))); + assert!(!compiled.is_valid(&json!({"billId":id,"billVersion":0}))); + assert!(!compiled.is_valid(&json!({"billId":id,"billVersion":9_007_199_254_740_992_u64}))); + assert!(!compiled.is_valid(&json!({"billId":Uuid::nil(),"billVersion":1}))); +} + +#[cfg(feature = "schema")] +#[test] +fn authored_money_refuses_zero_and_unsupported_fractional_precision() { + let schema = serde_json::to_value(schemars::schema_for!(Money)).unwrap(); + let compiled = jsonschema::JSONSchema::options() + .with_draft(jsonschema::Draft::Draft202012) + .compile(&schema) + .unwrap(); + assert!(compiled.is_valid(&json!({"value":"0.10","currency":"USD","scale":2}))); + for value in ["0", "0.0", "0.00", "0.000000", "0.0000001"] { + assert!( + !compiled.is_valid(&json!({"value":value,"currency":"USD","scale":6})), + "{value}" + ); + } +} diff --git a/crates/registry-payment-simulator-connector/Cargo.toml b/crates/registry-payment-simulator-connector/Cargo.toml new file mode 100644 index 0000000000..bb95ee8c8e --- /dev/null +++ b/crates/registry-payment-simulator-connector/Cargo.toml @@ -0,0 +1,29 @@ +[package] +name = "registry-payment-simulator-connector" +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +repository.workspace = true +description = "Bounded synthetic P2G payment provider connector." +publish = false + +[lints] +workspace = true + +[features] +schema = ["dep:schemars", "registry-platform-yaml/schema"] + +[dependencies] +registry-payment-protocol.workspace = true +registry-platform-httputil.workspace = true +registry-platform-yaml.workspace = true +serde.workspace = true +serde_json = { workspace = true, features = ["raw_value"] } +reqwest.workspace = true +url.workspace = true +thiserror.workspace = true +schemars = { workspace = true, optional = true } + +[dev-dependencies] +tokio.workspace = true diff --git a/crates/registry-payment-simulator-connector/src/lib.rs b/crates/registry-payment-simulator-connector/src/lib.rs new file mode 100644 index 0000000000..c3adb7c0ed --- /dev/null +++ b/crates/registry-payment-simulator-connector/src/lib.rs @@ -0,0 +1,428 @@ +// SPDX-License-Identifier: Apache-2.0 +//! The explicitly synthetic, local-only P2G profile. No live payment support. + +use registry_payment_protocol::{CollectionState, Money, MAX_MINOR_UNITS}; +use registry_platform_httputil::client::{build_client, BearerToken, OutboundOptions}; +use serde::{Deserialize, Serialize}; +use serde_json::value::RawValue; +use std::time::Duration; +use url::{Host, Url}; + +pub const CONNECTOR_VERSION: &str = "simulator-p2g/v1"; +const RESPONSE_LIMIT: u64 = 65_536; + +#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)] +pub enum ConnectorError { + #[error("adapter.payment.provider-configuration")] + Configuration, + #[error("adapter.payment.provider-command")] + Command, + #[error("adapter.payment.provider-protocol")] + Protocol, + #[error("adapter.payment.provider-unavailable")] + Unavailable, + #[error("adapter.payment.provider-outcome-unknown")] + Unknown, +} + +/// Operator-owned synthetic provider routing. Credentials are supplied only at +/// the send boundary and never belong to a persisted command or connection. +#[derive(Clone, Serialize, Deserialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct SimulatorConnection { + #[cfg_attr(feature = "schema", schemars(with = "registry_platform_yaml::Url"))] + pub base_url: String, + #[cfg_attr( + feature = "schema", + schemars(length(min = 1, max = 20), pattern(r"^[\x21-\x7e]+$")) + )] + pub tenant: String, + #[cfg_attr( + feature = "schema", + schemars(length(min = 1, max = 20), pattern(r"^[\x21-\x7e]+$")) + )] + pub biller: String, + #[cfg_attr( + feature = "schema", + schemars(length(min = 1, max = 10), pattern(r"^[\x21-\x7e]+$")) + )] + pub biller_name: String, + #[cfg_attr( + feature = "schema", + schemars(with = "registry_platform_yaml::Url", length(min = 1, max = 100)) + )] + pub callback_url: String, + #[cfg_attr( + feature = "schema", + schemars(length(min = 1, max = 10), pattern(r"^[\x21-\x7e]+$")) + )] + pub payer_fi_bic: String, +} + +impl SimulatorConnection { + pub fn validate(&self) -> Result<(), ConnectorError> { + registry_platform_yaml::Url::new(self.base_url.clone()) + .map_err(|_| ConnectorError::Configuration)?; + registry_platform_yaml::Url::new(self.callback_url.clone()) + .map_err(|_| ConnectorError::Configuration)?; + let url = Url::parse(&self.base_url).map_err(|_| ConnectorError::Configuration)?; + let loopback = match url.host() { + Some(Host::Ipv4(ip)) => ip.is_loopback(), + Some(Host::Ipv6(ip)) => ip.is_loopback(), + _ => false, + }; + if !loopback + || url.scheme() != "http" + || url.path() != "/" + || !url.username().is_empty() + || url.password().is_some() + || url.query().is_some() + || url.fragment().is_some() + || !text(&self.tenant, 20) + || !text(&self.biller, 20) + || !text(&self.biller_name, 10) + || !text(&self.payer_fi_bic, 10) + || !text(&self.callback_url, 100) + { + return Err(ConnectorError::Configuration); + } + let callback = Url::parse(&self.callback_url).map_err(|_| ConnectorError::Configuration)?; + if callback.scheme() != "https" + || !callback.username().is_empty() + || callback.password().is_some() + || callback.query().is_some() + || callback.fragment().is_some() + { + return Err(ConnectorError::Configuration); + } + Ok(()) + } +} + +/// Persisted identity and exact financial facts for one provider command. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct ProviderCommand { + pub request_id: String, + pub rtp_id: u64, + pub bill_id: String, + pub payer_address: String, + pub money: Money, +} + +impl ProviderCommand { + pub fn validate(&self) -> Result<(), ConnectorError> { + if !identifier(&self.request_id, 12) + || !identifier(&self.bill_id, 10) + || self.rtp_id == 0 + || self.rtp_id > MAX_MINOR_UNITS + || !text(&self.payer_address, 30) + { + return Err(ConnectorError::Command); + } + self.money + .minor_units() + .map_err(|_| ConnectorError::Command)?; + Ok(()) + } + + pub fn encode(&self, connection: &SimulatorConnection) -> Result, ConnectorError> { + self.validate()?; + connection.validate()?; + #[derive(Serialize)] + #[serde(rename_all = "camelCase")] + struct Request<'a> { + request_id: &'a str, + rtp_id: u64, + #[serde(rename = "billID")] + bill_id: &'a str, + request_type: &'static str, + payer_fi_details: Payer<'a>, + bill_details: Bill<'a>, + } + #[derive(Serialize)] + struct Payer<'a> { + #[serde(rename = "payerFIBIC")] + bic: &'a str, + #[serde(rename = "financialAddress")] + address: &'a str, + } + #[derive(Serialize)] + #[serde(rename_all = "camelCase")] + struct Bill<'a> { + biller_name: &'a str, + amount: Box, + currency: &'a str, + } + let money = self + .money + .canonical() + .map_err(|_| ConnectorError::Command)?; + let amount = RawValue::from_string(money.value).map_err(|_| ConnectorError::Command)?; + serde_json::to_vec(&Request { + request_id: &self.request_id, + rtp_id: self.rtp_id, + bill_id: &self.bill_id, + request_type: "00", + payer_fi_details: Payer { + bic: &connection.payer_fi_bic, + address: &self.payer_address, + }, + bill_details: Bill { + biller_name: &connection.biller_name, + amount, + currency: &self.money.currency, + }, + }) + .map_err(|_| ConnectorError::Command) + } + + pub fn decode_accepted(&self, bytes: &[u8]) -> Result { + #[derive(Deserialize)] + #[serde(rename_all = "camelCase", deny_unknown_fields)] + struct Accepted { + response_code: String, + response_description: String, + #[serde(rename = "requestID")] + request_id: String, + rtp_id: u64, + transfer_request_id: String, + } + if bytes.len() > RESPONSE_LIMIT as usize { + return Err(ConnectorError::Protocol); + } + let response: Accepted = + serde_json::from_slice(bytes).map_err(|_| ConnectorError::Protocol)?; + if response.response_code != "00" + || response.response_description.len() > 200 + || response.request_id != self.request_id + || response.rtp_id != self.rtp_id + || !identifier(&response.transfer_request_id, 50) + { + return Err(ConnectorError::Protocol); + } + Ok(response.transfer_request_id) + } + + pub fn decode_status( + &self, + transfer: &str, + bytes: &[u8], + ) -> Result { + #[derive(Deserialize)] + #[serde(rename_all = "camelCase", deny_unknown_fields)] + struct Status { + transfer_request_id: String, + #[serde(rename = "RequestId")] + request_id: String, + rtp_id: u64, + bill_id: String, + amount: Box, + currency: String, + request_status: String, + payment_status: String, + last_update_date: u64, + #[serde(rename = "PaymentReferenceID", default)] + reference: Option, + #[serde(default)] + failure_reason: Option, + } + self.validate()?; + if bytes.len() > RESPONSE_LIMIT as usize { + return Err(ConnectorError::Protocol); + } + let response: Status = + serde_json::from_slice(bytes).map_err(|_| ConnectorError::Protocol)?; + let amount = Money { + value: response.amount.get().to_owned(), + currency: response.currency, + scale: self.money.scale, + }; + if response.transfer_request_id != transfer + || response.request_id != self.request_id + || response.rtp_id != self.rtp_id + || response.bill_id != self.bill_id + || amount.currency != self.money.currency + || amount.minor_units().map_err(|_| ConnectorError::Protocol)? + != self + .money + .minor_units() + .map_err(|_| ConnectorError::Command)? + { + return Err(ConnectorError::Protocol); + } + let state = match ( + response.request_status.as_str(), + response.payment_status.as_str(), + ) { + ("PND" | "COM", "PENDING") + if response.reference.is_none() && response.failure_reason.is_none() => + { + CollectionState::Pending + } + ("COM", "PAID") + if response.failure_reason.is_none() + && response + .reference + .as_ref() + .is_some_and(|s| s.starts_with("SIM-") && identifier(s, 20)) => + { + CollectionState::Confirmed + } + ("RJC", "FAILED") + if response.reference.is_none() + && response.failure_reason.as_deref() == Some("payer-rejected") => + { + CollectionState::Failed + } + ("EXP", "EXPIRED") + if response.reference.is_none() + && response.failure_reason.as_deref() == Some("request-expired") => + { + CollectionState::Failed + } + _ => return Err(ConnectorError::Protocol), + }; + Ok(Observation { + state, + provider_reference: response.reference, + failure_reason: response.failure_reason, + observed_at: response.last_update_date, + }) + } +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct Observation { + pub state: CollectionState, + pub provider_reference: Option, + pub failure_reason: Option, + pub observed_at: u64, +} + +/// One bounded HTTP exchange per call. Retries belong to the durable host and +/// its saved command/window, never to this transport. +pub struct SimulatorClient { + connection: SimulatorConnection, + base_url: Url, + http: reqwest::Client, +} + +impl SimulatorClient { + pub fn new(connection: SimulatorConnection) -> Result { + connection.validate()?; + let base_url = + Url::parse(&connection.base_url).map_err(|_| ConnectorError::Configuration)?; + let http = build_client(OutboundOptions { + request_timeout: Duration::from_secs(15), + connect_timeout: Duration::from_secs(5), + user_agent: None, + trusted_root_certificates: None, + }) + .map_err(|_| ConnectorError::Configuration)?; + Ok(Self { + connection, + base_url, + http, + }) + } + + pub async fn submit( + &self, + command: &ProviderCommand, + token: &BearerToken, + ) -> Result { + let body = command.encode(&self.connection)?; + let response = self + .http + .post( + self.base_url + .join("rtpRequest") + .map_err(|_| ConnectorError::Configuration)?, + ) + .header("Authorization", token.authorization_header_value()) + .header("X-Platform-TenantId", &self.connection.tenant) + .header("X-billerId", &self.connection.biller) + .header("X-CorrelationID", &command.request_id) + .header("X-Callback-URL", &self.connection.callback_url) + .header("Content-Type", "application/json") + .body(body) + .send() + .await + .map_err(|_| ConnectorError::Unknown)?; + let bytes = checked_response(response, None) + .await + .map_err(|_| ConnectorError::Unknown)?; + // A malformed acknowledgement cannot undo a provider-side acceptance. + // Preserve uncertainty so the durable host keeps the original command. + command + .decode_accepted(&bytes) + .map_err(|_| ConnectorError::Unknown) + } + + pub async fn observe( + &self, + command: &ProviderCommand, + transfer: &str, + token: &BearerToken, + ) -> Result { + command.validate()?; + if !identifier(transfer, 50) { + return Err(ConnectorError::Command); + } + let response = self + .http + .get( + self.base_url + .join(&format!("transferRequests/{transfer}")) + .map_err(|_| ConnectorError::Configuration)?, + ) + .header("Authorization", token.authorization_header_value()) + .header("X-Platform-TenantId", &self.connection.tenant) + .header("X-billerId", &self.connection.biller) + .header("X-CorrelationID", &command.request_id) + .send() + .await + .map_err(|_| ConnectorError::Unavailable)?; + let bytes = checked_response(response, Some(&command.request_id)).await?; + command.decode_status(transfer, &bytes) + } +} + +async fn checked_response( + response: reqwest::Response, + correlation: Option<&str>, +) -> Result, ConnectorError> { + if response.status().as_u16() != 200 { + return Err(ConnectorError::Unavailable); + } + let header = |name: &str, expected: &str| { + let values: Vec<_> = response.headers().get_all(name).iter().collect(); + values.len() == 1 && values[0].to_str().is_ok_and(|s| s == expected) + }; + if !header("x-payment-simulator", "synthetic") + || correlation.is_some_and(|id| !header("x-correlationid", id)) + || response + .headers() + .get("content-type") + .and_then(|h| h.to_str().ok()) + .is_none_or(|s| s.split(';').next() != Some("application/json")) + { + return Err(ConnectorError::Protocol); + } + registry_platform_httputil::read_bounded(response, RESPONSE_LIMIT) + .await + .map_err(|_| ConnectorError::Unavailable) +} + +fn text(value: &str, max: usize) -> bool { + !value.is_empty() && value.len() <= max && value.bytes().all(|b| (0x21..=0x7e).contains(&b)) +} +fn identifier(value: &str, max: usize) -> bool { + text(value, max) + && value + .bytes() + .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_')) +} diff --git a/crates/registry-payment-simulator-connector/tests/profile.rs b/crates/registry-payment-simulator-connector/tests/profile.rs new file mode 100644 index 0000000000..de717eb8ae --- /dev/null +++ b/crates/registry-payment-simulator-connector/tests/profile.rs @@ -0,0 +1,169 @@ +// SPDX-License-Identifier: Apache-2.0 +use registry_payment_protocol::{CollectionState, Money}; +use registry_payment_simulator_connector::{ProviderCommand, SimulatorConnection}; + +fn connection() -> SimulatorConnection { + SimulatorConnection { + base_url: "http://127.0.0.1:8099/".into(), + tenant: "pilot".into(), + biller: "ministry".into(), + biller_name: "Ministry".into(), + callback_url: "https://programme.example.test/callback".into(), + payer_fi_bic: "SIMBANK".into(), + } +} +fn command() -> ProviderCommand { + ProviderCommand { + request_id: "request1".into(), + rtp_id: 1, + bill_id: "bill1".into(), + payer_address: "synthetic-payer".into(), + money: Money { + value: "25.50".into(), + currency: "USD".into(), + scale: 2, + }, + } +} +#[test] +fn synthetic_transport_cannot_point_to_live_or_named_remote_hosts() { + assert!(connection().validate().is_ok()); + for base in [ + "https://bank.example/", + "http://192.168.1.1/", + "http://user@127.0.0.1/", + "http://127.0.0.1/?token=secret", + " http://127.0.0.1/", + "http://127.0.0.1/\n", + "http://127.0.0.1/\\", + ] { + let mut config = connection(); + config.base_url = base.into(); + assert!(config.validate().is_err()); + } +} +#[test] +fn request_amount_is_an_exact_json_number_even_near_the_portable_bound() { + let mut cmd = command(); + cmd.money.value = "90071992547409.91".into(); + let body = String::from_utf8(cmd.encode(&connection()).unwrap()).unwrap(); + assert!(body.contains("\"amount\":90071992547409.91")); + assert!(!body.contains("\"amount\":\"")); +} +#[test] +fn com_pending_does_not_confirm_and_mismatched_facts_are_refused() { + let body = br#"{"transferRequestId":"tr1","RequestId":"request1","rtpId":1,"billId":"bill1","amount":25.50,"currency":"USD","requestStatus":"COM","paymentStatus":"PENDING","lastUpdateDate":1}"#; + let cmd = command(); + let observation = cmd.decode_status("tr1", body).unwrap(); + assert_eq!(observation.state, CollectionState::Pending); + for (from, to) in [ + ("25.50", "25.51"), + ("USD", "EUR"), + ("bill1", "bill2"), + ("request1", "request2"), + ("\"rtpId\":1", "\"rtpId\":2"), + ] { + let changed = String::from_utf8(body.to_vec()).unwrap().replace(from, to); + assert!(cmd.decode_status("tr1", changed.as_bytes()).is_err()); + } + assert!(cmd.decode_status("wrong-transfer", body).is_err()); +} +#[test] +fn confirmation_requires_synthetic_reference_and_exact_valid_pair() { + let body = br#"{"transferRequestId":"tr1","RequestId":"request1","rtpId":1,"billId":"bill1","amount":25.5,"currency":"USD","requestStatus":"COM","paymentStatus":"PAID","lastUpdateDate":1,"PaymentReferenceID":"SIM-1"}"#; + assert_eq!( + command().decode_status("tr1", body).unwrap().state, + CollectionState::Confirmed + ); + for (from, to) in [("SIM-1", "BANK-1"), ("COM", "PND"), ("25.5", "25.50001")] { + let changed = String::from_utf8(body.to_vec()).unwrap().replace(from, to); + assert!(command().decode_status("tr1", changed.as_bytes()).is_err()); + } +} + +#[tokio::test] +async fn an_invalid_acknowledgement_after_dispatch_is_an_unknown_outcome() { + use registry_payment_simulator_connector::{ConnectorError, SimulatorClient}; + use registry_platform_httputil::client::BearerToken; + use tokio::io::{AsyncReadExt, AsyncWriteExt}; + for body in [ + "not-json", + r#"{"responseCode":"00","responseDescription":"Accepted","requestID":"wrong","rtpId":1,"transferRequestId":"tr1"}"#, + r#"{"responseCode":"00","responseDescription":"Accepted","requestID":"request1","rtpId":2,"transferRequestId":"tr1"}"#, + r#"{"responseCode":"00","responseDescription":"Accepted","requestID":"request1","rtpId":1,"transferRequestId":"../wrong"}"#, + ] { + 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 { + let (mut socket, _) = listener.accept().await.unwrap(); + let mut request = vec![0; 4096]; + let count = socket.read(&mut request).await.unwrap(); + assert!(std::str::from_utf8(&request[..count]) + .unwrap() + .starts_with("POST /rtpRequest ")); + let response=format!("HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nX-Payment-Simulator: synthetic\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",body.len()); + socket.write_all(response.as_bytes()).await.unwrap(); + }); + let mut config = connection(); + config.base_url = format!("http://{address}/"); + let client = SimulatorClient::new(config).unwrap(); + assert_eq!( + client + .submit( + &command(), + &BearerToken::new("synthetic-test-token").unwrap() + ) + .await + .unwrap_err(), + ConnectorError::Unknown + ); + server.await.unwrap(); + } +} + +#[tokio::test] +async fn loopback_root_origins_with_or_without_a_slash_reach_the_same_provider_routes() { + use registry_payment_simulator_connector::SimulatorClient; + use registry_platform_httputil::client::BearerToken; + use tokio::io::{AsyncReadExt, AsyncWriteExt}; + for suffix in ["/", ""] { + 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 { + for (route, body) in [ + ( + "POST /rtpRequest ", + r#"{"responseCode":"00","responseDescription":"Accepted","requestID":"request1","rtpId":1,"transferRequestId":"tr1"}"#, + ), + ( + "GET /transferRequests/tr1 ", + r#"{"transferRequestId":"tr1","RequestId":"request1","rtpId":1,"billId":"bill1","amount":25.50,"currency":"USD","requestStatus":"COM","paymentStatus":"PENDING","lastUpdateDate":1}"#, + ), + ] { + let (mut socket, _) = listener.accept().await.unwrap(); + let mut request = vec![0; 4096]; + let count = socket.read(&mut request).await.unwrap(); + assert!(std::str::from_utf8(&request[..count]) + .unwrap() + .starts_with(route)); + let response = format!("HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nX-Payment-Simulator: synthetic\r\nX-CorrelationID: request1\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", body.len()); + socket.write_all(response.as_bytes()).await.unwrap(); + } + }); + let mut config = connection(); + config.base_url = format!("http://{address}{suffix}"); + let client = SimulatorClient::new(config).unwrap(); + let token = BearerToken::new("canary-synthetic-provider-token").unwrap(); + let transfer = client.submit(&command(), &token).await.unwrap(); + assert_eq!(transfer, "tr1"); + assert_eq!( + client + .observe(&command(), &transfer, &token) + .await + .unwrap() + .state, + CollectionState::Pending + ); + server.await.unwrap(); + } +} diff --git a/products/adapter/AGENTS.md b/products/adapter/AGENTS.md index 505e8907a9..686f0dcec0 100644 --- a/products/adapter/AGENTS.md +++ b/products/adapter/AGENTS.md @@ -18,7 +18,9 @@ product or any `registry-adapter*` crate. |---|---| | `crates/registry-adapter-core` | Source-neutral Adapter model, wire DTOs, `adapter.*` problem codes, and pure authoring checks; no I/O (it depends on `registry-platform-httputil` only for its pure header predicates and bounds) | | `crates/registry-adapter-engine` | Bounded route engine, components, compilation and replay shared by facade, jobs and Evidence; no listener or PostgreSQL client | -| `crates/registry-adapter` | Governed facade, caller security, audit journal and idempotency custody over the shared engine | +| `crates/registry-adapter` | Governed facade, caller security, audit journal and idempotency custody over the shared engine; optional typed payment host and PostgreSQL attempts | +| `crates/registry-payment-protocol` | Runtime-free typed collection, observation, receipt and problem contract | +| `crates/registry-payment-simulator-connector` | Standalone synthetic P2G wire and transport; no product clients, stores or runtimes | | `crates/registry-adapterctl` | Adapter authoring and operator tooling and the `adapterctl` binary | | `crates/registry-adapter-job` | The ingestion-job host and the `adapter-job` binary: the item table, the pass, interval and authenticated hook triggers, and the destination seam; it keeps identity and position only, never payloads | | `crates/registry-adapter-connectors` | BReg connector over `registry-breg-client`, behind the job host's off-by-default `direct-breg` feature. Engine and facade cannot reach it; the dependency gate names the exact permitted path | @@ -38,12 +40,18 @@ shared by facade, jobs and Evidence through named execution profiles. Evidence links only Adapter core and engine; its authorization, assertion meaning, signing and access/disclosure audit remain Evidence-owned. Shared platform changes preserve each consuming product's policy and have consumer proof. -`[ingestion]` The one exception to "never another product's protocol +`[ingestion]` The ingestion exception to "never another product's protocol types" is the connector crate above: it reaches `registry-breg-client` only, behind a feature, never a product runtime, CLI, or database crate, and `products/adapter/scripts/check_dependency_direction.py` enforces that boundary mechanically. No facade binary and -neither engine crate links the connector crate or any product client. +neither engine crate links the ingestion connector crate. +The payment-host exception is `registry-adapter::payments`: the host links +the payment protocol, standalone synthetic provider connector, and public +`registry-breg-client` for restricted bill and receipt Actions. Its authoring +tool may inherit that host closure. Core and engine remain source-neutral; +neither gains payment types, stores or product clients. No product runtime, +tooling, database crate or Coordinator client enters the payment host closure. ## Gates diff --git a/products/adapter/CHANGELOG.md b/products/adapter/CHANGELOG.md index 76120f5cf9..5509469042 100644 --- a/products/adapter/CHANGELOG.md +++ b/products/adapter/CHANGELOG.md @@ -104,6 +104,19 @@ - A reviewed projection operation serves BReg's read-only external views. See the BReg changelog and the [external projections pack](examples/external-projections/README.md). +- `adapter serve --payments-config` hosts typed synthetic payment collection + operations on the shared listener and PostgreSQL store, including without + a record project. Connections bind institution/service scope, admitted + callers, provider tenant/biller and separate BReg reporting credentials. + Retained attempts preserve their original binding and exact commands across + response loss and restart. Only a confirmed, correlated receipt can mark + the authoritative bill paid. One attempt is permitted per bill version, + including after definitive failure; live providers, replacement attempts, + refunds and settlement are outside this slice. +- `adapterctl payments check` validates connections offline and + `adapterctl payments contract` exports their typed HTTP contract. Generated + schemas, a native Coordinator workflow, the restricted BReg fee fixture, + and a joined native acceptance runner accompany the payment host. ## 0.46.0 - 2026-11-08 diff --git a/products/adapter/README.md b/products/adapter/README.md index c718f01a63..484a8cd6d0 100644 --- a/products/adapter/README.md +++ b/products/adapter/README.md @@ -9,6 +9,12 @@ reviewed projection either to a BReg Action or to a Coordinator workflow. The facade holds no records; the job stores item identity and progress, never source payloads. The institution's registry remains the system of record. +The optional [typed payment host](examples/payment-collections/README.md) +shares the listener and PostgreSQL infrastructure while keeping payment +attempts outside generic record routes. Coordinator uses dedicated payment +steps; operator configuration binds provider tenant, biller and restricted +registry Actions. The initial connector is synthetic and local-only. + Source-system knowledge and deployment mappings live in reviewed configuration. A reviewed, versioned pack declares a source's endpoints and route templates, with field mapping in Rhai scripts beside it; a project binds a pack to a profile's operations; a diff --git a/products/adapter/examples/payment-collections/CONTRACT.md b/products/adapter/examples/payment-collections/CONTRACT.md new file mode 100644 index 0000000000..c9e4bd467c --- /dev/null +++ b/products/adapter/examples/payment-collections/CONTRACT.md @@ -0,0 +1,95 @@ +# First P2G payment contract + +The in-source `payments/v1` host contract supports synthetic fee collection, +exact receipt reporting and payment-gated service issuance. It does **not** +claim conformance to `payments-capability-v1` in Registry Service Composition, +or general GovStack Payments conformance. The simulator's wire profile is +separate from this service-facing contract. + +BReg owns the bill, frozen tariff and single-use issuance gate. Adapter owns +provider identifiers, durable attempts, original connection snapshots and +prepared bind/receipt commands in PostgreSQL. Coordinator owns workflow state +and bounded observation through the named `collection` completion. Provider +acceptance, payment confirmation and a recorded registry receipt are distinct +facts. + +## HTTP and native operations + +All routes require an admitted OIDC client and the connection's configured +scope. Retained attempts also require their original issuer, client and +subject, and the current connection's institution/service scope. Caller-supplied +amounts, provider outcomes, tenant/biller routing and Action names are refused. + +| Operation | HTTP route below `/v1/payments/{connection}` | Input | Success | +| --- | --- | --- | --- | +| `payments.request-collection/v1` | `POST /collections` | `billId`, positive `billVersion`; `Idempotency-Key` header | 202, durable collection identity after provider acceptance | +| Recovery lookup | `POST /collections/receipt` | Original request and key | 200 if acceptance is known; lookup never dispatches | +| `payments.read-collection/v1` | `GET /collections/{collectionId}` | Collection identifier | 200 with exact identity, money and current validated state | +| `payments.record-receipt/v1` | `POST /collections/{collectionId}/record-receipt` | Matching `collectionId`; `Idempotency-Key` header | 200 only after exact BReg receipt readback | + +`adapterctl payments contract FILE` exports these routes and the generated +wire schemas. `registry-payment-protocol` owns the DTOs and the bounded problem +vocabulary; `registry-payment-client` validates responses before exposing them +to Coordinator. JSON Schema checks structural bounds. Runtime checks also +enforce currency scale, portable integer limits, exact correlation and evidence +consistency. + +## Relationship to payments-capability-v1 + +The earlier [composition capability contract](https://github.com/registrystack/registry-service-composition/blob/main/docs/capabilities/payments.md) +contains 31 numbered rules. This table records the first slice's behavior and +differences, rather than certifying that contract. Source and focused regression +coverage are not a substitute for a joined native runtime acceptance run. + +| Rule | First slice | +| --- | --- | +| 1 | Exact decimal-string `Money` with currency and scale. | +| 2 | Integer minor-unit conversion and exact JSON-number serialization, without binary floating point. | +| 3 | Positive amounts, configured scale, decimal precision and portable integer bounds are enforced. | +| 4 | Bill currency/scale must match the operator's connection policy. The fixture freezes a service-owned synthetic tariff; it does not model a tariff registry. | +| 5 | All bindings must declare `simulation: true`. No live or XTS-specific mode exists. | +| 6 | Source bill UUID/version remain unchanged. Bounded provider identifiers are derived separately. | +| 7 | Provider identifiers live in Adapter PostgreSQL. BReg stores the attempt ID and binding revision, not the provider's wire identifiers. | +| 8 | Domain-separated SHA-256 binds bounded provider identifiers to the full immutable bill and provider origin/producer/tenant/biller. Disjoint digest portions supply request, RTP and bill identifiers independently of the Adapter database. Source UUIDs are never truncated. | +| 9 | Provider transfer identity is durably stored before acceptance is exposed. | +| 10 | Confirmation requires a bounded `SIM-` reference. The connector does not independently enforce reference inequality with the transfer identifier. | +| 11 | One attempt per bill version, permanently, including after failure. | +| 12 | Confirmed and failed observations are terminal. Provider expiry maps to `failed` with `request-expired`, rather than a separate state. | +| 13 | Reissue/replacement after decline or expiry is outside this slice. No release/rebind Action is provided. | +| 14 | The permanent reservation is stronger than an active-attempt-only limit. BReg also binds the attempt atomically before dispatch. | +| 15 | Paid/issued bills cannot start a collection. The fixture also prevents another bill for the same institution/service/request. | +| 16 | Full bill/provider/connection snapshots and exact prepared binding are persisted before dispatch; binding readback must match. | +| 17 | Recovery reuses the original exact command only within its original declared replay window. Replay is never unconditional. | +| 18 | Missing acceptance remains unknown; elapsed replay windows remain held. Operator recovery has no automated replacement operation or configurable named-owner field. | +| 19 | Replays retain the original command. Provider conflicts or invalid acknowledgements remain uncertain and never authorize a fresh attempt. | +| 20 | Reads use the persisted transfer identity and store each validated observation before returning it. | +| 21 | Coordinator owns the observation deadline/budget. Adapter has no autonomous polling loop. A workflow timeout cannot issue a receipt. | +| 22 | Timeouts never manufacture a failed or expired payment. | +| 23 | Invalid or contradictory status responses return a protocol error and retain the last valid observation. They do not overwrite it with a fabricated terminal state. | +| 24 | Lost receipt acknowledgements recover through the original prepared command/key or exact matching bill, binding, money, reference and receipt digest. A paid flag alone is insufficient. | +| 25 | No failure Action is called. Pending, failed and unknown states stay in the Adapter journal, and the BReg bill remains bound/unpaid. | +| 26 | Only the restricted BReg receipt Action can mark the bill paid. The Adapter cannot waive it or change its frozen amount. | +| 27 | Confirmation checks all source/provider correlations, exact amount/currency and the synthetic payment reference. | +| 28 | Provider `COM/PENDING` remains pending. | +| 29 | `simulation: false` and non-loopback simulator origins are refused. The host does not read composition environment labels. | +| 30 | Provider and BReg credentials come from secret references. Persisted attempts retain references and logical identities, never credential values. | +| 31 | The fixture grants the Adapter only exact bind/receipt Actions and bill readback; it grants Coordinator no reporting Action. There is no failure Action in this slice. | + +Attempts and command receipts currently have no automatic expiry. Original +provider/registry origins, tenant, biller and credential references remain +attached to retained attempts when configuration changes. Operators must keep +those bindings and protected database backups available for recovery. A new +configuration cannot redirect an existing financial command. + +The provider request identifier has 72 digest bits, the wire bill identifier +has 56, and the positive RTP identifier has 52, within their respective wire +bounds. The provider must reject a reused request identifier with a different +body. The host verifies the complete saved command against its bill and +provider namespace before use; a partial identifier match never establishes +payment of another bill. + +This unreleased slice does not migrate the earlier sequence-based development +snapshots. They fail integrity validation and stay held, with their original +commands intact. Preserve such disposable development databases and their +matching build for inspection; run the current synthetic fixture in a fresh +database. Do not rewrite or resend retained attempts under derived identifiers. diff --git a/products/adapter/examples/payment-collections/README.md b/products/adapter/examples/payment-collections/README.md new file mode 100644 index 0000000000..2d6b067c0e --- /dev/null +++ b/products/adapter/examples/payment-collections/README.md @@ -0,0 +1,181 @@ +# Synthetic payment collection + +This source example combines the Adapter payment host with the maintained +[service-fee BReg project](../../../breg/examples/payment-fee-issuance/README.md). +The first provider is the repository's [P2G simulator](../../../../tools/payment-simulator/README.md). +It does not accept real payments or claim general GovStack Payments conformance. +The [contract and capability comparison](CONTRACT.md) names the exact HTTP +surface, ownership and differences from the earlier composition capability. + +A service creates the authoritative bill. The Coordinator workflow then uses +native payment operations: + +1. `payments.request-collection/v1` supplies `billId` and `billVersion` and + waits for the named `collection` completion. +2. `payments.read-collection/v1` can explicitly read the collection when + needed. Reads never start a payment or record a receipt. +3. `payments.record-receipt/v1` supplies only `collectionId`. The Adapter + derives and reports the exact confirmed receipt to the restricted BReg + Action. The service can then invoke `issue-paid-service` with the bill, + expected version, request, saved receipt and issuance identifiers. + +The request's named completion polls the provider through the Adapter, so an +ordinary workflow does not need to author its own polling loop. See the +[Coordinator operation catalog](../../../coordinator/generated/operations/README.md) +and [connection setup](../../../coordinator/DEPLOYMENT.md). + +## Bind the connection + +Copy `payments.example.yaml` and `runtime.example.yaml` into the operator's +configuration directory. `payments.yaml` binds the service to one provider +tenant/biller and one registry. Its caller policy must agree with the shared +runtime's OIDC issuer, audience and admitted clients. Its currency and scale +must agree with the authoritative bill. + +The provider token identifies the synthetic producer. The BReg token belongs +to `payment-adapter`, with `registry:payment-attempt:bind` and +`registry:payment-receipt:report` scopes and `payment-processing` purpose. +Keep that credential separate from Coordinator and citizens. The example +names secret references, never token values. The runtime supervisor must +renew externally supplied bearer tokens at those references; the host +resolves them on each exchange. Rotation must preserve the original logical +provider or registry identity. + +Build matching `adapter` and `adapterctl` binaries from this checkout, using +the repository's external Cargo target directory. Check the configuration +without resolving credentials or contacting a provider: + +```sh +adapterctl payments check /absolute/path/payments.yaml +adapterctl --format json payments contract /absolute/path/payments.yaml +``` + +Start the payment-only host with the configured PostgreSQL and OIDC service: + +```sh +adapter serve --runtime-config /absolute/path/runtime.yaml \ + --payments-config /absolute/path/payments.yaml +``` + +Pass the same `--payments-config` beside an existing `--project` to share a +record facade's listener and database. Payment routes have their own fixed +contract; they do not require a record profile or a generic HTTP workflow +step. `adapter effective-contract` exports the record-facade contract; +`adapterctl payments contract` exports the payment module's routes and schemas. + +## Grant the payment tables + +The configured migration role creates the payment tables at startup. If the +runtime role differs, grant it the following privileges after migration and +restart the host. Startup refuses missing grants before binding the listener. +Replace `payment_adapter_runtime` with the operator's runtime role. + +```sql +GRANT SELECT, INSERT, UPDATE ON adapter_payment_attempts TO payment_adapter_runtime; +GRANT SELECT, INSERT ON adapter_payment_commands, adapter_payment_events TO payment_adapter_runtime; +GRANT USAGE, SELECT ON SEQUENCE adapter_payment_events_sequence_seq + TO payment_adapter_runtime; +``` + +Production builds retain the shared Adapter PostgreSQL TLS requirement. The +`postgres-test` feature permits explicitly configured plaintext only for +isolated test databases. + +## Recovery and current limits + +Before dispatch, the host reserves the attempt and verifies BReg's atomic +bill binding. Duplicate workflow runs with different command keys reuse the +same attempt for that bill version. A changed request under a spent key is +refused. COM/PENDING and unknown observations never release the service. + +A lost provider response retains the original exact command, tenant, biller +and connection revision. Recovery may resend only inside the original replay +window. After that window, the attempt remains held. A changed connection +config applies to new attempts; it does not redirect retained ones. + +The host persists bind and receipt commands before sending them. A lost BReg +acknowledgement is recovered through the same command/key or exact bill and +receipt readback. A paid flag alone is insufficient. Every lookup remains +bound to the original authenticated caller and the currently permitted +connection/service scope. + +This slice permits one attempt per bill version, including after a definitive +failure. There is no replacement-attempt operation, refund, settlement, +callback handler or live-provider connector. Attempts and command receipts +have no automatic expiry; they contain restricted bill/payer facts needed for +recovery and require protected database storage and backup. Generic facade +retention does not erase these records. + +The focused `payment_service` PostgreSQL tests exercise recovery using +controlled registry/provider ports and a real database. They are separate +from the actual BReg fixture journey and a joined runtime acceptance run; +passing those focused tests alone does not establish a live integration. + +## Run the native acceptance + +Use an owned loopback PostgreSQL cluster with TLS and a trusted CA, normal +`breg`, `bregctl`, `adapter`, `adapterctl`, `coordinator`, and `coordinatorctl` +binaries from the same checkout, Node, `psql`, and the simulator's locked `uv` +environment. Build into the repository's required external Cargo target. +The native run does not use `postgres-test` or bypass package activation. + +First run the [BReg fixture helper](../../../breg/examples/payment-fee-issuance/README.md#native-acceptance-and-runtime-handoff) +with its documented binary, database, CA, and private-directory inputs. Set +`PAYMENT_FEE_KEEP_RUNNING=1` in a retained terminal or supervised session, +and run the joined acceptance separately while BReg stays live. Retain its +`handoff.json`. Store the +loopback PostgreSQL admin URL in a private file readable only by the operator. +Then, from the repository root: + +```sh +node products/adapter/scripts/test-payment-native.mjs \ + --fixture /absolute/private/breg-run/handoff.json \ + --bin-dir /absolute/external/cargo-target/debug \ + --simulator-bin /absolute/private/simulator-venv/bin/payment-simulator \ + --admin-url-file /absolute/private/postgres-admin-url \ + --ca-file /absolute/private/postgres-ca.crt \ + --build-record /absolute/private/payment-build-record.json \ + --state-dir /absolute/private/new-payment-acceptance-run +``` + +The state directory must be new. The runner creates fresh UTF8 databases and +separate migration/runtime roles, starts the actual simulator, Adapter and +Coordinator, and uses loopback relays to lose selected responses after the +upstream effect has happened. It checks original-binding recovery after +configuration changes, exact amount correlation, caller isolation, unpaid +issuance refusal, one receipt and one issuance, and the failed-attempt hold. +It also exercises Coordinator's native `reconcile`, named completion, and +`retry-same` against those processes, and verifies that extending configuration +cannot reopen an expired attempt's original replay window. +Two further fresh Adapter databases use the same provider namespace, payer +and amount for distinct BReg bills. The runner requires two provider requests, +distinct transfers and references, and separate authoritative receipts. + +The private build record is an operator-supplied attestation, not independent +source-to-binary verification. It must contain a `binaries` object with `adapter`, +`adapterctl`, `coordinator`, and `coordinatorctl` entries, each with its actual +`sha256`. Include the source revision/content identity, Cargo command, features, +profile and toolchain used for each build; Cargo JSON compiler-artifact output +provides the actual profile and enabled features. Put the common build command +in `command`, the compiler details in `toolchain`, and `head` plus `patchSha256` +under `source`; each binary entry also records its `features` and `profile`. +Stage new source files before +running. The runner retains the current Git base, binary patch and per-file +source hashes, including the harness and simulator, for dirty-tree provenance. +It verifies the simulator's imported Python package content and retains the +BReg fixture's binary hashes and declared feature profiles separately. The +run-time source snapshot does not establish the build source of preserved +fixture binaries. + +The runner stops its own services on exit. The BReg process remains owned by +its fixture launcher. Databases, roles, simulator state and private evidence +are retained for inspection. Only after all behavior and shutdown assertions +pass does the runner write `acceptance.json` with checks, source and binary +identities, command hashes and the synthetic provider ledger. +Tokens and database passwords are not included in that report. Logs and +credential files remain private under the supplied directory. This is a +synthetic integration proof. PostgreSQL uses TLS; service HTTP is numeric +loopback. It does not establish production transport, live-provider behavior +or full GovStack Payments conformance. +`progress.json` also preserves completed checks and safe command metadata +when a run fails, after the runner attempts to stop all its owned processes. diff --git a/products/adapter/examples/payment-collections/payments.example.yaml b/products/adapter/examples/payment-collections/payments.example.yaml new file mode 100644 index 0000000000..e29c67104f --- /dev/null +++ b/products/adapter/examples/payment-collections/payments.example.yaml @@ -0,0 +1,36 @@ +# yaml-language-server: $schema=https://id.registrystack.org/schemas/adapter/payments/payments.v1alpha1.schema.json +apiVersion: id.registrystack.org/formats/adapter/payments/v1alpha1 +kind: AdapterPayments +connections: + - id: licence-fees + institutionId: institution-a + serviceId: licence-issuance + allowedClients: [coordinator-payments] + requiredScope: payments:collect + binding: + simulation: true + currency: USD + currencyScale: 2 + providerCredentialRef: secret:env/PAYMENT_SIMULATOR_TOKEN + providerCredentialIdentity: registry + # The simulator retains commands in its database. The host permits + # recovery sends for only this bounded window after the first dispatch. + replayWindowSeconds: 3600 + provider: + baseUrl: http://127.0.0.1:8099/ + tenant: pilot + biller: ministry + billerName: Ministry + callbackUrl: https://programme.example.test/callback + payerFiBic: SIMBANK + registry: + baseUrl: http://127.0.0.1:8080/ + recordType: service-fee-bill + recordRoute: service-fee-bills + readProfile: payment-adapter-reporter + bindProfile: payment-adapter-binder + receiptProfile: payment-adapter-reporter + bindAction: bind-payment-attempt + receiptAction: record-payment-receipt + credentialRef: secret:env/PAYMENT_ADAPTER_BREG_TOKEN + credentialIdentity: payment-adapter diff --git a/products/adapter/examples/payment-collections/runtime.example.yaml b/products/adapter/examples/payment-collections/runtime.example.yaml new file mode 100644 index 0000000000..015c867e75 --- /dev/null +++ b/products/adapter/examples/payment-collections/runtime.example.yaml @@ -0,0 +1,17 @@ +# yaml-language-server: $schema=https://id.registrystack.org/schemas/adapter/runtime/runtime.v1alpha1.schema.json +apiVersion: id.registrystack.org/formats/adapter/runtime/v1alpha1 +kind: AdapterRuntimeConfig +id: synthetic-licence-payments +endpoints: [] +listener: + bind: 127.0.0.1:8098 +database: + runtimeUrlRef: secret:env/PAYMENT_ADAPTER_DB_RUNTIME + migrationUrlRef: secret:env/PAYMENT_ADAPTER_DB_MIGRATION +oidc: + issuer: https://issuer.example.invalid + audience: urn:registry:payment-adapter +allowedClients: [coordinator-payments] +allowedPrivateCidrs: [127.0.0.0/8] +audit: + retentionDays: 90 diff --git a/products/adapter/schemas/payments.v1alpha1.schema.json b/products/adapter/schemas/payments.v1alpha1.schema.json new file mode 100644 index 0000000000..c1f0a9eb81 --- /dev/null +++ b/products/adapter/schemas/payments.v1alpha1.schema.json @@ -0,0 +1,238 @@ +{ + "$defs": { + "LocalId": { + "description": "A local identifier: a lowercase letter, then up to 63 lowercase letters, digits, `_`, or `-`.", + "pattern": "^[a-z][a-z0-9_-]{0,63}$", + "type": "string" + }, + "PaymentBinding": { + "additionalProperties": false, + "description": "Persisted in full before a provider send. It holds credential references\nand identities, never credential values. Rotation at the same reference is\nsupported; changing a reference does not reroute a retained attempt.", + "properties": { + "currency": { + "pattern": "^[A-Z]{3}$", + "type": "string" + }, + "currencyScale": { + "format": "uint8", + "maximum": 6, + "minimum": 0, + "type": "integer" + }, + "provider": { + "$ref": "#/$defs/SimulatorConnection" + }, + "providerCredentialIdentity": { + "type": "string" + }, + "providerCredentialRef": { + "$ref": "#/$defs/SecretReference" + }, + "registry": { + "$ref": "#/$defs/RegistryBinding" + }, + "replayWindowSeconds": { + "format": "uint64", + "maximum": 86400, + "minimum": 1, + "type": "integer" + }, + "simulation": { + "const": true, + "type": "boolean" + } + }, + "required": [ + "simulation", + "currency", + "currencyScale", + "provider", + "providerCredentialRef", + "providerCredentialIdentity", + "replayWindowSeconds", + "registry" + ], + "type": "object" + }, + "PaymentConnection": { + "additionalProperties": false, + "properties": { + "allowedClients": { + "items": { + "type": "string" + }, + "maxItems": 64, + "minItems": 1, + "type": "array", + "uniqueItems": true + }, + "binding": { + "$ref": "#/$defs/PaymentBinding" + }, + "id": { + "$ref": "#/$defs/LocalId" + }, + "institutionId": { + "maxLength": 128, + "minLength": 1, + "pattern": "^[\\x21-\\x7e]+$", + "type": "string" + }, + "requiredScope": { + "maxLength": 128, + "minLength": 1, + "pattern": "^[\\x21-\\x7e]+$", + "type": "string" + }, + "serviceId": { + "maxLength": 128, + "minLength": 1, + "pattern": "^[\\x21-\\x7e]+$", + "type": "string" + } + }, + "required": [ + "id", + "institutionId", + "serviceId", + "allowedClients", + "requiredScope", + "binding" + ], + "type": "object" + }, + "RegistryBinding": { + "additionalProperties": false, + "properties": { + "baseUrl": { + "$ref": "#/$defs/Url" + }, + "bindAction": { + "type": "string" + }, + "bindProfile": { + "type": "string" + }, + "credentialIdentity": { + "type": "string" + }, + "credentialRef": { + "$ref": "#/$defs/SecretReference" + }, + "readProfile": { + "type": "string" + }, + "receiptAction": { + "type": "string" + }, + "receiptProfile": { + "type": "string" + }, + "recordRoute": { + "type": "string" + }, + "recordType": { + "type": "string" + } + }, + "required": [ + "baseUrl", + "recordType", + "recordRoute", + "readProfile", + "bindProfile", + "receiptProfile", + "bindAction", + "receiptAction", + "credentialRef", + "credentialIdentity" + ], + "type": "object" + }, + "SecretReference": { + "description": "An exact secret reference: secret:file/name, resolved under secretProviders.file.root, or secret:env/NAME, resolved only when secretProviders.environment is declared.", + "pattern": "^(?:secret:env/[A-Z][A-Z0-9_]{0,127}|secret:file/[a-z][a-z0-9._-]{0,127})$", + "type": "string" + }, + "SimulatorConnection": { + "additionalProperties": false, + "description": "Operator-owned synthetic provider routing. Credentials are supplied only at\nthe send boundary and never belong to a persisted command or connection.", + "properties": { + "baseUrl": { + "$ref": "#/$defs/Url" + }, + "biller": { + "maxLength": 20, + "minLength": 1, + "pattern": "^[\\x21-\\x7e]+$", + "type": "string" + }, + "billerName": { + "maxLength": 10, + "minLength": 1, + "pattern": "^[\\x21-\\x7e]+$", + "type": "string" + }, + "callbackUrl": { + "$ref": "#/$defs/Url" + }, + "payerFiBic": { + "maxLength": 10, + "minLength": 1, + "pattern": "^[\\x21-\\x7e]+$", + "type": "string" + }, + "tenant": { + "maxLength": 20, + "minLength": 1, + "pattern": "^[\\x21-\\x7e]+$", + "type": "string" + } + }, + "required": [ + "baseUrl", + "tenant", + "biller", + "billerName", + "callbackUrl", + "payerFiBic" + ], + "type": "object" + }, + "Url": { + "description": "An absolute http or https URL with a host preserved as written, no user information, and no backslash, whitespace or control character. DNS case and equivalent IPv6 literals are permitted.", + "format": "uri", + "maxLength": 2048, + "pattern": "^[Hh][Tt][Tt][Pp][Ss]?://[^/?#@\\u005C\\u0000-\\u0020\\u007F-\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000]+([/?#][^\\u005C\\u0000-\\u0020\\u007F-\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000]*)?$", + "type": "string" + } + }, + "$id": "https://id.registrystack.org/schemas/adapter/payments/payments.v1alpha1.schema.json", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "properties": { + "apiVersion": { + "const": "id.registrystack.org/formats/adapter/payments/v1alpha1", + "type": "string" + }, + "connections": { + "items": { + "$ref": "#/$defs/PaymentConnection" + }, + "maxItems": 64, + "minItems": 1, + "type": "array" + }, + "kind": { + "const": "AdapterPayments", + "type": "string" + } + }, + "required": [ + "apiVersion", + "connections", + "kind" + ], + "title": "Registry Adapter payment connections", + "type": "object" +} diff --git a/products/adapter/scripts/check-contracts.sh b/products/adapter/scripts/check-contracts.sh index 9c95c85f04..6f36882036 100755 --- a/products/adapter/scripts/check-contracts.sh +++ b/products/adapter/scripts/check-contracts.sh @@ -26,8 +26,8 @@ python3 -m unittest discover -s products/adapter/scripts -p 'test_test_connector # the caller's PATH. PATH="$HOME/.cargo/bin:$PATH" cargo fmt --all --check clear_completed_adapter_lane -PATH="$HOME/.cargo/bin:$PATH" cargo clippy --locked -p registry-adapter -p registry-adapter-core -p registry-adapter-engine -p registry-adapter-job -p registry-adapterctl --all-targets -- -D warnings -PATH="$HOME/.cargo/bin:$PATH" cargo test --locked -p registry-adapter -p registry-adapter-core -p registry-adapter-engine -p registry-adapter-job -p registry-adapterctl --no-fail-fast +PATH="$HOME/.cargo/bin:$PATH" cargo clippy --locked -p registry-adapter -p registry-adapter-core -p registry-adapter-engine -p registry-adapter-job -p registry-adapterctl -p registry-payment-protocol -p registry-payment-client -p registry-payment-simulator-connector --all-targets -- -D warnings +PATH="$HOME/.cargo/bin:$PATH" cargo test --locked -p registry-adapter -p registry-adapter-core -p registry-adapter-engine -p registry-adapter-job -p registry-adapterctl -p registry-payment-protocol -p registry-payment-client -p registry-payment-simulator-connector --no-fail-fast # The BReg connector is default-off. Compile every connector target with its # feature and execute its scripted suites here; the real-runtime scenarios # remain isolated under test-connector-native.py because they provision BReg diff --git a/products/adapter/scripts/check_dependency_direction.py b/products/adapter/scripts/check_dependency_direction.py index e6564131c8..c7acdd6a8c 100755 --- a/products/adapter/scripts/check_dependency_direction.py +++ b/products/adapter/scripts/check_dependency_direction.py @@ -2,16 +2,22 @@ # SPDX-License-Identifier: Apache-2.0 """Check Adapter dependency direction from Cargo's resolved graph. -The Adapter's engine and facade stay source-neutral: `registry-adapter-engine`, -`registry-adapter`, `registry-adapter-core`, `registry-adapter-job`, and -`registry-adapterctl` reach shared platform primitives and nothing else -of the workspace, and no Adapter crate links a Coordinator crate. The -one product-surface exception is the direct BReg connector crate: +The Adapter's core and shared engine stay source-neutral, and no Adapter +crate links a Coordinator crate. The one product-surface exception for +ingestion is the direct BReg connector crate: `registry-adapter-connectors` reaches exactly `registry-breg-client` behind the job host's exact off-by-default `direct-breg` feature, is linked by no facade or engine crate, and never reaches a product runtime, adopter tooling, supporting service, binding, or database crate. +The payment host exception permits `registry-adapter` +to link its payment protocol, standalone synthetic provider connector, and +the public BReg client for exact restricted Actions. Authoring inherits that +closure only through its host edge. No product runtime enters it, and no +payment or product-client dependency enters the shared engine. The provider +connector itself reaches only the runtime-free payment protocol and platform +transport primitives. + `registry-adapter-engine` is the listener-free engine used by ingestion, the facade, Evidence and BReg external projections. Its resolved closure may reach only `registry-adapter-core`, shared platform crates, and non-workspace support. @@ -38,8 +44,8 @@ ADAPTER_PREFIX = "registry-adapter" -# The engine crates the product contract keeps source-neutral. None may -# reach a product crate of any kind. +# Hosts and engine crates checked here. The facade host has the explicit +# payment exception; authoring may inherit it through that host edge only. ADAPTER_ENGINE = ( "registry-adapter-engine", "registry-adapter", @@ -93,6 +99,7 @@ "idempotent", "journal", "notifier", + "payments", "serve", "replay_serve", ) @@ -114,6 +121,9 @@ # feature path, and never reaches a product runtime, adopter tooling, # supporting service, binding, database crate, or any Coordinator crate. CONNECTOR = "registry-adapter-connectors" +PAYMENT_HOST = "registry-adapter" +PAYMENT_PROTOCOL = "registry-payment-protocol" +PAYMENT_PROVIDER = "registry-payment-simulator-connector" # The maintained product client the connector may reach. CONNECTOR_CLIENTS = frozenset( @@ -290,6 +300,30 @@ def connector_may_reach(name: str) -> bool: return name in CONNECTOR_CLIENTS or name in CLIENT_SUPPORT +def payment_host_may_reach(name: str) -> bool: + """The host keeps attempts and calls only the public BReg client surface.""" + return ( + engine_may_reach(PAYMENT_HOST, name) + or name in {PAYMENT_PROTOCOL, PAYMENT_PROVIDER} + or name in CONNECTOR_CLIENTS + or name in CLIENT_SUPPORT + ) + + +def authoring_refused(start, names, every, linked) -> set[str]: + """Authoring may inherit the host closure, not link product clients itself.""" + refused = set() + for dependency in every.get(start, set()): + permits = payment_host_may_reach if names[dependency] == PAYMENT_HOST else ( + lambda name: engine_may_reach("registry-adapterctl", name) + ) + for reached in {dependency, *linked_closure(dependency, linked)}: + # The host is the declared authoring edge itself. + if names[reached] != PAYMENT_HOST and not permits(names[reached]): + refused.add(names[reached]) + return refused + + def job_refused( start: str, names: dict[str, str], @@ -420,6 +454,10 @@ def violations(metadata: dict) -> list[str]: if name in ADAPTER_ENGINE: if name == JOB_HOST: refused = sorted(job_refused(package_id, names, every, linked)) + elif name == PAYMENT_HOST: + refused = sorted(item for item in reached if not payment_host_may_reach(item)) + elif name == "registry-adapterctl": + refused = sorted(authoring_refused(package_id, names, every, linked)) else: refused = sorted( item for item in reached if not engine_may_reach(name, item) @@ -429,6 +467,17 @@ def violations(metadata: dict) -> list[str]: f"{name} reaches package(s) outside registry-platform-* and " f"neutral support: {', '.join(refused)}" ) + elif name in {PAYMENT_PROTOCOL, PAYMENT_PROVIDER}: + refused = sorted( + item for item in reached + if item.startswith("registry-") + and not ( + name == PAYMENT_PROVIDER + and (item == PAYMENT_PROTOCOL or item.startswith("registry-platform-")) + ) + ) + if refused: + failures.append(f"{name} reaches package(s) outside its payment boundary: {', '.join(refused)}") elif name == CONNECTOR: refused = sorted(item for item in reached if not connector_may_reach(item)) if refused: @@ -648,7 +697,8 @@ def main() -> int: print("fixed GovStack wire behavior stays in the facade host;") print("the job's off-by-default direct-BReg path reaches the connector,") print("the signed-event path reaches platform primitives only, the connector") - print("reaches registry-breg-client alone, and no Adapter crate links a") + print("reaches registry-breg-client alone; the scoped payment host reaches its") + print("protocol, standalone provider and public BReg client. No Adapter crate links a") print("Coordinator crate.") return 0 diff --git a/products/adapter/scripts/payment-native-support.mjs b/products/adapter/scripts/payment-native-support.mjs new file mode 100644 index 0000000000..081f20b61a --- /dev/null +++ b/products/adapter/scripts/payment-native-support.mjs @@ -0,0 +1,221 @@ +// SPDX-License-Identifier: Apache-2.0 +// Process and transport fixtures for synthetic native payment acceptance. +import assert from 'node:assert/strict'; +import { createHash, generateKeyPairSync, randomUUID, sign, verify } from 'node:crypto'; +import { closeSync, openSync } from 'node:fs'; +import { chmod, readFile, writeFile } from 'node:fs/promises'; +import http from 'node:http'; +import { spawn, spawnSync } from 'node:child_process'; +import { basename, join } from 'node:path'; + +export const sleep = (milliseconds) => new Promise((resolve) => setTimeout(resolve, milliseconds)); +export const hash = (value) => createHash('sha256').update(value).digest('hex'); + +export async function privateFile(path, value) { + await writeFile(path, typeof value === 'string' || Buffer.isBuffer(value) ? value : JSON.stringify(value, null, 2), { mode: 0o600 }); + await chmod(path, 0o600); +} + +export async function secret(path) { + const value = (await readFile(path, 'utf8')).trim(); + assert(value && value.length <= 65536, 'private fixture value must be bounded'); + return value; +} + +// Keep dirty-tree provenance private. The known Git base plus this binary patch +// reconstructs tracked content; per-file hashes also cover the executed harness. +export async function sourceSnapshot(repository, directory) { + const git = (...args) => command('git', ['--no-optional-locks', '-C', repository, ...args], { json: false }); + assert.equal(git('ls-files', '--others', '--exclude-standard').trim(), '', 'stage new source files before native acceptance'); + const patch = git('diff', '--binary', 'HEAD'); + await privateFile(join(directory, 'source.patch'), patch); + const files = []; + for (const path of git('ls-files', '-z').split('\0').filter(Boolean)) { + try { files.push({ path, sha256: hash(await readFile(join(repository, path))) }); } + catch (error) { + if (error.code !== 'ENOENT') throw error; + files.push({ path, deleted: true }); + } + } + const snapshot = { scope: 'source content at run time; binary build provenance is separately attested', + head: git('rev-parse', 'HEAD').trim(), status: git('status', '--porcelain'), patchSha256: hash(patch), files }; + await privateFile(join(directory, 'source-snapshot.json'), snapshot); + return snapshot; +} + +export function command(binary, args, { env = process.env, input, json = true } = {}) { + const result = spawnSync(binary, args, { env, input, encoding: 'utf8', maxBuffer: 4 * 1024 * 1024, timeout: 120000 }); + // Never repeat stderr or argv: tools may include configured credentials in errors. + if (result.status !== 0) { + const codes = new Set(); + function visit(value) { + if (!value || typeof value !== 'object') return; + if (typeof value.code === 'string' && /^[a-z][a-z0-9_.-]{1,100}$/.test(value.code)) codes.add(value.code); + for (const child of Object.values(value)) visit(child); + } + try { visit(JSON.parse(result.stdout)); } catch { codes.add('fixture.non-json-command-failure'); } + throw new Error(`${basename(binary)} failed (${result.status ?? result.error?.code ?? result.signal}): ${[...codes].join(', ')}`); + } + return json ? JSON.parse(result.stdout) : result.stdout; +} + +export function start(binary, args, logPath, env = process.env) { + const descriptor = openSync(logPath, 'w', 0o600); + const child = spawn(binary, args, { env, stdio: ['ignore', descriptor, descriptor] }); + closeSync(descriptor); + const exited = new Promise((resolve, reject) => { + child.once('exit', (code, signal) => resolve({ code, signal })); + child.once('error', () => reject(new Error('native fixture process could not start'))); + }); + return { + child, exited, + async stop() { + if (child.exitCode === null && child.signalCode === null) child.kill('SIGTERM'); + let timer; + const timeout = new Promise((resolve) => { timer = setTimeout(() => resolve(null), 15000); }); + const result = await Promise.race([exited, timeout]); + clearTimeout(timer); + assert(result, 'native fixture process did not stop within its shutdown budget'); + }, + }; +} + +export function loopback(origin) { + const url = new URL(origin); + assert(url.protocol === 'http:' && ['127.0.0.1', '[::1]'].includes(url.hostname) + && !url.username && !url.password && !url.search && !url.hash && url.pathname === '/', + 'native payment acceptance requires a numeric loopback HTTP origin'); + return url.origin; +} + +export async function exchange(method, url, { token, body, key, expected = [200] } = {}) { + const headers = {}; + if (token) headers.Authorization = `Bearer ${token}`; + if (key) headers['Idempotency-Key'] = key; + if (body !== undefined) headers['Content-Type'] = 'application/json'; + const response = await fetch(url, { method, headers, body: body === undefined ? undefined : JSON.stringify(body), + redirect: 'manual', signal: AbortSignal.timeout(20000) }); + const bytes = await response.arrayBuffer(); + assert(bytes.byteLength <= 1048576, 'native response exceeded its fixture bound'); + const value = bytes.byteLength ? JSON.parse(Buffer.from(bytes).toString()) : null; + const code = typeof value?.code === 'string' && /^[a-z][a-z0-9_.-]{1,100}$/.test(value.code) ? ` (${value.code})` : ''; + assert(expected.includes(response.status), `native ${method} ${new URL(url).pathname} returned HTTP ${response.status}${code}`); + return { status: response.status, body: value }; +} + +export async function ready(url, processHandle, expected = [200, 401]) { + for (let attempt = 0; attempt < 200; attempt += 1) { + assert(processHandle.child.exitCode === null && processHandle.child.signalCode === null, + 'native service exited before readiness; inspect its private log'); + try { + const response = await fetch(url, { signal: AbortSignal.timeout(300), redirect: 'manual' }); + if (expected.includes(response.status)) return; + } catch (error) { + if (!['TypeError', 'TimeoutError'].includes(error.name)) throw error; + } + await sleep(100); + } + throw new Error('native service did not become ready within its startup budget'); +} + +async function listen(server) { + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); + return `http://127.0.0.1:${server.address().port}`; +} + +export async function unusedPort() { + const server = http.createServer(); + const url = await listen(server); + await new Promise((resolve) => server.close(resolve)); + return Number(new URL(url).port); +} + +export async function authorization(secretsRoot) { + const issuer = 'https://payment-acceptance.example.test'; + const signer = generateKeyPairSync('ec', { namedCurve: 'P-256' }); + const client = generateKeyPairSync('ec', { namedCurve: 'P-256' }); + const jwks = { keys: [{ ...signer.publicKey.export({ format: 'jwk' }), kid: 'native-issuer', alg: 'ES256', use: 'sig' }] }; + const clientJwk = { ...client.privateKey.export({ format: 'jwk' }), kid: 'native-coordinator', alg: 'ES256', use: 'sig' }; + await privateFile(`${secretsRoot}/jwks`, jwks); + await privateFile(`${secretsRoot}/coordinator-payments-jwk`, clientJwk); + const b64 = (value) => Buffer.from(JSON.stringify(value)).toString('base64url'); + function token(subject, audience, scope, clientId = 'coordinator-payments') { + const now = Math.floor(Date.now() / 1000); + const payload = `${b64({ alg: 'ES256', kid: 'native-issuer', typ: 'at+jwt' })}.${b64({ + iss: issuer, sub: subject, client_id: clientId, aud: audience, scope, iat: now, nbf: now, exp: now + 3600, jti: randomUUID(), + })}`; + return `${payload}.${sign('sha256', Buffer.from(payload), { key: signer.privateKey, dsaEncoding: 'ieee-p1363' }).toString('base64url')}`; + } + const used = new Set(); + let grants = 0; + const server = http.createServer(async (request, response) => { + try { + assert(request.method === 'POST' && request.url === '/token'); + const chunks = []; let size = 0; + for await (const chunk of request) { size += chunk.length; assert(size <= 16384); chunks.push(chunk); } + const form = new URLSearchParams(Buffer.concat(chunks).toString()); + assert.equal(form.get('grant_type'), 'client_credentials'); + assert.equal(form.get('client_assertion_type'), 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer'); + assert.equal(form.get('resource'), 'urn:registry:payment-adapter'); + assert.equal(form.get('scope'), 'payments:collect'); + const parts = form.get('client_assertion').split('.'); assert.equal(parts.length, 3); + const header = JSON.parse(Buffer.from(parts[0], 'base64url')); assert.equal(header.alg, 'ES256'); + assert(verify('sha256', Buffer.from(`${parts[0]}.${parts[1]}`), { key: client.publicKey, dsaEncoding: 'ieee-p1363' }, Buffer.from(parts[2], 'base64url'))); + const claims = JSON.parse(Buffer.from(parts[1], 'base64url')); + assert.equal(claims.iss, 'coordinator-payments'); assert.equal(claims.sub, 'coordinator-payments'); + assert.equal(claims.aud, issuer); + const now = Math.floor(Date.now() / 1000); + assert(claims.exp > now && claims.exp <= now + 600 && typeof claims.jti === 'string' && !used.has(claims.jti)); + used.add(claims.jti); grants += 1; + response.writeHead(200, { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' }); + response.end(JSON.stringify({ token_type: 'Bearer', expires_in: 3600, + access_token: token('payment-coordinator', 'urn:registry:payment-adapter', 'payments:collect') })); + } catch { + response.writeHead(401, { 'Content-Type': 'application/json' }); + response.end(JSON.stringify({ error: 'invalid_client' })); + } + }); + const origin = await listen(server); + return { issuer, origin, token, jwks, get grants() { return grants; }, + async close() { server.closeAllConnections(); await new Promise((resolve) => server.close(resolve)); } }; +} + +export async function relay(origin) { + origin = loopback(origin); + const records = []; const drops = new Set(); + let failRead = false; let corruptAmount = false; + const server = http.createServer(async (request, response) => { + try { + assert(request.url.startsWith('/') && !request.url.startsWith('//')); + const chunks = []; let length = 0; + for await (const chunk of request) { length += chunk.length; assert(length <= 1048576); chunks.push(chunk); } + const body = Buffer.concat(chunks); + if (failRead && request.method === 'GET' && request.url.startsWith('/v1/records/')) { + failRead = false; response.writeHead(503); response.end(); return; + } + const headers = Object.fromEntries(Object.entries(request.headers).filter(([name]) => !['host', 'connection', 'content-length'].includes(name))); + const upstream = await fetch(origin + request.url, { method: request.method, headers, + body: ['GET', 'HEAD'].includes(request.method) ? undefined : body, redirect: 'manual', signal: AbortSignal.timeout(15000) }); + let raw = Buffer.from(await upstream.arrayBuffer()); assert(raw.length <= 1048576); + if (request.method === 'POST') records.push({ path: request.url.split('?')[0], key: request.headers['idempotency-key'] ?? null, + bodyHash: hash(body), tenant: request.headers['x-platform-tenantid'] ?? null, + biller: request.headers['x-billerid'] ?? null, status: upstream.status }); + const path = request.url.split('?')[0]; + if (request.method === 'POST' && upstream.ok && drops.delete(path)) { + if (path.startsWith('/v1/actions/')) failRead = true; + request.socket.destroy(); return; + } + if (corruptAmount && request.method === 'GET' && path.startsWith('/transferRequests/') && upstream.ok) { + const value = JSON.parse(raw); value.amount = 25.51; raw = Buffer.from(JSON.stringify(value)); + } + const returned = Object.fromEntries([...upstream.headers].filter(([name]) => !['connection', 'transfer-encoding', 'content-length'].includes(name))); + response.writeHead(upstream.status, { ...returned, 'Content-Length': raw.length }); response.end(raw); + } catch { + if (!response.headersSent) response.writeHead(502); + response.end(); + } + }); + const url = await listen(server); + return { url, records, drop(path) { drops.add(path); }, corrupt(value) { corruptAmount = value; }, + async close() { server.closeAllConnections(); await new Promise((resolve) => server.close(resolve)); } }; +} diff --git a/products/adapter/scripts/test-payment-native.mjs b/products/adapter/scripts/test-payment-native.mjs new file mode 100644 index 0000000000..7733a78776 --- /dev/null +++ b/products/adapter/scripts/test-payment-native.mjs @@ -0,0 +1,385 @@ +#!/usr/bin/env node +// SPDX-License-Identifier: Apache-2.0 +// Synthetic native acceptance. Existing fixture BReg stays owned by its launcher. +import assert from 'node:assert/strict'; +import { randomBytes, randomUUID } from 'node:crypto'; +import { mkdir, readFile } from 'node:fs/promises'; +import { resolve, join, dirname } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { parseArgs } from 'node:util'; +import { authorization, command, exchange, hash, loopback, privateFile, ready, relay, secret, sleep, sourceSnapshot, start, unusedPort } from './payment-native-support.mjs'; + +const argumentNames = ['fixture', 'bin-dir', 'simulator-bin', 'admin-url-file', 'ca-file', 'state-dir', 'build-record']; +const options = parseArgs({ options: Object.fromEntries(argumentNames.map((name) => [name, { type: 'string' }])) }).values; +for (const name of argumentNames) assert(options[name], `--${name} is required`); +const repository = fileURLToPath(new URL('../../..', import.meta.url)); +const root = resolve(options['state-dir']); +const binaries = resolve(options['bin-dir']); +const simulatorBin = resolve(options['simulator-bin']); +await mkdir(root, { mode: 0o700 }); // A new private run only; no overwrites or cleanup of other runs. +const secrets = join(root, 'secrets'); await mkdir(secrets, { mode: 0o700 }); +const fixture = JSON.parse(await readFile(options.fixture, 'utf8')); +assert.equal(fixture.mode, 'synthetic-loopback-only'); +const bregOrigin = loopback(fixture.baseUrl); +await exchange('GET', `${bregOrigin}/ready`); +const admin = new URL(await secret(options['admin-url-file'])); +assert(['postgres:', 'postgresql:'].includes(admin.protocol) && ['127.0.0.1', 'localhost', '[::1]'].includes(admin.hostname), 'owned loopback PostgreSQL is required'); +await privateFile(join(secrets, 'postgres-ca'), await readFile(options['ca-file'])); +await privateFile(join(secrets, 'registry-token'), await secret(fixture.credentials.paymentAdapter)); +await privateFile(join(secrets, 'provider-token'), randomBytes(32).toString('hex')); +await privateFile(join(secrets, 'changed-provider-token'), randomBytes(32).toString('hex')); +for (const name of ['state-key', 'admission-key', 'audit-key']) await privateFile(join(secrets, name), randomBytes(32)); +let issuer; +const reporter = await secret(fixture.credentials.paymentAdapter); +const serviceToken = await secret(fixture.credentials.issuanceService); +const readOnlyToken = await secret(fixture.credentials.serviceCoordinator); +let paymentToken; +const suffix = randomUUID().replaceAll('-', '').slice(0, 12); +const handles = []; const relays = []; const evidence = { mode: 'synthetic-native', checks: [] }; +let adapter; let simulator; let coordinator; +function check(name) { evidence.checks.push(name); console.log(`PASS ${name}`); } +function sql(text, url = admin) { + const env = Object.fromEntries(Object.entries(process.env).filter(([name]) => !name.startsWith('PG'))); + Object.assign(env, { PGHOST: url.hostname.replaceAll('[', '').replaceAll(']', ''), PGPORT: url.port || '5432', + PGUSER: decodeURIComponent(url.username), PGPASSWORD: decodeURIComponent(url.password), PGDATABASE: url.pathname.slice(1), + PGSSLMODE: 'verify-full', PGSSLROOTCERT: resolve(options['ca-file']), PGCONNECT_TIMEOUT: '5' }); + return command('psql', ['--no-psqlrc', '-X', '-q', '-A', '-t', '-v', 'ON_ERROR_STOP=1'], { env, input: text, json: false }); +} +async function database(kind) { + const name = `payment_${kind}_${suffix}`; const migration = `${name}_m`; const runtime = `${name}_r`; + const password = randomBytes(24).toString('hex'); + sql(`CREATE ROLE ${migration} LOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE NOINHERIT NOBYPASSRLS PASSWORD '${password}'; +CREATE ROLE ${runtime} LOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE NOINHERIT NOBYPASSRLS PASSWORD '${password}'; +CREATE DATABASE ${name} OWNER ${migration} ENCODING 'UTF8' TEMPLATE template0;`); + const owner = new URL(admin); owner.pathname = `/${name}`; + sql(`ALTER SCHEMA public OWNER TO ${migration}; REVOKE ALL ON SCHEMA public FROM PUBLIC; GRANT USAGE ON SCHEMA public TO ${runtime};`, owner); + const url = (role) => { const value = new URL(owner); value.username = role; value.password = password; value.search = '?sslmode=require'; return value.toString(); }; + await privateFile(join(secrets, `${kind}-migration`), url(migration)); + await privateFile(join(secrets, `${kind}-runtime`), url(runtime)); + return { name, migration, runtime, owner }; +} +function ctl(args) { return command(join(binaries, 'coordinatorctl'), ['--format', 'json', ...args]); } +const simDatabase = join(root, 'simulator.sqlite'); +let simulatorPort; let adapterPort; let coordinatorPort; +let adapterOrigin; let coordinatorOrigin; let collectionPath; +let runtimePath; let paymentsPath; let configuration; let simulatorProxy; let registryProxy; let coordinatorProxy; +function simControl(args) { return command(simulatorBin, [...args, '--database', simDatabase], { json: args[0] === 'inspect-collections' }); } +const ledger = () => simControl(['inspect-collections']); +async function startSimulator() { + simulator = start(simulatorBin, ['serve', '--manual', '--database', simDatabase, '--token-file', join(secrets, 'provider-token'), '--port', String(simulatorPort)], join(root, 'simulator.log')); + handles.push(simulator); await ready(`http://127.0.0.1:${simulatorPort}/healthz`, simulator); +} +async function startAdapter() { + adapter = start(join(binaries, 'adapter'), ['serve', '--runtime-config', runtimePath, '--payments-config', paymentsPath], join(root, `adapter-${handles.length}.log`)); + handles.push(adapter); await ready(`${collectionPath}/${randomUUID()}`, adapter, [401]); +} +async function restartAdapter() { await adapter.stop(); await startAdapter(); } +async function createBill(label) { + const requestId = `${label}-${suffix}`; + const input = { institutionId: 'institution-a', serviceId: 'licence-issuance', requestId, + payerId: 'synthetic-payer', payerFinancialAddress: '+99123456789', billDigest: hash(requestId), simulation: true }; + const response = await exchange('POST', bregOrigin + fixture.create.path, { token: serviceToken, body: { input }, key: requestId }); + return { billId: response.body.results.bill.recordId, billVersion: 1, requestId, issuanceId: randomUUID() }; +} +const intent = (bill) => ({ billId: bill.billId, billVersion: bill.billVersion }); +async function readBill(bill) { + const response = await exchange('GET', `${bregOrigin}/v1/records/${fixture.recordRoute}/${bill.billId}?accessProfile=${fixture.readProfile}`, { token: reporter }); + return response.body.data.domainData; +} +async function collect(bill, key, expected = [202], token = paymentToken, extra = {}) { + return exchange('POST', collectionPath, { token, body: { ...intent(bill), ...extra }, key, expected }); +} +async function observe(id, expected = [200], token = paymentToken) { + return exchange('GET', `${collectionPath}/${id}`, { token, expected }); +} +async function report(id, key, expected = [200]) { + return exchange('POST', `${collectionPath}/${id}/record-receipt`, { token: paymentToken, body: { collectionId: id }, key, expected }); +} +async function issue(bill, receipt, key, expected = [200]) { + const path = `/v1/actions/${fixture.issue.action}`; + const query = `?accessProfile=${fixture.issue.profile}`; + const conditions = await exchange('POST', bregOrigin + path + '/target-conditions' + query, { token: serviceToken, body: { input: { billId: bill.billId } } }); + const input = { ...intent(bill), requestId: bill.requestId, paymentReceiptId: receipt, issuanceId: bill.issuanceId }; + return exchange('POST', bregOrigin + path + query, { token: serviceToken, body: { input, preconditions: conditions.body.preconditions }, key: `${key}-${suffix}`, expected }); +} + +async function preflightAndGrant(db, runtime, payments, label) { + const log = join(root, `${label}-preflight.log`); + const initial = start(join(binaries, 'adapter'), ['serve', '--runtime-config', runtime, '--payments-config', payments], log); + handles.push(initial); + const result = await Promise.race([initial.exited, sleep(15000).then(() => null)]); + assert(result && result.code !== 0, 'split runtime must refuse before payment table grants'); + assert.match(await readFile(log, 'utf8'), /\badapter\.payment\.configuration\b/, 'preflight must fail at the payment privilege diagnostic'); + sql(`GRANT SELECT, INSERT, UPDATE ON adapter_payment_attempts TO ${db.runtime}; +GRANT SELECT, INSERT ON adapter_payment_commands, adapter_payment_events TO ${db.runtime}; +GRANT USAGE, SELECT ON SEQUENCE adapter_payment_events_sequence_seq TO ${db.runtime};`, db.owner); +} + +async function independentStores(originalConfiguration) { + const prior = ledger(); const collections = []; + simControl(['collection-scenario', '--outcome', 'paid']); + const configPath = join(root, 'independent-payments.yaml'); + await privateFile(configPath, originalConfiguration); + for (const kind of ['independent_a', 'independent_b']) { + const db = await database(kind); evidence.databases.push(db.name); + const port = await unusedPort(); const origin = `http://127.0.0.1:${port}`; + const runtime = JSON.parse(await readFile(runtimePath, 'utf8')); + runtime.id = `${kind.replaceAll('_', '-')}-${suffix}`; + runtime.listener.bind = `127.0.0.1:${port}`; + runtime.database.runtimeUrlRef = `secret:file/${kind}-runtime`; + runtime.database.migrationUrlRef = `secret:file/${kind}-migration`; + const path = join(root, `${kind}-runtime.yaml`); await privateFile(path, runtime); + await preflightAndGrant(db, path, configPath, kind); + const process = start(join(binaries, 'adapter'), ['serve', '--runtime-config', path, '--payments-config', configPath], join(root, `${kind}.log`)); + handles.push(process); + const route = `${origin}/v1/payments/licence-fees/collections`; + await ready(`${route}/${randomUUID()}`, process, [401]); + const bill = await createBill(kind); + const accepted = (await exchange('POST', route, { token: paymentToken, body: intent(bill), key: kind, expected: [202] })).body; + assert.deepEqual((await exchange('POST', route, { token: paymentToken, body: intent(bill), key: `${kind}-repeat`, expected: [202] })).body, accepted); + collections.push({ route, bill, accepted }); + } + // Both fresh stores start from identical provider scope, payer and amount. + assert.notEqual(collections[0].accepted.collectionId, collections[1].accepted.collectionId); + assert.equal(ledger().requestCount, prior.requestCount + 2, 'independent bills must create two provider requests'); + simControl(['advance', '--steps', '2']); + const receipts = []; + for (const { route, bill, accepted } of collections) { + const path = `${route}/${accepted.collectionId}`; + const observation = (await exchange('GET', path, { token: paymentToken })).body; + assert.equal(observation.state, 'confirmed'); + const receipt = (await exchange('POST', `${path}/record-receipt`, { token: paymentToken, body: { collectionId: accepted.collectionId }, key: 'independent-receipt' })).body; + assert.equal((await readBill(bill)).paymentReceiptId, receipt.receiptId); + receipts.push(receipt); + } + assert.notEqual(receipts[0].receiptId, receipts[1].receiptId); + assert.notEqual(receipts[0].providerReference, receipts[1].providerReference); + const payments = ledger().payments.filter((payment) => receipts.some((receipt) => receipt.providerReference === payment.PaymentReferenceID)); + assert.equal(payments.length, 2); + for (const field of ['transferRequestId', 'RequestId', 'rtpId', 'billId']) assert.notEqual(payments[0][field], payments[1][field]); + assert.equal(ledger().payments.length, prior.payments.length + 2); + evidence.independentStores = { collections: collections.map(({ bill, accepted }) => ({ bill, accepted })), payments }; + check('independent Adapter databases preserve distinct same-payer same-amount bills and provider payments'); +} + +try { + issuer = await authorization(secrets); + paymentToken = issuer.token('payment-coordinator', 'urn:registry:payment-adapter', 'payments:collect'); + simulatorPort = await unusedPort(); adapterPort = await unusedPort(); coordinatorPort = await unusedPort(); + adapterOrigin = `http://127.0.0.1:${adapterPort}`; coordinatorOrigin = `http://127.0.0.1:${coordinatorPort}`; + collectionPath = `${adapterOrigin}/v1/payments/licence-fees/collections`; + evidence.transport = { postgres: 'TLS with trusted CA', services: 'synthetic numeric-loopback HTTP' }; + evidence.source = await sourceSnapshot(repository, root); + evidence.build = { ...JSON.parse(await readFile(options['build-record'], 'utf8')), kind: 'operator-supplied-attestation' }; + assert(evidence.build.source?.head && evidence.build.source?.patchSha256 && evidence.build.command?.length && evidence.build.toolchain, + 'build attestation requires source, command and toolchain facts'); + evidence.binaries = {}; + for (const name of ['adapter', 'adapterctl', 'coordinator', 'coordinatorctl']) { + evidence.binaries[name] = hash(await readFile(join(binaries, name))); + assert.equal(evidence.build.binaries[name].sha256, evidence.binaries[name], 'build record must describe the actual executable'); + assert(Array.isArray(evidence.build.binaries[name].features) && evidence.build.binaries[name].profile, + 'build attestation requires enabled features and profile facts'); + } + evidence.fixtureBinaries = fixture.binaryProvenance; + for (const name of ['breg', 'bregctl']) { + const binary = fixture.binaryProvenance[name]; + assert.equal(hash(await readFile(binary.path)), binary.sha256, 'BReg handoff binary must retain its recorded identity'); + } + const imported = command(join(dirname(simulatorBin), 'python'), ['-c', `import hashlib, json, pathlib, platform, payment_simulator +root = pathlib.Path(payment_simulator.__file__).resolve().parent +print(json.dumps({'path':str(root), 'python':platform.python_version(), 'files':[{'path':str(path.relative_to(root)), 'sha256':hashlib.sha256(path.read_bytes()).hexdigest()} for path in sorted(root.rglob('*.py'))]}))`]); + const packagePrefix = 'tools/payment-simulator/src/payment_simulator/'; + const expectedPackage = evidence.source.files.filter((file) => file.path.startsWith(packagePrefix) && file.path.endsWith('.py')) + .map((file) => ({ ...file, path: file.path.slice(packagePrefix.length) })); + assert.deepEqual(imported.files, expectedPackage, 'simulator must import the recorded package content'); + evidence.simulator = { executableSha256: hash(await readFile(simulatorBin)), imported, + source: evidence.source.files.filter((file) => file.path.startsWith('tools/payment-simulator/')) }; + const adapterDb = await database('adapter'); const coordinatorDb = await database('coordinator'); + evidence.databases = [adapterDb.name, coordinatorDb.name]; + await startSimulator(); + simulatorProxy = await relay(`http://127.0.0.1:${simulatorPort}`); relays.push(simulatorProxy); + registryProxy = await relay(bregOrigin); relays.push(registryProxy); + configuration = { apiVersion: 'id.registrystack.org/formats/adapter/payments/v1alpha1', kind: 'AdapterPayments', connections: [{ + id: 'licence-fees', institutionId: 'institution-a', serviceId: 'licence-issuance', allowedClients: ['coordinator-payments'], requiredScope: 'payments:collect', + binding: { simulation: true, currency: 'USD', currencyScale: 2, providerCredentialRef: 'secret:file/provider-token', providerCredentialIdentity: 'registry', replayWindowSeconds: 3600, + provider: { baseUrl: simulatorProxy.url, tenant: 'pilot', biller: 'ministry', billerName: 'Ministry', callbackUrl: 'https://programme.example.test/callback', payerFiBic: 'SIMBANK' }, + registry: { baseUrl: registryProxy.url, recordType: fixture.recordType, recordRoute: fixture.recordRoute, readProfile: fixture.readProfile, + bindProfile: fixture.bind.profile, receiptProfile: fixture.receipt.profile, bindAction: fixture.bind.action, receiptAction: fixture.receipt.action, + credentialRef: 'secret:file/registry-token', credentialIdentity: 'payment-adapter' } }, + }] }; + const originalConfiguration = structuredClone(configuration); + paymentsPath = join(root, 'payments.yaml'); runtimePath = join(root, 'adapter-runtime.yaml'); + await privateFile(paymentsPath, configuration); + await privateFile(runtimePath, { apiVersion: 'id.registrystack.org/formats/adapter/runtime/v1alpha1', kind: 'AdapterRuntimeConfig', id: `payment-native-${suffix}`, + endpoints: [], listener: { bind: `127.0.0.1:${adapterPort}` }, secretProviders: { file: { root: secrets } }, + database: { runtimeUrlRef: 'secret:file/adapter-runtime', migrationUrlRef: 'secret:file/adapter-migration', trustedRootCertificateRef: 'secret:file/postgres-ca' }, + oidc: { issuer: issuer.issuer, audience: 'urn:registry:payment-adapter', jwksSource: { type: 'static', documentRef: 'secret:file/jwks' } }, + allowedClients: ['coordinator-payments'], allowedPrivateCidrs: ['127.0.0.0/8'], audit: { retentionDays: 90 } }); + await preflightAndGrant(adapterDb, runtimePath, paymentsPath, 'adapter'); + await startAdapter(); check('PostgreSQL TLS startup and exact split-role payment privilege diagnostic'); + + const bill = await createBill('recovery'); + await issue(bill, 'absent-receipt', 'unpaid-issue', [412]); + await collect(bill, 'extra-facts', [422], paymentToken, { amount: 1, paid: true }); + await collect(bill, 'missing-scope', [403], issuer.token('payment-coordinator', 'urn:registry:payment-adapter', '')); + await collect(bill, 'citizen', [401], null); + assert.equal(ledger().requestCount, 0); check('unpaid issuance, forged financial fields and unauthorized callers refused'); + + registryProxy.drop(`/v1/actions/${fixture.bind.action}`); + await collect(bill, 'original', [503]); assert.equal(ledger().requestCount, 0); + await restartAdapter(); simulatorProxy.drop('/rtpRequest'); + await collect(bill, 'original', [503]); assert.equal(ledger().requestCount, 1); + const beforeLookup = simulatorProxy.records.length; + await exchange('POST', `${collectionPath}/receipt`, { token: paymentToken, body: intent(bill), key: 'original', expected: [404] }); + assert.equal(simulatorProxy.records.length, beforeLookup); + await simulator.stop(); await startSimulator(); + const originalBinding = structuredClone(configuration.connections[0].binding); + Object.assign(configuration.connections[0].binding.provider, { baseUrl: 'http://127.0.0.1:9/', tenant: 'changed-tenant', biller: 'changed-biller' }); + configuration.connections[0].binding.providerCredentialRef = 'secret:file/changed-provider-token'; + configuration.connections[0].binding.providerCredentialIdentity = 'changed-producer'; + await privateFile(paymentsPath, configuration); await restartAdapter(); + const accepted = (await collect(bill, 'original')).body; + assert.deepEqual((await collect(bill, 'another-workflow-key')).body, accepted); + assert.equal(ledger().requestCount, 1); + const sends = simulatorProxy.records.filter((record) => record.path === '/rtpRequest'); + assert.equal(sends.length, 2); assert.equal(sends[0].bodyHash, sends[1].bodyHash); + assert(sends.every((record) => record.tenant === 'pilot' && record.biller === 'ministry')); + check('lost bind/provider responses recover across restarts under original command and binding'); + + await observe(accepted.collectionId, [404], issuer.token('another-subject', 'urn:registry:payment-adapter', 'payments:collect')); + await observe(accepted.collectionId, [403], issuer.token('payment-coordinator', 'urn:registry:payment-adapter', '')); + await collect({ ...bill, billVersion: 2 }, 'original', [409]); + simControl(['advance', '--steps', '1']); + assert.equal((await observe(accepted.collectionId)).body.state, 'pending'); + await report(accepted.collectionId, 'too-early', [409]); + assert.equal((await readBill(bill)).paymentState, 'attempt-bound'); + check('read isolation, changed-key-body refusal and COM/PENDING never release the bill'); + simControl(['advance', '--steps', '1']); simulatorProxy.corrupt(true); + await observe(accepted.collectionId, [502]); await report(accepted.collectionId, 'corrupt-observation', [409]); + simulatorProxy.corrupt(false); + const paid = (await observe(accepted.collectionId)).body; + assert.equal(paid.state, 'confirmed'); assert.deepEqual(paid.money, { value: '25.00', currency: 'USD', scale: 2 }); + registryProxy.drop(`/v1/actions/${fixture.receipt.action}`); + await report(accepted.collectionId, 'receipt', [503]); await restartAdapter(); + const receipt = (await report(accepted.collectionId, 'receipt')).body; + assert.deepEqual((await report(accepted.collectionId, 'new-receipt-key')).body, receipt); + assert.equal(registryProxy.records.filter((record) => record.path === `/v1/actions/${fixture.receipt.action}`).length, 1); + assert.equal((await readBill(bill)).paymentReceiptId, receipt.receiptId); + assert.equal(ledger().payments.length, 1); + await issue(bill, receipt.receiptId, 'issue-once'); await issue(bill, receipt.receiptId, 'issue-twice', [412]); + assert.equal((await readBill(bill)).paymentState, 'issued'); + await exchange('POST', bregOrigin + fixture.receipt.path, { token: readOnlyToken, body: { input: {} }, key: 'unauthorized-report', expected: [404] }); + check('exact-money correlation and lost receipt acknowledgement recover one receipt and one issuance'); + + configuration.connections[0].binding = originalBinding; await privateFile(paymentsPath, configuration); await restartAdapter(); + coordinatorProxy = await relay(adapterOrigin); relays.push(coordinatorProxy); + const packagePath = join(root, 'coordinator-package'); + const packaged = ctl(['package', '--project', join(repository, 'products/coordinator/examples/payment-collections'), '--output', packagePath]); + const coordinatorRuntime = join(root, 'coordinator-runtime.yaml'); + await privateFile(coordinatorRuntime, { apiVersion: 'id.registrystack.org/formats/coordinator/runtime/v1alpha1', kind: 'CoordinatorRuntimeConfig', + secretProviders: { file: { root: secrets } }, database: { runtimeUrlRef: 'secret:file/coordinator-runtime', migrationUrlRef: 'secret:file/coordinator-migration', trustedRootCertificateRef: 'secret:file/postgres-ca' }, + namespace: 'coordinator_payment_native', connections: { 'licence-fees': { type: 'payments', baseUrl: coordinatorProxy.url, paymentConnection: 'licence-fees', resultCheckSeconds: 60, + authorization: { tokenEndpoint: `${issuer.origin}/token`, clientAssertionAudience: issuer.issuer, clientId: 'coordinator-payments', signingKeyRef: 'secret:file/coordinator-payments-jwk', resource: 'urn:registry:payment-adapter', scopes: ['payments:collect'] } } }, + deployment: { databaseId: `coordinator-payment-${suffix}`, runtimeRole: coordinatorDb.runtime, + packages: [{ root: packagePath, expectedDigest: packaged.packageDigest }], listener: { bind: `127.0.0.1:${coordinatorPort}`, tlsTermination: 'development-loopback' }, + authentication: { issuer: issuer.issuer, audience: 'urn:example:coordinator', scopeClaim: 'scope', jwksSource: { type: 'static', documentRef: 'secret:file/jwks' }, + policies: { 'licence-service': { subjects: ['licence-service'], requiredScopes: ['coordinator:start'], workflows: ['payment-collections'], actions: ['start', 'status'] }, + 'payment-operator': { subjects: ['payment-operator'], requiredScopes: ['coordinator:operate'], workflows: ['payment-collections'], actions: ['status', 'inspect', 'reconcile', 'retry-same'], operator: true } } }, + auditFile: join(root, 'coordinator-audit.jsonl'), auditKeyRef: 'secret:file/audit-key', activeStateKey: 1, stateKeys: { '1': { keyRef: 'secret:file/state-key' } }, admissionKeyRef: 'secret:file/admission-key' } }); + ctl(['--runtime-config', coordinatorRuntime, 'check', '--deny-warnings']); + ctl(['--runtime-config', coordinatorRuntime, 'plan']); + const applied = ctl(['--runtime-config', coordinatorRuntime, 'apply']); assert.equal(applied.activation.roleMode, 'split'); + coordinator = start(join(binaries, 'coordinator'), ['--runtime-config', coordinatorRuntime], join(root, 'coordinator.log')); handles.push(coordinator); + await ready(`${coordinatorOrigin}/health`, coordinator); + const caller = issuer.token('licence-service', 'urn:example:coordinator', 'coordinator:start', 'licence-service'); + const operator = issuer.token('payment-operator', 'urn:example:coordinator', 'coordinator:operate', 'payment-operator'); + const contract = (await exchange('GET', `${coordinatorOrigin}/v1/workflows/payment-collections`, { token: caller })).body; + const workflowBill = await createBill('workflow'); + coordinatorProxy.drop('/v1/payments/licence-fees/collections'); + const run = (await exchange('POST', `${coordinatorOrigin}/v1/runs`, { token: caller, key: `run-${suffix}`, + body: { workflow: 'payment-collections', workflowRevision: contract.workflowRevision, input: intent(workflowBill) } })).body; + async function untilPaused({ finish = false } = {}) { + const deadline = Date.now() + 150000; + while (Date.now() < deadline) { + const status = (await exchange('GET', `${coordinatorOrigin}/v1/runs/${run.runId}`, { token: caller })).body; + evidence.coordinatorRun = status; + // A scheduled retry retains attention until the worker proves its outcome. + if (status.state !== 'running' && (!finish || status.state !== 'attention')) return status; + await sleep(500); + } + throw new Error('native Coordinator did not pause or finish within its acceptance budget'); + } + const requestHold = await untilPaused(); + evidence.coordinatorRequestHold = requestHold; + assert.equal(requestHold.state, 'attention'); assert.equal(requestHold.step, 'request-collection'); + assert.equal(requestHold.uncertain, true); assert.equal(ledger().requestCount, 2); + const coordinatorRequest = coordinatorProxy.records.find((record) => record.path === '/v1/payments/licence-fees/collections'); + assert(coordinatorRequest?.key); + const workflowCollection = (await exchange('POST', `${collectionPath}/receipt`, { + token: paymentToken, body: intent(workflowBill), key: coordinatorRequest.key, + })).body; + coordinatorProxy.drop(`/v1/payments/licence-fees/collections/${workflowCollection.collectionId}/record-receipt`); + await exchange('POST', `${coordinatorOrigin}/v1/runs/${run.runId}/reconcile`, { token: operator, body: { reason: 'native-payment-response-loss' } }); + assert.equal(coordinatorProxy.records.filter((record) => record.path === '/v1/payments/licence-fees/collections').length, 1); + assert.equal(ledger().requestCount, 2); + simControl(['advance', '--steps', '2']); + const receiptHold = await untilPaused(); + evidence.coordinatorReceiptHold = receiptHold; + assert.equal(receiptHold.state, 'attention'); assert.equal(receiptHold.step, 'record-receipt'); assert.equal(receiptHold.uncertain, true); + assert.equal((await readBill(workflowBill)).paymentState, 'paid'); + const receiptMutations = registryProxy.records.filter((record) => record.path === `/v1/actions/${fixture.receipt.action}`).length; + await exchange('POST', `${coordinatorOrigin}/v1/runs/${run.runId}/retry-same`, { token: operator, body: { reason: 'native-receipt-response-loss' } }); + const settled = await untilPaused({ finish: true }); + assert(settled && settled.outcome === 'receipt-recorded', 'native Coordinator did not reach the receipt outcome'); + assert.equal(registryProxy.records.filter((record) => record.path === `/v1/actions/${fixture.receipt.action}`).length, receiptMutations); + const receiptSends = coordinatorProxy.records.filter((record) => record.path.endsWith('/record-receipt')); + assert.equal(receiptSends.length, 2); assert.equal(receiptSends[0].key, receiptSends[1].key); + assert.equal(receiptSends[0].bodyHash, receiptSends[1].bodyHash); + assert.equal(settled.output.billId, workflowBill.billId); assert.equal(settled.output.simulation, true); + assert.equal((await readBill(workflowBill)).paymentReceiptId, settled.output.receiptId); + assert(issuer.grants > 0); assert.equal(ledger().payments.length, 2); + await issue(workflowBill, settled.output.receiptId, 'workflow-issue'); + check('native Coordinator request reconciliation, named completion, exact receipt retry and BReg issuance'); + + simControl(['collection-scenario', '--outcome', 'failed']); + const declined = await createBill('declined'); const failed = (await collect(declined, 'declined')).body; + simControl(['advance', '--steps', '2']); assert.equal((await observe(failed.collectionId)).body.state, 'failed'); + const count = ledger().requestCount; + await restartAdapter(); assert.deepEqual((await collect(declined, 'after-decline')).body, failed); + assert.equal(ledger().requestCount, count); await report(failed.collectionId, 'declined-report', [409]); + assert.equal((await readBill(declined)).paymentState, 'attempt-bound'); + check('definitive failure permanently reserves its bill across restart and new command keys'); + + configuration.connections[0].binding.replayWindowSeconds = 1; + await privateFile(paymentsPath, configuration); await restartAdapter(); + const expired = await createBill('expired-recovery'); + simulatorProxy.drop('/rtpRequest'); await collect(expired, 'expired-recovery', [503]); + const expiredCount = ledger().requestCount; await sleep(1100); + configuration.connections[0].binding.replayWindowSeconds = 86400; + await privateFile(paymentsPath, configuration); await restartAdapter(); + const held = await collect(expired, 'fresh-key-after-expiry', [409]); + assert.equal(held.body.code, 'adapter.payment.recovery-held'); + assert.equal(ledger().requestCount, expiredCount); + const heldBill = await readBill(expired); + assert.equal(heldBill.paymentState, 'attempt-bound'); + assert.equal((await observe(heldBill.paymentAttemptId)).body.state, 'unknown'); + await report(heldBill.paymentAttemptId, 'held-report', [409]); + check('expired original replay window stays held after restart, config extension and a new command key'); + await independentStores(originalConfiguration); + evidence.provider = ledger(); evidence.providerCommands = simulatorProxy.records; + evidence.registryCommands = registryProxy.records; evidence.coordinatorRun = settled; + evidence.coordinatorCommands = coordinatorProxy.records; + evidence.registryPackage = { digest: fixture.packageDigest, schemaFingerprint: fixture.schemaFingerprint }; +} finally { + if (simulatorProxy) evidence.providerCommands = simulatorProxy.records; + if (registryProxy) evidence.registryCommands = registryProxy.records; + if (coordinatorProxy) evidence.coordinatorCommands = coordinatorProxy.records; + const stopped = await Promise.allSettled(handles.reverse().map((handle) => handle.stop())); + const closed = await Promise.allSettled([...relays.reverse().map((proxy) => proxy.close()), ...(issuer ? [issuer.close()] : [])]); + evidence.shutdown = [...stopped, ...closed].every((result) => result.status === 'fulfilled') ? 'passed' : 'failed'; + await privateFile(join(root, 'progress.json'), evidence); + assert.equal(evidence.shutdown, 'passed', 'native fixture shutdown failed; inspect owned process logs'); +} +evidence.result = 'passed'; +await privateFile(join(root, 'acceptance.json'), evidence); +console.log(`Native payment acceptance passed: ${evidence.checks.length} checks. Private evidence: ${join(root, 'acceptance.json')}`); diff --git a/products/adapter/scripts/test_dependency_direction.py b/products/adapter/scripts/test_dependency_direction.py index adaeec4321..347c73a0ca 100755 --- a/products/adapter/scripts/test_dependency_direction.py +++ b/products/adapter/scripts/test_dependency_direction.py @@ -16,6 +16,8 @@ SPEC.loader.exec_module(MODULE) NAMES = { + "payment-protocol": "registry-payment-protocol", + "payment-provider": "registry-payment-simulator-connector", "engine": "registry-adapter", "shared-engine": "registry-adapter-engine", "core": "registry-adapter-core", @@ -51,6 +53,8 @@ } INTENDED = { + "payment-protocol": ["serde"], + "payment-provider": ["payment-protocol", "platform", "serde"], "engine": ["shared-engine", "core", "platform", "platform-script", "serde", ("platform-testing", "dev")], "shared-engine": ["core", "platform", "platform-script", "serde"], "core": ["platform", "serde"], @@ -163,6 +167,19 @@ def failures(**changes: list) -> str: class EngineTests(unittest.TestCase): + def test_only_the_payment_host_reaches_the_payment_contract_and_breg_client(self): + graph = metadata(engine=[*INTENDED["engine"], "payment-protocol", "payment-provider", "breg-client"]) + self.assertEqual(MODULE.violations(graph), []) + for owner in ("shared-engine", "core", "job"): + for payment in ("payment-protocol", "payment-provider", "breg-client"): + with self.subTest(owner=owner, payment=payment): + self.assertIn(NAMES[payment], failures(**{owner: [*INTENDED[owner], payment]})) + + def test_payment_provider_remains_independent_of_product_clients_and_runtimes(self): + for dependency in ("breg-client", "breg", "coordinator", "engine"): + with self.subTest(dependency=dependency): + self.assertIn(NAMES[dependency], failures(payment_provider=[*INTENDED["payment-provider"], dependency])) + def test_the_extracted_engine_crate_is_an_accepted_engine_boundary(self): self.assertEqual(MODULE.violations(metadata()), []) @@ -201,7 +218,7 @@ def test_an_engine_crate_reaching_a_product_client_is_refused(self): with self.subTest(client=client): self.assertIn( NAMES[client], - failures(engine=[*INTENDED["engine"], client]), + failures(shared_engine=[*INTENDED["shared-engine"], client]), ) def test_an_engine_crate_reaching_the_connector_crate_is_refused(self): @@ -221,7 +238,7 @@ def test_an_engine_crate_reaching_adopter_tooling_is_refused(self): def test_a_dev_dependency_of_an_engine_crate_counts(self): self.assertIn( "registry-breg-client", - failures(engine=[*INTENDED["engine"], ("breg-client", "dev")]), + failures(shared_engine=[*INTENDED["shared-engine"], ("breg-client", "dev")]), ) def test_a_dev_dependency_of_a_reached_platform_crate_is_not_followed(self): @@ -438,7 +455,7 @@ def test_an_accepted_graph_exits_zero(self): self.assertEqual(completed.stderr, "") def test_a_violation_exits_one_and_names_it(self): - completed = self.run_gate(metadata(engine=[*INTENDED["engine"], "breg-client"])) + completed = self.run_gate(metadata(engine=[*INTENDED["engine"], "coordinator"])) self.assertEqual(completed.returncode, 1) self.assertIn("dependency-direction violation: registry-adapter", completed.stderr) diff --git a/products/breg/examples/payment-fee-issuance/README.md b/products/breg/examples/payment-fee-issuance/README.md new file mode 100644 index 0000000000..445f76987c --- /dev/null +++ b/products/breg/examples/payment-fee-issuance/README.md @@ -0,0 +1,224 @@ +# Payment-gated service issuance + +This synthetic example keeps the authoritative fee and issuance decision in +BReg while the Payment Adapter owns provider identifiers, retries, pending or +unknown outcomes, and its receipt-reporting journal in PostgreSQL. It does not +turn BReg into a provider queue. + +`create-fee-bill` applies the service-owned `synthetic-licence-fee` tariff. It +creates one bill at version 1 for USD 25.00, represented exactly as 2500 minor +units with currency scale 2. The unique +`(institution-id, service-id, request-id)` constraint prevents a fresh workflow +from creating another bill UUID for the same service request. The BReg record +root UUID is the payment protocol's `billId`. The `bill-version` field is the +protocol's positive domain `billVersion`; it is not the BReg record revision or +HTTP condition. + +Every Action that changes an existing bill also requires BReg target +conditions captured immediately before the attempted transition. That opaque +condition carries the current BReg document revision and prevents a concurrent +mutation from committing against a stale read. It is deliberately separate +from the service-owned `bill-version`, which remains an explicit Action input +and exact stored-field guard. + +The authorised service supplies `bill-digest` as its opaque commitment to the +frozen bill facts. BReg requires exactly 64 characters, stores it, and compares it +exactly in every later Action. BReg does not recompute SHA-256 or RFC 8785 JCS. +The Adapter must independently hash and retain its full exact intent snapshot, +and the binding and receipt Actions compare every financial and identity fact +even when the digest matches. + +## Guarded state transitions + +The bill moves only through these Action-owned transitions: + +1. `create-fee-bill`: absent to `due-unbound`. +2. `bind-payment-attempt`: `due-unbound` to `attempt-bound`, atomically + freezing `payment-attempt-id` and `provider-binding-revision` before provider + dispatch. +3. `record-payment-receipt`: `attempt-bound` to `paid`, after exact comparison + of institution, service, request, tariff identity/version/digest, payer, + payer financial address, bill version and digest, amount, currency, scale, + simulation flag, payment attempt, and provider binding. +4. `issue-paid-service`: `paid` to `issued`, using only `billId`, expected + `billVersion`, `requestId`, `paymentReceiptId`, and a new `issuanceId`. The + Action reads the authoritative stored state and cannot replace or reassemble + provider evidence. + +No access profile has CRUD Create or Patch authority. Only the issuance service +can create bills and issue the service. Only the Payment Adapter can bind an +attempt or report a receipt. One Adapter credential can carry both exact +scopes while selecting the separate binder and reporter profiles. The +Coordinator profile is read-only and citizens +have no profile. Once an attempt is bound, Adapter outcomes `pending` and +`unknown` both remain BReg `attempt-bound`; neither creates a route to bind a +second attempt. An exact retry uses the original BReg idempotency key. A new +idempotency key cannot replace the binding or receipt because the state guard +has already advanced. + +The Action invoke routes are: + +- `POST /v1/actions/create-fee-bill?accessProfile=service-biller` +- `POST /v1/actions/bind-payment-attempt?accessProfile=payment-adapter-binder` +- `POST /v1/actions/record-payment-receipt?accessProfile=payment-adapter-reporter` +- `POST /v1/actions/issue-paid-service?accessProfile=service-issuer` + +The exact receipt can be recovered through the normal +`GET /v1/records/service-fee-bills/{billId}` route with +`payment-adapter-reporter`. The Action result named `bill` returns the same +record envelope after each successful transition. + +The HTTP input contracts use these authored camel-case names: + +- `create-fee-bill`, profile `service-biller`, client `issuance-service`, scope + `registry:fee-bill:create`: `institutionId`, `serviceId`, `requestId`, + `payerId`, `payerFinancialAddress`, `billDigest`, `simulation`. +- `bind-payment-attempt`, profile `payment-adapter-binder`, client + `payment-adapter`, scope `registry:payment-attempt:bind`: `billId`, + `billVersion`, `billDigest`, `institutionId`, `serviceId`, `requestId`, + `tariffId`, `tariffVersion`, `tariffDigest`, `payerId`, + `payerFinancialAddress`, `amountMinor`, `currency`, `currencyScale`, + `simulation`, `paymentAttemptId`, `providerBindingRevision`. +- `record-payment-receipt`, profile `payment-adapter-reporter`, client + `payment-adapter`, scope `registry:payment-receipt:report`: every bind input + plus `paymentReceiptId`, `providerReference`, and `receiptDigest`. +- `issue-paid-service`, profile `service-issuer`, client `issuance-service`, + scope `registry:paid-service:issue`: `billId`, `billVersion`, `requestId`, + `paymentReceiptId`, `issuanceId`. + +Every successful Action response exposes result `bill`, the resulting BReg +record envelope. Exact readback uses profile `payment-adapter-reporter`, client +`payment-adapter`, and scope `registry:payment-receipt:report`. The read-only +Coordinator profile is `coordinator-bill-reader`, client +`service-coordinator`, scope `registry:fee-bill:read`; it receives no Action +permission. + +## Payment protocol mapping + +| BReg field | Payment protocol field | +| --- | --- | +| record root UUID | `billId` | +| `bill-version` | `billVersion` | +| `amount-minor`, `currency`, `currency-scale` | exact `Money.value`, `currency`, `scale` | +| `payment-attempt-id` | `collectionId` | +| `provider-binding-revision` | `bindingRevision` | +| `simulation` | `simulation` | +| `payment-receipt-id` | `receiptId` | +| `provider-reference` | `providerReference` | + +The Adapter converts minor units to canonical decimal text without binary +floating point. The fixture bounds positive minor units and bill versions to +9,007,199,254,740,991, matching the payment protocol's portable JSON integer +limit. Adapter provider configuration must independently allow the bill's +currency and currency scale before dispatch; the BReg Actions then require +those frozen values to remain exact. + +`payer-financial-address` is a frozen synthetic provider address of at most 30 +printable ASCII characters. BReg enforces that persisted pattern and exact +comparison, while the Adapter validates the provider-specific address grammar. +`receipt-digest` is exactly 64 lowercase hexadecimal characters, representing +the Adapter's SHA-256 commitment to its exact receipt object. `payerFiBic` +remains in the provider connection configuration and is not a bill fact. + +## Synthetic and live operation + +The authored journey uses `simulation: true` and synthetic references. BReg +freezes and compares that flag, so a receipt with a different flag cannot +satisfy the bill. BReg trusts the restricted Adapter reporter for provider +facts and cannot detect a compromised reporter relabelling synthetic data. +Live rejection therefore also belongs to Adapter configuration: a live binding +must refuse the simulator or any receipt marked as simulation before invoking +the BReg reporter Action. + +Validate the authored project and its journey with the pinned `bregctl` build +for this branch: + +```sh +bregctl check products/breg/examples/payment-fee-issuance +``` + +The 30-step journey covers duplicate bill creation, unauthorised binding and receipt +reporting through missing scopes, changed bill/version/amount/attempt facts, +simulation mismatch, exact idempotent recovery, pending or unknown guards, +receipt readback, and single-use issuance. The journey reader intentionally +refuses a requester client outside the selected profile even for an expected +404, so native acceptance separately probes the Coordinator credential and an +unauthenticated citizen against both Adapter Actions. Compiler validation does +not prove PostgreSQL uniqueness, authorization, transaction atomicity, or +idempotent replay; those require the native real-PostgreSQL fixture run. + +## Native acceptance and runtime handoff + +[`run-native.sh`](run-native.sh) is the maintained synthetic acceptance helper. +It requires a caller-owned TLS PostgreSQL cluster and absolute paths supplied +through these environment variables: + +- `PAYMENT_FEE_BREGCTL_BIN`: the pinned normal `bregctl` executable. +- `PAYMENT_FEE_BREG_BIN`: the matching normal `breg` executable. +- `PAYMENT_FEE_DATABASE_ADMIN_URL`: an administration URL for the isolated + cluster, including `sslmode=require`, `verify-ca`, or `verify-full`. Inject + credential-bearing values without placing them in shell history. +- `PAYMENT_FEE_POSTGRES_CA_FILE`: the PEM trust root for that server. +- `PAYMENT_FEE_ACCEPTANCE_ROOT`: an existing private directory under which the + helper may create `payment-fee-issuance/runs/`. +- `PAYMENT_FEE_DYLD_FALLBACK_LIBRARY_PATH`: optional macOS dynamic-library + directory required by the pinned binaries. +- `PAYMENT_FEE_DYLD_LIBRARY_PATH`: optional macOS dynamic-library directory + for a preserved binary whose FIPS library is referenced through `@rpath`. +- `PAYMENT_FEE_LISTENER`: optional `127.0.0.1:PORT` override. Otherwise the + helper chooses an available loopback port. +- `PAYMENT_FEE_KEEP_RUNNING`: optional `0` or `1`, default `0`. Set it to `1` + for a joined Adapter and Coordinator run that must retain BReg after the + helper publishes its handoff. +- `PAYMENT_FEE_BREG_FEATURE_PROFILE` and + `PAYMENT_FEE_BREGCTL_FEATURE_PROFILE`: optional bounded provenance labels, + default `unspecified`. Set these from the pinned build metadata rather than + inferring compile-time features from a filename. + +The helper creates unique schema-test and runtime databases, with separate +non-administrative migration and runtime roles. It preserves all existing +databases and services and deliberately does not delete its own databases or +roles after a run. It executes the maintained sequence `check`, `test`, +`package`, `plan`, `apply`, and `status`, then starts the matching `breg` +process. Every command report is retained under the private run directory. +The private `reports/binary-provenance.json` and handoff record each binary's +absolute path, SHA-256 digest, version output, and supplied feature-profile +label. +With `PAYMENT_FEE_KEEP_RUNNING=1`, the helper prints the completed handoff and +then waits in the foreground for its own BReg child. Keep that terminal or +managed session open for the joined run. Sending `TERM` or `INT` to the helper +forwards the signal only to that owned child PID and waits for it to finish. +Closing the retained terminal can send `HUP` to the helper. Because its +`nohup`-launched child ignores `HUP`, the helper deliberately maps parent +`HUP` to child `TERM`, then waits for that same owned PID to finish. The +default `0` preserves the non-waiting handoff behavior. + +On success, the helper prints only the path to its owner-readable +`handoff.json`. The stable pointer +`payment-fee-issuance/latest-run` contains the private run-directory path. The +handoff names the loopback base URL, package root and digest, schema +fingerprint, runtime configuration, process ID file, action routes and +profiles, selected helper lifetime mode, and these credential references: + +- `secrets/payment-adapter-token`: client `payment-adapter`, purpose + `payment-processing`, with only `registry:payment-attempt:bind` and + `registry:payment-receipt:report`. +- `secrets/issuance-service-token`: client `issuance-service`, purpose + `service-issuance`, with only `registry:fee-bill:create` and + `registry:paid-service:issue`. +- `secrets/service-coordinator-token`: client `service-coordinator`, purpose + `service-orchestration`, with only `registry:fee-bill:read`. + +These are synthetic acceptance credentials, not deployment credentials. The +helper generates a run-local Ed25519 key and static JWKS, writes every key and +token owner-only, and issues JWTs for at most 7,200 seconds. Tokens bind the +configured issuer and audience plus `client_id`, `sub`, `jti`, +`registry_actor_kind`, `registry_principal`, `registry_purpose`, and the exact +space-separated `scope` claim. The Coordinator receives no bind or receipt +scope. The runtime additionally probes that its credential sees both Adapter +Action routes as `404 resource.not_found` and that an unauthenticated caller +receives `401`. + +The schema test uses additional one-scope token files for each Action profile, +so every journey step proves its declared authority without relying on a +broader combined runtime credential. diff --git a/products/breg/examples/payment-fee-issuance/lifecycle.sh b/products/breg/examples/payment-fee-issuance/lifecycle.sh new file mode 100644 index 0000000000..9a0731acd0 --- /dev/null +++ b/products/breg/examples/payment-fee-issuance/lifecycle.sh @@ -0,0 +1,41 @@ +#!/usr/bin/env bash + +# Wait for a child started by the current shell. TERM and INT received while +# waiting are forwarded only to that child PID. HUP is mapped to TERM because +# the child is launched through nohup and deliberately ignores HUP. No signal +# is sent to its process group or another service on the host. +payment_fee_wait_for_owned_child() { + local payment_fee_owned_child_pid=$1 + local payment_fee_forwarded_signal= + local interrupted_status= + local status + + [[ "$payment_fee_owned_child_pid" =~ ^[1-9][0-9]*$ ]] || { + printf 'Refusing to wait for an invalid owned child PID\n' >&2 + return 2 + } + + trap 'payment_fee_forwarded_signal=TERM; kill -TERM "$payment_fee_owned_child_pid" 2>/dev/null || true' TERM + trap 'payment_fee_forwarded_signal=INT; kill -INT "$payment_fee_owned_child_pid" 2>/dev/null || true' INT + trap 'payment_fee_forwarded_signal=HUP; kill -TERM "$payment_fee_owned_child_pid" 2>/dev/null || true' HUP + + while :; do + if wait "$payment_fee_owned_child_pid"; then + status=0 + else + status=$? + fi + if [[ -n "$payment_fee_forwarded_signal" && "$status" -ge 128 ]]; then + interrupted_status=$status + payment_fee_forwarded_signal= + continue + fi + if [[ "$status" -eq 127 && -n "$interrupted_status" ]]; then + status=$interrupted_status + fi + break + done + + trap - HUP TERM INT + return "$status" +} diff --git a/products/breg/examples/payment-fee-issuance/registry.yaml b/products/breg/examples/payment-fee-issuance/registry.yaml new file mode 100644 index 0000000000..ba14a8f818 --- /dev/null +++ b/products/breg/examples/payment-fee-issuance/registry.yaml @@ -0,0 +1,347 @@ +# yaml-language-server: $schema=https://id.registrystack.org/schemas/breg/project/project.v1alpha1.schema.json +apiVersion: id.registrystack.org/formats/breg/project/v1alpha1 +kind: BRegProject +project: + id: payment-fee-issuance + canonicalBaseIri: https://payment-fee-issuance.example.test + version: 0.1.0 + defaultLanguage: en + display: + label: Payment-gated service issuance + description: A synthetic fee-before-issuance registry with one authoritative bill and one bound collection attempt. + +package: + sourceRevision: payment-fee-issuance-0.1.0 + +datasets: + - id: service-billing + display: + label: Service billing + description: Authoritative service fee, collection binding, receipt, and single-use issuance facts. + +vocabularies: + - id: payment-state + values: [due-unbound, attempt-bound, paid, issued] + +recordTypes: + - id: service-fee-bill + route: service-fee-bills + primaryDataset: service-billing + mutationMode: mutable + constraints: + - id: one-bill-per-service-request + type: unique + fields: [institution-id, service-id, request-id] + - id: payment-attempt-id-unique + type: unique + fields: [payment-attempt-id] + - id: payment-receipt-id-unique + type: unique + fields: [payment-receipt-id] + - id: issuance-id-unique + type: unique + fields: [issuance-id] + - id: portable-positive-bill-version + type: int-range + field: bill-version + minimum: 1 + maximum: 9007199254740991 + - id: portable-positive-amount-minor + type: int-range + field: amount-minor + minimum: 1 + maximum: 9007199254740991 + - id: portable-currency-scale + type: int-range + field: currency-scale + minimum: 0 + maximum: 6 + display: + label: Service fee bill + description: One service-owned bill whose collection binding, exact receipt, and issuance are immutable state transitions. + fields: + - {id: institution-id, apiName: institutionId, type: string, required: true, minimumLength: 1, maximumLength: 128, classification: internal} + - {id: service-id, apiName: serviceId, type: string, required: true, minimumLength: 1, maximumLength: 128, classification: internal} + - {id: request-id, apiName: requestId, type: string, required: true, minimumLength: 1, maximumLength: 128, classification: internal} + - {id: payer-id, apiName: payerId, type: string, required: true, minimumLength: 1, maximumLength: 128, classification: restricted} + - {id: payer-financial-address, apiName: payerFinancialAddress, type: string, required: true, minimumLength: 1, maximumLength: 30, pattern: '^[ -~]{1,30}$', classification: restricted} + - {id: tariff-id, apiName: tariffId, type: string, required: true, minimumLength: 1, maximumLength: 128, classification: internal} + - {id: tariff-version, apiName: tariffVersion, type: int64, required: true, classification: internal} + - {id: tariff-digest, apiName: tariffDigest, type: string, required: true, minimumLength: 64, maximumLength: 64, classification: internal} + - {id: bill-version, apiName: billVersion, type: int64, required: true, classification: internal} + - {id: bill-digest, apiName: billDigest, type: string, required: true, minimumLength: 64, maximumLength: 64, classification: internal} + - {id: amount-minor, apiName: amountMinor, type: int64, required: true, classification: internal} + - {id: currency, type: string, required: true, minimumLength: 3, maximumLength: 3, classification: internal} + - {id: currency-scale, apiName: currencyScale, type: int64, required: true, classification: internal} + - {id: simulation, type: boolean, required: true, classification: internal} + - {id: payment-state, apiName: paymentState, type: vocabulary-code, vocabulary: payment-state, required: true, classification: internal} + - {id: payment-attempt-id, apiName: paymentAttemptId, type: uuid, required: false, classification: internal} + - {id: provider-binding-revision, apiName: providerBindingRevision, type: string, required: false, minimumLength: 1, maximumLength: 128, classification: internal} + - {id: payment-receipt-id, apiName: paymentReceiptId, type: string, required: false, minimumLength: 1, maximumLength: 128, classification: internal} + - {id: provider-reference, apiName: providerReference, type: string, required: false, minimumLength: 1, maximumLength: 128, classification: internal} + - {id: receipt-digest, apiName: receiptDigest, type: string, required: false, minimumLength: 64, maximumLength: 64, pattern: '^[0-9a-f]{64}$', classification: internal} + - {id: issuance-id, apiName: issuanceId, type: uuid, required: false, classification: internal} + +actions: + - id: create-fee-bill + display: + label: Create service fee bill + description: Create the one authoritative bill for a service request from the service-owned synthetic tariff. + execution: {mode: immediate} + inputs: + - {id: institution-id, apiName: institutionId, type: string, required: true, minimumLength: 1, maximumLength: 128, classification: internal} + - {id: service-id, apiName: serviceId, type: string, required: true, minimumLength: 1, maximumLength: 128, classification: internal} + - {id: request-id, apiName: requestId, type: string, required: true, minimumLength: 1, maximumLength: 128, classification: internal} + - {id: payer-id, apiName: payerId, type: string, required: true, minimumLength: 1, maximumLength: 128, classification: restricted} + - {id: payer-financial-address, apiName: payerFinancialAddress, type: string, required: true, minimumLength: 1, maximumLength: 30, pattern: '^[ -~]{1,30}$', classification: restricted} + - {id: bill-digest, apiName: billDigest, type: string, required: true, minimumLength: 64, maximumLength: 64, classification: internal} + - {id: simulation, type: boolean, required: true, classification: internal} + plan: + type: fixed + effects: + - id: bill + target: {recordType: service-fee-bill} + operation: create + set: + institution-id: {fromInput: institution-id} + service-id: {fromInput: service-id} + request-id: {fromInput: request-id} + payer-id: {fromInput: payer-id} + payer-financial-address: {fromInput: payer-financial-address} + tariff-id: {value: synthetic-licence-fee} + tariff-version: {value: 1} + tariff-digest: {value: cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc} + bill-version: {value: 1} + bill-digest: {fromInput: bill-digest} + amount-minor: {value: 2500} + currency: {value: USD} + currency-scale: {value: 2} + simulation: {fromInput: simulation} + payment-state: {value: due-unbound} + + - id: bind-payment-attempt + display: + label: Bind payment collection attempt + description: Freeze one Adapter collection and provider binding before provider dispatch. + execution: {mode: immediate} + inputs: + - {id: bill, apiName: billId, type: reference, target: service-fee-bill, required: true, classification: internal} + - {id: bill-version, apiName: billVersion, type: int64, required: true, classification: internal} + - {id: bill-digest, apiName: billDigest, type: string, required: true, minimumLength: 64, maximumLength: 64, classification: internal} + - {id: institution-id, apiName: institutionId, type: string, required: true, minimumLength: 1, maximumLength: 128, classification: internal} + - {id: service-id, apiName: serviceId, type: string, required: true, minimumLength: 1, maximumLength: 128, classification: internal} + - {id: request-id, apiName: requestId, type: string, required: true, minimumLength: 1, maximumLength: 128, classification: internal} + - {id: tariff-id, apiName: tariffId, type: string, required: true, minimumLength: 1, maximumLength: 128, classification: internal} + - {id: tariff-version, apiName: tariffVersion, type: int64, required: true, classification: internal} + - {id: tariff-digest, apiName: tariffDigest, type: string, required: true, minimumLength: 64, maximumLength: 64, classification: internal} + - {id: payer-id, apiName: payerId, type: string, required: true, minimumLength: 1, maximumLength: 128, classification: restricted} + - {id: payer-financial-address, apiName: payerFinancialAddress, type: string, required: true, minimumLength: 1, maximumLength: 30, pattern: '^[ -~]{1,30}$', classification: restricted} + - {id: amount-minor, apiName: amountMinor, type: int64, required: true, classification: internal} + - {id: currency, type: string, required: true, minimumLength: 3, maximumLength: 3, classification: internal} + - {id: currency-scale, apiName: currencyScale, type: int64, required: true, classification: internal} + - {id: simulation, type: boolean, required: true, classification: internal} + - {id: payment-attempt-id, apiName: paymentAttemptId, type: uuid, required: true, classification: internal} + - {id: provider-binding-revision, apiName: providerBindingRevision, type: string, required: true, minimumLength: 1, maximumLength: 128, classification: internal} + commitGuards: + targets: + - {input: bill, field: payment-state, equals: due-unbound, reason: bill-not-due-unbound} + - {input: bill, field: bill-version, equalsFromInput: bill-version} + - {input: bill, field: bill-digest, equalsFromInput: bill-digest} + - {input: bill, field: institution-id, equalsFromInput: institution-id} + - {input: bill, field: service-id, equalsFromInput: service-id} + - {input: bill, field: request-id, equalsFromInput: request-id} + - {input: bill, field: tariff-id, equalsFromInput: tariff-id} + - {input: bill, field: tariff-version, equalsFromInput: tariff-version} + - {input: bill, field: tariff-digest, equalsFromInput: tariff-digest} + - {input: bill, field: payer-id, equalsFromInput: payer-id} + - {input: bill, field: payer-financial-address, equalsFromInput: payer-financial-address} + - {input: bill, field: amount-minor, equalsFromInput: amount-minor} + - {input: bill, field: currency, equalsFromInput: currency} + - {input: bill, field: currency-scale, equalsFromInput: currency-scale} + - {input: bill, field: simulation, equalsFromInput: simulation} + plan: + type: fixed + effects: + - id: bill + target: {fromInput: bill} + operation: patch + set: + payment-attempt-id: {fromInput: payment-attempt-id} + provider-binding-revision: {fromInput: provider-binding-revision} + payment-state: {value: attempt-bound} + + - id: record-payment-receipt + display: + label: Record exact payment receipt + description: Record one receipt only when every bill, collection, provider, and money fact matches the frozen binding. + execution: {mode: immediate} + inputs: + - {id: bill, apiName: billId, type: reference, target: service-fee-bill, required: true, classification: internal} + - {id: bill-version, apiName: billVersion, type: int64, required: true, classification: internal} + - {id: bill-digest, apiName: billDigest, type: string, required: true, minimumLength: 64, maximumLength: 64, classification: internal} + - {id: institution-id, apiName: institutionId, type: string, required: true, minimumLength: 1, maximumLength: 128, classification: internal} + - {id: service-id, apiName: serviceId, type: string, required: true, minimumLength: 1, maximumLength: 128, classification: internal} + - {id: request-id, apiName: requestId, type: string, required: true, minimumLength: 1, maximumLength: 128, classification: internal} + - {id: tariff-id, apiName: tariffId, type: string, required: true, minimumLength: 1, maximumLength: 128, classification: internal} + - {id: tariff-version, apiName: tariffVersion, type: int64, required: true, classification: internal} + - {id: tariff-digest, apiName: tariffDigest, type: string, required: true, minimumLength: 64, maximumLength: 64, classification: internal} + - {id: payer-id, apiName: payerId, type: string, required: true, minimumLength: 1, maximumLength: 128, classification: restricted} + - {id: payer-financial-address, apiName: payerFinancialAddress, type: string, required: true, minimumLength: 1, maximumLength: 30, pattern: '^[ -~]{1,30}$', classification: restricted} + - {id: amount-minor, apiName: amountMinor, type: int64, required: true, classification: internal} + - {id: currency, type: string, required: true, minimumLength: 3, maximumLength: 3, classification: internal} + - {id: currency-scale, apiName: currencyScale, type: int64, required: true, classification: internal} + - {id: simulation, type: boolean, required: true, classification: internal} + - {id: payment-attempt-id, apiName: paymentAttemptId, type: uuid, required: true, classification: internal} + - {id: provider-binding-revision, apiName: providerBindingRevision, type: string, required: true, minimumLength: 1, maximumLength: 128, classification: internal} + - {id: payment-receipt-id, apiName: paymentReceiptId, type: string, required: true, minimumLength: 1, maximumLength: 128, classification: internal} + - {id: provider-reference, apiName: providerReference, type: string, required: true, minimumLength: 1, maximumLength: 128, classification: internal} + - {id: receipt-digest, apiName: receiptDigest, type: string, required: true, minimumLength: 64, maximumLength: 64, pattern: '^[0-9a-f]{64}$', classification: internal} + commitGuards: + targets: + - {input: bill, field: payment-state, equals: attempt-bound, reason: bill-not-attempt-bound} + - {input: bill, field: bill-version, equalsFromInput: bill-version} + - {input: bill, field: bill-digest, equalsFromInput: bill-digest} + - {input: bill, field: institution-id, equalsFromInput: institution-id} + - {input: bill, field: service-id, equalsFromInput: service-id} + - {input: bill, field: request-id, equalsFromInput: request-id} + - {input: bill, field: tariff-id, equalsFromInput: tariff-id} + - {input: bill, field: tariff-version, equalsFromInput: tariff-version} + - {input: bill, field: tariff-digest, equalsFromInput: tariff-digest} + - {input: bill, field: payer-id, equalsFromInput: payer-id} + - {input: bill, field: payer-financial-address, equalsFromInput: payer-financial-address} + - {input: bill, field: amount-minor, equalsFromInput: amount-minor} + - {input: bill, field: currency, equalsFromInput: currency} + - {input: bill, field: currency-scale, equalsFromInput: currency-scale} + - {input: bill, field: simulation, equalsFromInput: simulation} + - {input: bill, field: payment-attempt-id, equalsFromInput: payment-attempt-id} + - {input: bill, field: provider-binding-revision, equalsFromInput: provider-binding-revision} + plan: + type: fixed + effects: + - id: bill + target: {fromInput: bill} + operation: patch + set: + payment-receipt-id: {fromInput: payment-receipt-id} + provider-reference: {fromInput: provider-reference} + receipt-digest: {fromInput: receipt-digest} + payment-state: {value: paid} + + - id: issue-paid-service + display: + label: Issue paid service + description: Mark the service request issued once, only for its exact paid bill and receipt. + execution: {mode: immediate} + inputs: + - {id: bill, apiName: billId, type: reference, target: service-fee-bill, required: true, classification: internal} + - {id: bill-version, apiName: billVersion, type: int64, required: true, classification: internal} + - {id: request-id, apiName: requestId, type: string, required: true, minimumLength: 1, maximumLength: 128, classification: internal} + - {id: payment-receipt-id, apiName: paymentReceiptId, type: string, required: true, minimumLength: 1, maximumLength: 128, classification: internal} + - {id: issuance-id, apiName: issuanceId, type: uuid, required: true, classification: internal} + commitGuards: + targets: + - {input: bill, field: payment-state, equals: paid, reason: exact-receipt-required} + - {input: bill, field: bill-version, equalsFromInput: bill-version} + - {input: bill, field: request-id, equalsFromInput: request-id} + - {input: bill, field: payment-receipt-id, equalsFromInput: payment-receipt-id} + - {input: bill, field: tariff-id, equals: synthetic-licence-fee} + - {input: bill, field: tariff-version, equals: 1} + - {input: bill, field: tariff-digest, equals: cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc} + - {input: bill, field: amount-minor, equals: 2500} + - {input: bill, field: currency, equals: USD} + - {input: bill, field: currency-scale, equals: 2} + - {input: bill, field: simulation, equals: true} + plan: + type: fixed + effects: + - id: bill + target: {fromInput: bill} + operation: patch + set: + issuance-id: {fromInput: issuance-id} + payment-state: {value: issued} + +accessProfiles: + - id: service-biller + actorKind: service + principalClaim: registry_principal + requesterClients: [issuance-service] + requiredScopes: [registry:fee-bill:create] + requiredPurposes: [service-issuance] + permissions: + actions: + - action: create-fee-bill + operations: [invoke] + targets: + - {recordType: service-fee-bill, rowBoundaries: unrestricted} + results: [bill] + + - id: service-issuer + actorKind: service + principalClaim: registry_principal + requesterClients: [issuance-service] + requiredScopes: [registry:paid-service:issue] + requiredPurposes: [service-issuance] + permissions: + records: + - recordType: service-fee-bill + operations: [get] + readableFields: [institution-id, service-id, request-id, payer-id, payer-financial-address, tariff-id, tariff-version, tariff-digest, bill-version, bill-digest, amount-minor, currency, currency-scale, simulation, payment-state, payment-attempt-id, provider-binding-revision, payment-receipt-id, provider-reference, receipt-digest, issuance-id] + rowBoundaries: unrestricted + actions: + - action: issue-paid-service + operations: [invoke] + targets: + - {recordType: service-fee-bill, rowBoundaries: unrestricted} + results: [bill] + + - id: payment-adapter-binder + actorKind: service + principalClaim: registry_principal + requesterClients: [payment-adapter] + requiredScopes: [registry:payment-attempt:bind] + requiredPurposes: [payment-processing] + permissions: + records: + - recordType: service-fee-bill + operations: [get] + readableFields: [institution-id, service-id, request-id, payer-id, payer-financial-address, tariff-id, tariff-version, tariff-digest, bill-version, bill-digest, amount-minor, currency, currency-scale, simulation, payment-state, payment-attempt-id, provider-binding-revision] + rowBoundaries: unrestricted + actions: + - action: bind-payment-attempt + operations: [invoke] + targets: + - {recordType: service-fee-bill, rowBoundaries: unrestricted} + results: [bill] + + - id: payment-adapter-reporter + actorKind: service + principalClaim: registry_principal + requesterClients: [payment-adapter] + requiredScopes: [registry:payment-receipt:report] + requiredPurposes: [payment-processing] + permissions: + records: + - recordType: service-fee-bill + operations: [get] + readableFields: [institution-id, service-id, request-id, payer-id, payer-financial-address, tariff-id, tariff-version, tariff-digest, bill-version, bill-digest, amount-minor, currency, currency-scale, simulation, payment-state, payment-attempt-id, provider-binding-revision, payment-receipt-id, provider-reference, receipt-digest] + rowBoundaries: unrestricted + actions: + - action: record-payment-receipt + operations: [invoke] + targets: + - {recordType: service-fee-bill, rowBoundaries: unrestricted} + results: [bill] + + - id: coordinator-bill-reader + actorKind: service + principalClaim: registry_principal + requesterClients: [service-coordinator] + requiredScopes: [registry:fee-bill:read] + requiredPurposes: [service-orchestration] + permissions: + records: + - recordType: service-fee-bill + operations: [get] + readableFields: [bill-version, payment-state] + rowBoundaries: unrestricted diff --git a/products/breg/examples/payment-fee-issuance/run-native.sh b/products/breg/examples/payment-fee-issuance/run-native.sh new file mode 100755 index 0000000000..b0bf72d0db --- /dev/null +++ b/products/breg/examples/payment-fee-issuance/run-native.sh @@ -0,0 +1,592 @@ +#!/usr/bin/env bash +set -euo pipefail + +# Run the complete synthetic native acceptance against a caller-owned TLS +# PostgreSQL cluster. The helper creates uniquely named databases and roles. It +# never drops them, resets the cluster, or prints database credentials or JWTs. + +script_dir=$( + python3 - "${BASH_SOURCE[0]}" <<'PY' +import sys +from pathlib import Path + +print(Path(sys.argv[1]).resolve().parent) +PY +) +readonly script_dir +repository_root=$(git --no-optional-locks -C "$script_dir" rev-parse --show-toplevel) +readonly repository_root +readonly fixture="$script_dir" +readonly bregctl=${PAYMENT_FEE_BREGCTL_BIN:-} +readonly breg=${PAYMENT_FEE_BREG_BIN:-} +readonly admin_url=${PAYMENT_FEE_DATABASE_ADMIN_URL:-} +readonly postgres_ca_source=${PAYMENT_FEE_POSTGRES_CA_FILE:-} +readonly acceptance_root=${PAYMENT_FEE_ACCEPTANCE_ROOT:-} +readonly listener_override=${PAYMENT_FEE_LISTENER:-} +readonly keep_running=${PAYMENT_FEE_KEEP_RUNNING:-0} +readonly breg_feature_profile=${PAYMENT_FEE_BREG_FEATURE_PROFILE:-unspecified} +readonly bregctl_feature_profile=${PAYMENT_FEE_BREGCTL_FEATURE_PROFILE:-unspecified} +readonly issuer=https://issuer.example.test/payment-fee-issuance +readonly audience=urn:breg:payment-fee-issuance + +# Resolved beside this helper after path validation. +# shellcheck disable=SC1091 +source "$script_dir/lifecycle.sh" + +refuse() { + printf 'Refusing: %s\n' "$1" >&2 + exit 2 +} + +for required in \ + PAYMENT_FEE_BREGCTL_BIN \ + PAYMENT_FEE_BREG_BIN \ + PAYMENT_FEE_DATABASE_ADMIN_URL \ + PAYMENT_FEE_POSTGRES_CA_FILE \ + PAYMENT_FEE_ACCEPTANCE_ROOT; do + [[ -n "${!required:-}" ]] || refuse "$required is required" +done + +[[ "$keep_running" == "0" || "$keep_running" == "1" ]] || + refuse "PAYMENT_FEE_KEEP_RUNNING must be 0 or 1" +[[ "$breg_feature_profile" =~ ^[a-z0-9][a-z0-9,._+-]{0,127}$ ]] || + refuse "PAYMENT_FEE_BREG_FEATURE_PROFILE must be a bounded lowercase feature label" +[[ "$bregctl_feature_profile" =~ ^[a-z0-9][a-z0-9,._+-]{0,127}$ ]] || + refuse "PAYMENT_FEE_BREGCTL_FEATURE_PROFILE must be a bounded lowercase feature label" + +for path in "$bregctl" "$breg" "$postgres_ca_source" "$acceptance_root"; do + [[ "$path" == /* && "$path" != *$'\n'* && "$path" != */../* && "$path" != */.. ]] || + refuse "all binary, CA, and acceptance-root paths must be absolute lexical paths" +done +[[ -x "$bregctl" && -f "$bregctl" ]] || refuse "PAYMENT_FEE_BREGCTL_BIN must name an executable file" +[[ -x "$breg" && -f "$breg" ]] || refuse "PAYMENT_FEE_BREG_BIN must name an executable file" +[[ -f "$postgres_ca_source" && ! -L "$postgres_ca_source" ]] || + refuse "PAYMENT_FEE_POSTGRES_CA_FILE must name a regular non-symlink file" +[[ -d "$acceptance_root" && ! -L "$acceptance_root" ]] || + refuse "PAYMENT_FEE_ACCEPTANCE_ROOT must name an existing non-symlink directory" +case "$acceptance_root" in +/ | /tmp | /private/tmp | /var/tmp | /private/var/tmp) + refuse "PAYMENT_FEE_ACCEPTANCE_ROOT must not be a broad shared directory" + ;; +esac + +if [[ -n "${PAYMENT_FEE_DYLD_FALLBACK_LIBRARY_PATH:-}" ]]; then + [[ "$PAYMENT_FEE_DYLD_FALLBACK_LIBRARY_PATH" == /* && -d "$PAYMENT_FEE_DYLD_FALLBACK_LIBRARY_PATH" ]] || + refuse "PAYMENT_FEE_DYLD_FALLBACK_LIBRARY_PATH must name an absolute directory" + export DYLD_FALLBACK_LIBRARY_PATH="$PAYMENT_FEE_DYLD_FALLBACK_LIBRARY_PATH" +fi +if [[ -n "${PAYMENT_FEE_DYLD_LIBRARY_PATH:-}" ]]; then + [[ "$PAYMENT_FEE_DYLD_LIBRARY_PATH" == /* && -d "$PAYMENT_FEE_DYLD_LIBRARY_PATH" ]] || + refuse "PAYMENT_FEE_DYLD_LIBRARY_PATH must name an absolute directory" + export DYLD_LIBRARY_PATH="$PAYMENT_FEE_DYLD_LIBRARY_PATH" +fi +export PGSSLROOTCERT="$postgres_ca_source" + +for command in git jq openssl psql python3 yq; do + command -v "$command" >/dev/null 2>&1 || refuse "$command is required on PATH" +done + +python3 - "$admin_url" <<'PY' +import sys +from urllib.parse import parse_qs, urlsplit + +url = urlsplit(sys.argv[1]) +if url.scheme not in {"postgres", "postgresql"} or not url.hostname or not url.path.strip("/"): + raise SystemExit("PAYMENT_FEE_DATABASE_ADMIN_URL must be a PostgreSQL URL with host and database") +sslmode = parse_qs(url.query).get("sslmode", [""])[-1] +if sslmode not in {"require", "verify-ca", "verify-full"}: + raise SystemExit("PAYMENT_FEE_DATABASE_ADMIN_URL must require TLS with sslmode=require or stronger") +PY + +umask 077 +readonly scratch_root="$acceptance_root/payment-fee-issuance" +run_suffix="$(date -u +%Y%m%dt%H%M%Sz)_$$" +readonly run_suffix +readonly run_root="$scratch_root/runs/$run_suffix" +readonly secrets="$run_root/secrets" +readonly reports="$run_root/reports" +mkdir -p "$secrets" "$reports" "$run_root/audit" "$run_root/empty-package" +chmod 700 "$scratch_root" "$scratch_root/runs" "$run_root" "$secrets" "$reports" "$run_root/audit" "$run_root/empty-package" + +readonly test_database="payment_fee_test_$run_suffix" +readonly runtime_database="payment_fee_runtime_$run_suffix" +readonly test_migration_role="payment_fee_test_m_$run_suffix" +readonly test_runtime_role="payment_fee_test_r_$run_suffix" +readonly runtime_migration_role="payment_fee_live_m_$run_suffix" +readonly runtime_runtime_role="payment_fee_live_r_$run_suffix" +test_password="$(openssl rand -hex 24)" +runtime_password="$(openssl rand -hex 24)" +readonly test_password runtime_password + +derive_database_url() { + local database=$1 + local role=$2 + local password=$3 + python3 - "$admin_url" "$database" "$role" "$password" <<'PY' +import sys +from urllib.parse import quote, urlsplit, urlunsplit + +admin = urlsplit(sys.argv[1]) +database, role, password = sys.argv[2:] +host = admin.hostname if admin.port is None else f"{admin.hostname}:{admin.port}" +userinfo = f"{quote(role, safe='')}:{quote(password, safe='')}" +print(urlunsplit((admin.scheme, f"{userinfo}@{host}", f"/{quote(database, safe='')}", admin.query, ""))) +PY +} + +derive_admin_database_url() { + local database=$1 + python3 - "$admin_url" "$database" <<'PY' +import sys +from urllib.parse import quote, urlsplit, urlunsplit + +admin = urlsplit(sys.argv[1]) +print(urlunsplit((admin.scheme, admin.netloc, f"/{quote(sys.argv[2], safe='')}", admin.query, ""))) +PY +} + +provision_database() { + local database=$1 + local migration_role=$2 + local runtime_role=$3 + local database_url + database_url="$(derive_admin_database_url "$database")" + psql "$admin_url" -v ON_ERROR_STOP=1 -q <"$secrets/test-migration-url" +printf '%s' "$(derive_database_url "$test_database" "$test_runtime_role" "$test_password")" >"$secrets/test-runtime-url" +printf '%s' "$(derive_database_url "$runtime_database" "$runtime_migration_role" "$runtime_password")" >"$secrets/runtime-migration-url" +printf '%s' "$(derive_database_url "$runtime_database" "$runtime_runtime_role" "$runtime_password")" >"$secrets/runtime-runtime-url" +openssl rand -hex 32 >"$secrets/audit-key" +openssl rand -hex 32 >"$secrets/cursor-key" +cp "$postgres_ca_source" "$secrets/postgres-ca" +openssl genpkey -algorithm ED25519 -out "$secrets/oidc-signer.pem" >/dev/null 2>&1 +chmod 600 "$secrets"/* + +python3 - "$secrets/oidc-signer.pem" "$secrets/oidc-jwks" <<'PY' +import base64 +import json +import subprocess +import sys +from pathlib import Path + +der = subprocess.run( + ["openssl", "pkey", "-in", sys.argv[1], "-pubout", "-outform", "DER"], + check=True, + capture_output=True, +).stdout +x = base64.urlsafe_b64encode(der[-32:]).rstrip(b"=").decode("ascii") +jwk = {"alg": "EdDSA", "crv": "Ed25519", "kid": "payment-fee-issuer", "kty": "OKP", "x": x} +Path(sys.argv[2]).write_text(json.dumps({"keys": [jwk]}, sort_keys=True, separators=(",", ":")), encoding="utf-8") +PY + +write_jwt() { + local client_id=$1 + local principal=$2 + local purpose=$3 + local scopes=$4 + local output=$5 + local signing_input="$output.signing-input" + local signature="$output.signature" + python3 - "$issuer" "$audience" "$client_id" "$principal" "$purpose" "$scopes" "$signing_input" <<'PY' +import base64 +import json +import secrets +import sys +import time +from pathlib import Path + +def b64(value): + encoded = json.dumps(value, sort_keys=True, separators=(",", ":")).encode() + return base64.urlsafe_b64encode(encoded).rstrip(b"=").decode("ascii") + +issuer, audience, client_id, principal, purpose, scopes, output = sys.argv[1:] +now = int(time.time()) +claims = { + "aud": audience, + "client_id": client_id, + "exp": now + 7200, + "iat": now, + "iss": issuer, + "jti": f"{client_id}-{principal}-{now}-{secrets.token_hex(8)}", + "registry_actor_kind": "service", + "registry_principal": principal, + "registry_purpose": purpose, + "scope": scopes, + "sub": principal, +} +header = {"alg": "EdDSA", "kid": "payment-fee-issuer", "typ": "JWT"} +Path(output).write_text(f"{b64(header)}.{b64(claims)}", encoding="ascii") +PY + openssl pkeyutl -sign -rawin -inkey "$secrets/oidc-signer.pem" -in "$signing_input" -out "$signature" + python3 - "$signing_input" "$signature" "$output" <<'PY' +import base64 +import sys +from pathlib import Path + +signing_input = Path(sys.argv[1]).read_text(encoding="ascii") +signature = base64.urlsafe_b64encode(Path(sys.argv[2]).read_bytes()).rstrip(b"=").decode("ascii") +Path(sys.argv[3]).write_text(f"{signing_input}.{signature}", encoding="ascii") +PY + chmod 600 "$output" "$signing_input" "$signature" +} + +write_jwt issuance-service synthetic-issuance-service service-issuance \ + 'registry:fee-bill:create registry:paid-service:issue' "$secrets/issuance-service-token" +write_jwt issuance-service synthetic-issuance-service service-issuance \ + 'registry:fee-bill:create' "$secrets/issuance-service-create-token" +write_jwt issuance-service synthetic-issuance-service service-issuance \ + 'registry:paid-service:issue' "$secrets/issuance-service-issue-token" +write_jwt payment-adapter synthetic-payment-adapter payment-processing \ + 'registry:payment-attempt:bind registry:payment-receipt:report' "$secrets/payment-adapter-token" +write_jwt payment-adapter synthetic-payment-adapter payment-processing \ + 'registry:payment-attempt:bind' "$secrets/payment-adapter-bind-token" +write_jwt payment-adapter synthetic-payment-adapter payment-processing \ + 'registry:payment-receipt:report' "$secrets/payment-adapter-report-token" +write_jwt payment-adapter synthetic-unauthorized-adapter payment-processing \ + '' "$secrets/payment-adapter-unauthorized-token" +write_jwt service-coordinator synthetic-coordinator service-orchestration \ + 'registry:fee-bill:read' "$secrets/service-coordinator-token" + +select_free_listener() { + python3 - <<'PY' +import socket +with socket.socket() as sock: + sock.bind(("127.0.0.1", 0)) + print(f"127.0.0.1:{sock.getsockname()[1]}") +PY +} +readonly listener=${listener_override:-$(select_free_listener)} +[[ "$listener" =~ ^127\.0\.0\.1:[1-9][0-9]{0,4}$ ]] || + refuse "PAYMENT_FEE_LISTENER must be a 127.0.0.1 host and port" +readonly base_url="http://$listener" + +render_runtime_config() { + local output=$1 + local package_root=$2 + local runtime_ref=$3 + local migration_ref=$4 + local migration_role=$5 + local runtime_role=$6 + local bind=$7 + local database_id=$8 + cat >"$output" <"$run_root/schema-test-credentials.yaml" <<'EOF' +apiVersion: id.registrystack.org/formats/breg/schema-test-credentials/v1 +kind: BRegSchemaTestCredentials +bindings: + - {journeyId: exact-fee-before-issuance, stepId: create-authoritative-bill, credential: {type: bearer, tokenRef: secret:file/issuance-service-create-token}} + - {journeyId: exact-fee-before-issuance, stepId: capture-bill-condition-after-create, credential: {type: bearer, tokenRef: secret:file/payment-adapter-bind-token}} + - {journeyId: exact-fee-before-issuance, stepId: capture-issue-condition-after-create, credential: {type: bearer, tokenRef: secret:file/issuance-service-issue-token}} + - {journeyId: exact-fee-before-issuance, stepId: fresh-workflow-cannot-create-another-bill, credential: {type: bearer, tokenRef: secret:file/issuance-service-create-token}} + - {journeyId: exact-fee-before-issuance, stepId: issue-before-payment-is-refused, credential: {type: bearer, tokenRef: secret:file/issuance-service-issue-token}} + - {journeyId: exact-fee-before-issuance, stepId: missing-scope-cannot-bind-attempt, credential: {type: bearer, tokenRef: secret:file/payment-adapter-unauthorized-token}} + - {journeyId: exact-fee-before-issuance, stepId: changed-version-cannot-bind, credential: {type: bearer, tokenRef: secret:file/payment-adapter-bind-token}} + - {journeyId: exact-fee-before-issuance, stepId: changed-digest-cannot-bind, credential: {type: bearer, tokenRef: secret:file/payment-adapter-bind-token}} + - {journeyId: exact-fee-before-issuance, stepId: bind-exact-payment-attempt, credential: {type: bearer, tokenRef: secret:file/payment-adapter-bind-token}} + - {journeyId: exact-fee-before-issuance, stepId: capture-bill-condition-after-bind, credential: {type: bearer, tokenRef: secret:file/payment-adapter-report-token}} + - {journeyId: exact-fee-before-issuance, stepId: recover-exact-binding, credential: {type: bearer, tokenRef: secret:file/payment-adapter-bind-token}} + - {journeyId: exact-fee-before-issuance, stepId: capture-bind-condition-after-bind, credential: {type: bearer, tokenRef: secret:file/payment-adapter-bind-token}} + - {journeyId: exact-fee-before-issuance, stepId: capture-issue-condition-after-bind, credential: {type: bearer, tokenRef: secret:file/issuance-service-issue-token}} + - {journeyId: exact-fee-before-issuance, stepId: pending-or-unknown-cannot-bind-second-attempt, credential: {type: bearer, tokenRef: secret:file/payment-adapter-bind-token}} + - {journeyId: exact-fee-before-issuance, stepId: pending-or-unknown-cannot-issue, credential: {type: bearer, tokenRef: secret:file/issuance-service-issue-token}} + - {journeyId: exact-fee-before-issuance, stepId: missing-scope-cannot-report-receipt, credential: {type: bearer, tokenRef: secret:file/payment-adapter-unauthorized-token}} + - {journeyId: exact-fee-before-issuance, stepId: changed-bill-fact-cannot-report-receipt, credential: {type: bearer, tokenRef: secret:file/payment-adapter-report-token}} + - {journeyId: exact-fee-before-issuance, stepId: changed-amount-cannot-report-receipt, credential: {type: bearer, tokenRef: secret:file/payment-adapter-report-token}} + - {journeyId: exact-fee-before-issuance, stepId: changed-attempt-cannot-report-receipt, credential: {type: bearer, tokenRef: secret:file/payment-adapter-report-token}} + - {journeyId: exact-fee-before-issuance, stepId: changed-provider-binding-cannot-report-receipt, credential: {type: bearer, tokenRef: secret:file/payment-adapter-report-token}} + - {journeyId: exact-fee-before-issuance, stepId: simulation-mode-cannot-change-at-receipt, credential: {type: bearer, tokenRef: secret:file/payment-adapter-report-token}} + - {journeyId: exact-fee-before-issuance, stepId: record-exact-synthetic-receipt, credential: {type: bearer, tokenRef: secret:file/payment-adapter-report-token}} + - {journeyId: exact-fee-before-issuance, stepId: recover-exact-receipt, credential: {type: bearer, tokenRef: secret:file/payment-adapter-report-token}} + - {journeyId: exact-fee-before-issuance, stepId: read-exact-receipt-after-lost-acknowledgement, credential: {type: bearer, tokenRef: secret:file/payment-adapter-report-token}} + - {journeyId: exact-fee-before-issuance, stepId: capture-bill-condition-after-receipt, credential: {type: bearer, tokenRef: secret:file/issuance-service-issue-token}} + - {journeyId: exact-fee-before-issuance, stepId: capture-receipt-condition-after-receipt, credential: {type: bearer, tokenRef: secret:file/payment-adapter-report-token}} + - {journeyId: exact-fee-before-issuance, stepId: new-request-identity-cannot-replace-receipt, credential: {type: bearer, tokenRef: secret:file/payment-adapter-report-token}} + - {journeyId: exact-fee-before-issuance, stepId: issue-after-exact-receipt, credential: {type: bearer, tokenRef: secret:file/issuance-service-issue-token}} + - {journeyId: exact-fee-before-issuance, stepId: capture-bill-condition-after-issuance, credential: {type: bearer, tokenRef: secret:file/issuance-service-issue-token}} + - {journeyId: exact-fee-before-issuance, stepId: issuance-is-single-use, credential: {type: bearer, tokenRef: secret:file/issuance-service-issue-token}} +EOF + +run_json() { + local output=$1 + shift + "$bregctl" --format json "$@" >"$output" + jq -e '.ok == true' "$output" >/dev/null +} + +"$bregctl" --version >"$reports/bregctl-version.txt" +"$breg" --version >"$reports/breg-version.txt" +python3 - "$breg" "$bregctl" "$breg_feature_profile" "$bregctl_feature_profile" "$reports" <<'PY' +import hashlib +import json +import sys +from pathlib import Path + +breg, bregctl, breg_profile, bregctl_profile, reports = sys.argv[1:] +reports = Path(reports) + +def binary(binary_path, version_file, feature_profile): + path = Path(binary_path).resolve() + return { + "featureProfile": feature_profile, + "path": str(path), + "sha256": hashlib.sha256(path.read_bytes()).hexdigest(), + "version": (reports / version_file).read_text(encoding="utf-8").strip(), + } + +document = { + "breg": binary(breg, "breg-version.txt", breg_profile), + "bregctl": binary(bregctl, "bregctl-version.txt", bregctl_profile), +} +(reports / "binary-provenance.json").write_text( + json.dumps(document, indent=2, sort_keys=True) + "\n", + encoding="utf-8", +) +PY +git --no-optional-locks -C "$repository_root" rev-parse HEAD >"$reports/source-head.txt" +run_json "$reports/check.json" check "$fixture" +run_json "$reports/test.json" test "$fixture" \ + --runtime-config "$run_root/runtime-test.yaml" \ + --credentials "$run_root/schema-test-credentials.yaml" \ + --output "$run_root/schema-test-receipt.json" +schema_fingerprint=$(jq -er '.schemaFingerprint' "$reports/test.json") +readonly schema_fingerprint +run_json "$reports/package.json" package "$fixture" \ + --schema-fingerprint "$schema_fingerprint" \ + --test-receipt "$run_root/schema-test-receipt.json" \ + --output "$run_root/package-build" \ + --revision "payment-fee-issuance-$run_suffix" +package_digest=$(jq -er '.packageDigest' "$reports/package.json") +readonly package_digest + +render_runtime_config "$run_root/runtime.yaml" "$run_root/package-build/package" \ + secret:file/runtime-runtime-url secret:file/runtime-migration-url \ + "$runtime_migration_role" "$runtime_runtime_role" "$listener" "payment-fee-runtime-$run_suffix" +run_json "$reports/plan.json" plan \ + --runtime-config "$run_root/runtime.yaml" \ + --package "$run_root/package-build/package" \ + --expected-digest "$package_digest" +run_json "$reports/apply.json" apply \ + --runtime-config "$run_root/runtime.yaml" \ + --package "$run_root/package-build/package" \ + --initial \ + --operator-reference payment-fee-issuance-native-acceptance \ + --expected-digest "$package_digest" +run_json "$reports/status.json" status --runtime-config "$run_root/runtime.yaml" + +breg_pid= +stop_failed_launch() { + local exit_code=$? + if [[ "$exit_code" -ne 0 && -n "$breg_pid" ]] && kill -0 "$breg_pid" 2>/dev/null; then + kill "$breg_pid" 2>/dev/null || true + fi +} +trap stop_failed_launch EXIT +launch_environment=(BREG_LOG=info) +if [[ -n "${PAYMENT_FEE_DYLD_FALLBACK_LIBRARY_PATH:-}" ]]; then + launch_environment+=("DYLD_FALLBACK_LIBRARY_PATH=$PAYMENT_FEE_DYLD_FALLBACK_LIBRARY_PATH") +fi +if [[ -n "${PAYMENT_FEE_DYLD_LIBRARY_PATH:-}" ]]; then + launch_environment+=("DYLD_LIBRARY_PATH=$PAYMENT_FEE_DYLD_LIBRARY_PATH") +fi +nohup env "${launch_environment[@]}" "$breg" --runtime-config "$run_root/runtime.yaml" >"$reports/breg.log" 2>&1 & +breg_pid=$! +printf '%s\n' "$breg_pid" >"$run_root/breg.pid" + +python3 - "$base_url/ready" <<'PY' +import sys +import time +import urllib.error +import urllib.request + +deadline = time.time() + 30 +last = None +while time.time() < deadline: + try: + with urllib.request.urlopen(sys.argv[1], timeout=2) as response: + last = response.status + except urllib.error.HTTPError as error: + last = error.code + except Exception: + last = None + if last == 200: + raise SystemExit(0) + time.sleep(0.5) +raise SystemExit(f"readiness did not reach 200; last status was {last}") +PY + +python3 - "$base_url" "$secrets/service-coordinator-token" "$reports/authorization-probes.json" <<'PY' +import json +import sys +import urllib.error +import urllib.request +from pathlib import Path + +base_url, coordinator_token_file, output = sys.argv[1:] +coordinator_token = Path(coordinator_token_file).read_text(encoding="ascii").strip() +paths = [ + "/v1/actions/bind-payment-attempt?accessProfile=payment-adapter-binder", + "/v1/actions/record-payment-receipt?accessProfile=payment-adapter-reporter", +] +results = [] +for actor, token, expected in [ + ("service-coordinator", coordinator_token, 404), + ("unauthenticated-citizen", None, 401), +]: + for path in paths: + headers = { + "Accept": "application/json", + "Content-Type": "application/json", + "Idempotency-Key": f"probe-{actor}-{len(results)}", + } + if token is not None: + headers["Authorization"] = f"Bearer {token}" + request = urllib.request.Request(base_url + path, data=b"{}", method="POST", headers=headers) + try: + with urllib.request.urlopen(request, timeout=10) as response: + status, body = response.status, response.read() + except urllib.error.HTTPError as error: + status, body = error.code, error.read() + if status != expected: + raise SystemExit(f"{actor} authorization probe returned {status}, expected {expected}") + try: + problem_code = json.loads(body).get("code") + except (json.JSONDecodeError, UnicodeDecodeError, AttributeError): + problem_code = None + if actor == "service-coordinator" and problem_code != "resource.not_found": + raise SystemExit("coordinator probe did not conceal the Adapter Action") + results.append({"actor": actor, "path": path, "status": status, "problemCode": problem_code}) +Path(output).write_text(json.dumps({"ok": True, "probes": results}, indent=2, sort_keys=True) + "\n", encoding="utf-8") +PY + +python3 - "$run_root/handoff.json" "$run_root" "$base_url" "$package_digest" "$schema_fingerprint" "$breg_pid" "$fixture" "$reports/source-head.txt" "$keep_running" "$reports/binary-provenance.json" <<'PY' +import hashlib +import json +import sys +from pathlib import Path + +output, root, base_url, package_digest, schema_fingerprint, pid, fixture, source_head_file, keep_running, binary_provenance_file = sys.argv[1:] +root = Path(root) +fixture = Path(fixture) +source_files = [ + "README.md", + "lifecycle.sh", + "registry.yaml", + "run-native.sh", + "tests/journeys.yaml", + "tests/lifecycle-smoke.sh", +] +source_hashes = { + relative: hashlib.sha256((fixture / relative).read_bytes()).hexdigest() + for relative in source_files +} +source_inventory = "".join(f"{source_hashes[relative]} {relative}\n" for relative in source_files) +document = { + "mode": "synthetic-loopback-only", + "baseUrl": base_url, + "recordType": "service-fee-bill", + "recordRoute": "service-fee-bills", + "readProfile": "payment-adapter-reporter", + "bind": {"action": "bind-payment-attempt", "profile": "payment-adapter-binder", "path": "/v1/actions/bind-payment-attempt?accessProfile=payment-adapter-binder"}, + "receipt": {"action": "record-payment-receipt", "profile": "payment-adapter-reporter", "path": "/v1/actions/record-payment-receipt?accessProfile=payment-adapter-reporter"}, + "create": {"action": "create-fee-bill", "profile": "service-biller", "path": "/v1/actions/create-fee-bill?accessProfile=service-biller"}, + "issue": {"action": "issue-paid-service", "profile": "service-issuer", "path": "/v1/actions/issue-paid-service?accessProfile=service-issuer"}, + "credentials": { + "paymentAdapter": str(root / "secrets/payment-adapter-token"), + "issuanceService": str(root / "secrets/issuance-service-token"), + "serviceCoordinator": str(root / "secrets/service-coordinator-token"), + }, + "runtimeConfig": str(root / "runtime.yaml"), + "packageRoot": str(root / "package-build/package"), + "packageDigest": package_digest, + "schemaFingerprint": schema_fingerprint, + "binaryProvenance": json.loads(Path(binary_provenance_file).read_text(encoding="utf-8")), + "binaryProvenanceFile": binary_provenance_file, + "helperLifetime": { + "signalForwarding": {"HUP": "TERM", "INT": "INT", "TERM": "TERM"}, + "keepRunning": keep_running == "1", + "mode": "retained-helper-session" if keep_running == "1" else "detached-handoff", + }, + "sourceHead": Path(source_head_file).read_text(encoding="ascii").strip(), + "fixtureSourceSha256": hashlib.sha256(source_inventory.encode("ascii")).hexdigest(), + "sourceFilesSha256": source_hashes, + "helperSha256": source_hashes["run-native.sh"], + "pidFile": str(root / "breg.pid"), + "pid": int(pid), +} +Path(output).write_text(json.dumps(document, indent=2, sort_keys=True) + "\n", encoding="utf-8") +PY +chmod 600 "$run_root/handoff.json" "$run_root/runtime.yaml" "$run_root/runtime-test.yaml" "$run_root/schema-test-credentials.yaml" "$reports/binary-provenance.json" +printf '%s\n' "$run_root" >"$scratch_root/latest-run" +chmod 600 "$scratch_root/latest-run" +trap - EXIT +printf 'Native BReg fixture is ready. Private handoff: %s\n' "$run_root/handoff.json" +if [[ "$keep_running" == "1" ]]; then + printf 'Retaining this terminal for the owned BReg process. TERM and INT are forwarded; HUP is mapped to TERM.\n' + payment_fee_wait_for_owned_child "$breg_pid" +fi diff --git a/products/breg/examples/payment-fee-issuance/tests/journeys.yaml b/products/breg/examples/payment-fee-issuance/tests/journeys.yaml new file mode 100644 index 0000000000..835cbf44d0 --- /dev/null +++ b/products/breg/examples/payment-fee-issuance/tests/journeys.yaml @@ -0,0 +1,309 @@ +# 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: exact-fee-before-issuance + steps: + - id: create-authoritative-bill + action: create-fee-bill + accessProfile: service-biller + claims: {principal: synthetic-issuance-service, scopes: [registry:fee-bill:create], purpose: service-issuance, actorKind: service, requesterClient: issuance-service} + request: + type: invoke + idempotencyKey: create-authoritative-bill + input: {institutionId: institution-a, serviceId: licence-issuance, requestId: request-001, payerId: payer-001, payerFinancialAddress: "+99123456789", billDigest: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, simulation: true} + expect: {outcome: success, status: 200} + captureResults: {bill: bill} + + - id: capture-bill-condition-after-create + action: bind-payment-attempt + accessProfile: payment-adapter-binder + claims: {principal: synthetic-payment-adapter, scopes: [registry:payment-attempt:bind], purpose: payment-processing, actorKind: service, requesterClient: payment-adapter} + request: {type: target-conditions, input: {billId: {recordCapture: bill}}} + expect: {outcome: success, status: 200} + capture: bill-condition-after-create + + - id: capture-issue-condition-after-create + action: issue-paid-service + accessProfile: service-issuer + claims: {principal: synthetic-issuance-service, scopes: [registry:paid-service:issue], purpose: service-issuance, actorKind: service, requesterClient: issuance-service} + request: {type: target-conditions, input: {billId: {recordCapture: bill}}} + expect: {outcome: success, status: 200} + capture: issue-condition-after-create + + - id: fresh-workflow-cannot-create-another-bill + action: create-fee-bill + accessProfile: service-biller + claims: {principal: synthetic-issuance-service, scopes: [registry:fee-bill:create], purpose: service-issuance, actorKind: service, requesterClient: issuance-service} + request: + type: invoke + idempotencyKey: duplicate-service-request-bill + input: {institutionId: institution-a, serviceId: licence-issuance, requestId: request-001, payerId: payer-001, payerFinancialAddress: "+99123456789", billDigest: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, simulation: true} + expect: {outcome: refusal, status: 409, problemCode: mutation.conflict} + + - id: issue-before-payment-is-refused + action: issue-paid-service + accessProfile: service-issuer + claims: {principal: synthetic-issuance-service, scopes: [registry:paid-service:issue], purpose: service-issuance, actorKind: service, requesterClient: issuance-service} + request: + type: invoke + idempotencyKey: issue-before-payment + preconditions: {billId: {conditionCapture: issue-condition-after-create}} + input: {billId: {recordCapture: bill}, billVersion: 1, requestId: request-001, paymentReceiptId: synthetic-receipt-001, issuanceId: 00000000-0000-4000-8000-000000000201} + expect: {outcome: refusal, status: 412, problemCode: action.guard_failed} + + - id: missing-scope-cannot-bind-attempt + action: bind-payment-attempt + accessProfile: payment-adapter-binder + claims: {principal: synthetic-unauthorized-adapter, scopes: [], purpose: payment-processing, actorKind: service, requesterClient: payment-adapter} + request: + type: invoke + idempotencyKey: unauthorized-bind + preconditions: {billId: {conditionCapture: bill-condition-after-create}} + input: {billId: {recordCapture: bill}, billVersion: 1, billDigest: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, institutionId: institution-a, serviceId: licence-issuance, requestId: request-001, tariffId: synthetic-licence-fee, tariffVersion: 1, tariffDigest: cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc, payerId: payer-001, payerFinancialAddress: "+99123456789", amountMinor: 2500, currency: USD, currencyScale: 2, simulation: true, paymentAttemptId: 00000000-0000-4000-8000-000000000001, providerBindingRevision: synthetic-binding-v1} + expect: {outcome: refusal, status: 404, problemCode: resource.not_found} + + - id: changed-version-cannot-bind + action: bind-payment-attempt + accessProfile: payment-adapter-binder + claims: {principal: synthetic-payment-adapter, scopes: [registry:payment-attempt:bind], purpose: payment-processing, actorKind: service, requesterClient: payment-adapter} + request: + type: invoke + idempotencyKey: changed-version-bind + preconditions: {billId: {conditionCapture: bill-condition-after-create}} + input: {billId: {recordCapture: bill}, billVersion: 2, billDigest: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, institutionId: institution-a, serviceId: licence-issuance, requestId: request-001, tariffId: synthetic-licence-fee, tariffVersion: 1, tariffDigest: cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc, payerId: payer-001, payerFinancialAddress: "+99123456789", amountMinor: 2500, currency: USD, currencyScale: 2, simulation: true, paymentAttemptId: 00000000-0000-4000-8000-000000000001, providerBindingRevision: synthetic-binding-v1} + expect: {outcome: refusal, status: 412, problemCode: action.guard_failed} + + - id: changed-digest-cannot-bind + action: bind-payment-attempt + accessProfile: payment-adapter-binder + claims: {principal: synthetic-payment-adapter, scopes: [registry:payment-attempt:bind], purpose: payment-processing, actorKind: service, requesterClient: payment-adapter} + request: + type: invoke + idempotencyKey: changed-digest-bind + preconditions: {billId: {conditionCapture: bill-condition-after-create}} + input: {billId: {recordCapture: bill}, billVersion: 1, billDigest: bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb, institutionId: institution-a, serviceId: licence-issuance, requestId: request-001, tariffId: synthetic-licence-fee, tariffVersion: 1, tariffDigest: cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc, payerId: payer-001, payerFinancialAddress: "+99123456789", amountMinor: 2500, currency: USD, currencyScale: 2, simulation: true, paymentAttemptId: 00000000-0000-4000-8000-000000000001, providerBindingRevision: synthetic-binding-v1} + expect: {outcome: refusal, status: 412, problemCode: action.guard_failed} + + - id: bind-exact-payment-attempt + action: bind-payment-attempt + accessProfile: payment-adapter-binder + claims: {principal: synthetic-payment-adapter, scopes: [registry:payment-attempt:bind], purpose: payment-processing, actorKind: service, requesterClient: payment-adapter} + request: + type: invoke + idempotencyKey: bind-exact-payment-attempt + preconditions: {billId: {conditionCapture: bill-condition-after-create}} + input: {billId: {recordCapture: bill}, billVersion: 1, billDigest: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, institutionId: institution-a, serviceId: licence-issuance, requestId: request-001, tariffId: synthetic-licence-fee, tariffVersion: 1, tariffDigest: cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc, payerId: payer-001, payerFinancialAddress: "+99123456789", amountMinor: 2500, currency: USD, currencyScale: 2, simulation: true, paymentAttemptId: 00000000-0000-4000-8000-000000000001, providerBindingRevision: synthetic-binding-v1} + expect: {outcome: success, status: 200} + + - id: capture-bill-condition-after-bind + action: record-payment-receipt + accessProfile: payment-adapter-reporter + claims: {principal: synthetic-payment-adapter, scopes: [registry:payment-receipt:report], purpose: payment-processing, actorKind: service, requesterClient: payment-adapter} + request: {type: target-conditions, input: {billId: {recordCapture: bill}}} + expect: {outcome: success, status: 200} + capture: bill-condition-after-bind + + - id: recover-exact-binding + action: bind-payment-attempt + accessProfile: payment-adapter-binder + claims: {principal: synthetic-payment-adapter, scopes: [registry:payment-attempt:bind], purpose: payment-processing, actorKind: service, requesterClient: payment-adapter} + request: + type: invoke + idempotencyKey: bind-exact-payment-attempt + preconditions: {billId: {conditionCapture: bill-condition-after-create}} + input: {billId: {recordCapture: bill}, billVersion: 1, billDigest: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, institutionId: institution-a, serviceId: licence-issuance, requestId: request-001, tariffId: synthetic-licence-fee, tariffVersion: 1, tariffDigest: cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc, payerId: payer-001, payerFinancialAddress: "+99123456789", amountMinor: 2500, currency: USD, currencyScale: 2, simulation: true, paymentAttemptId: 00000000-0000-4000-8000-000000000001, providerBindingRevision: synthetic-binding-v1} + expect: {outcome: success, status: 200} + + - id: capture-bind-condition-after-bind + action: bind-payment-attempt + accessProfile: payment-adapter-binder + claims: {principal: synthetic-payment-adapter, scopes: [registry:payment-attempt:bind], purpose: payment-processing, actorKind: service, requesterClient: payment-adapter} + request: {type: target-conditions, input: {billId: {recordCapture: bill}}} + expect: {outcome: success, status: 200} + capture: bind-condition-after-bind + + - id: capture-issue-condition-after-bind + action: issue-paid-service + accessProfile: service-issuer + claims: {principal: synthetic-issuance-service, scopes: [registry:paid-service:issue], purpose: service-issuance, actorKind: service, requesterClient: issuance-service} + request: {type: target-conditions, input: {billId: {recordCapture: bill}}} + expect: {outcome: success, status: 200} + capture: issue-condition-after-bind + + - id: pending-or-unknown-cannot-bind-second-attempt + action: bind-payment-attempt + accessProfile: payment-adapter-binder + claims: {principal: synthetic-payment-adapter, scopes: [registry:payment-attempt:bind], purpose: payment-processing, actorKind: service, requesterClient: payment-adapter} + request: + type: invoke + idempotencyKey: second-payment-attempt + preconditions: {billId: {conditionCapture: bind-condition-after-bind}} + input: {billId: {recordCapture: bill}, billVersion: 1, billDigest: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, institutionId: institution-a, serviceId: licence-issuance, requestId: request-001, tariffId: synthetic-licence-fee, tariffVersion: 1, tariffDigest: cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc, payerId: payer-001, payerFinancialAddress: "+99123456789", amountMinor: 2500, currency: USD, currencyScale: 2, simulation: true, paymentAttemptId: 00000000-0000-4000-8000-000000000002, providerBindingRevision: synthetic-binding-v1} + expect: {outcome: refusal, status: 412, problemCode: action.guard_failed} + + - id: pending-or-unknown-cannot-issue + action: issue-paid-service + accessProfile: service-issuer + claims: {principal: synthetic-issuance-service, scopes: [registry:paid-service:issue], purpose: service-issuance, actorKind: service, requesterClient: issuance-service} + request: + type: invoke + idempotencyKey: issue-while-attempt-bound + preconditions: {billId: {conditionCapture: issue-condition-after-bind}} + input: {billId: {recordCapture: bill}, billVersion: 1, requestId: request-001, paymentReceiptId: synthetic-receipt-001, issuanceId: 00000000-0000-4000-8000-000000000201} + expect: {outcome: refusal, status: 412, problemCode: action.guard_failed} + + - id: missing-scope-cannot-report-receipt + action: record-payment-receipt + accessProfile: payment-adapter-reporter + claims: {principal: synthetic-unauthorized-adapter, scopes: [], purpose: payment-processing, actorKind: service, requesterClient: payment-adapter} + request: + type: invoke + idempotencyKey: unauthorized-receipt + preconditions: {billId: {conditionCapture: bill-condition-after-bind}} + input: {billId: {recordCapture: bill}, billVersion: 1, billDigest: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, institutionId: institution-a, serviceId: licence-issuance, requestId: request-001, tariffId: synthetic-licence-fee, tariffVersion: 1, tariffDigest: cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc, payerId: payer-001, payerFinancialAddress: "+99123456789", amountMinor: 2500, currency: USD, currencyScale: 2, simulation: true, paymentAttemptId: 00000000-0000-4000-8000-000000000001, providerBindingRevision: synthetic-binding-v1, paymentReceiptId: synthetic-receipt-001, providerReference: SYNTHETIC-PAID-001, receiptDigest: dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd} + expect: {outcome: refusal, status: 404, problemCode: resource.not_found} + + - id: changed-bill-fact-cannot-report-receipt + action: record-payment-receipt + accessProfile: payment-adapter-reporter + claims: {principal: synthetic-payment-adapter, scopes: [registry:payment-receipt:report], purpose: payment-processing, actorKind: service, requesterClient: payment-adapter} + request: + type: invoke + idempotencyKey: changed-bill-receipt + preconditions: {billId: {conditionCapture: bill-condition-after-bind}} + input: {billId: {recordCapture: bill}, billVersion: 1, billDigest: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, institutionId: institution-b, serviceId: licence-issuance, requestId: request-001, tariffId: synthetic-licence-fee, tariffVersion: 1, tariffDigest: cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc, payerId: payer-001, payerFinancialAddress: "+99123456789", amountMinor: 2500, currency: USD, currencyScale: 2, simulation: true, paymentAttemptId: 00000000-0000-4000-8000-000000000001, providerBindingRevision: synthetic-binding-v1, paymentReceiptId: synthetic-receipt-001, providerReference: SYNTHETIC-PAID-001, receiptDigest: dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd} + expect: {outcome: refusal, status: 412, problemCode: action.guard_failed} + + - id: changed-amount-cannot-report-receipt + action: record-payment-receipt + accessProfile: payment-adapter-reporter + claims: {principal: synthetic-payment-adapter, scopes: [registry:payment-receipt:report], purpose: payment-processing, actorKind: service, requesterClient: payment-adapter} + request: + type: invoke + idempotencyKey: changed-amount-receipt + preconditions: {billId: {conditionCapture: bill-condition-after-bind}} + input: {billId: {recordCapture: bill}, billVersion: 1, billDigest: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, institutionId: institution-a, serviceId: licence-issuance, requestId: request-001, tariffId: synthetic-licence-fee, tariffVersion: 1, tariffDigest: cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc, payerId: payer-001, payerFinancialAddress: "+99123456789", amountMinor: 2501, currency: USD, currencyScale: 2, simulation: true, paymentAttemptId: 00000000-0000-4000-8000-000000000001, providerBindingRevision: synthetic-binding-v1, paymentReceiptId: synthetic-receipt-001, providerReference: SYNTHETIC-PAID-001, receiptDigest: dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd} + expect: {outcome: refusal, status: 412, problemCode: action.guard_failed} + + - id: changed-attempt-cannot-report-receipt + action: record-payment-receipt + accessProfile: payment-adapter-reporter + claims: {principal: synthetic-payment-adapter, scopes: [registry:payment-receipt:report], purpose: payment-processing, actorKind: service, requesterClient: payment-adapter} + request: + type: invoke + idempotencyKey: changed-attempt-receipt + preconditions: {billId: {conditionCapture: bill-condition-after-bind}} + input: {billId: {recordCapture: bill}, billVersion: 1, billDigest: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, institutionId: institution-a, serviceId: licence-issuance, requestId: request-001, tariffId: synthetic-licence-fee, tariffVersion: 1, tariffDigest: cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc, payerId: payer-001, payerFinancialAddress: "+99123456789", amountMinor: 2500, currency: USD, currencyScale: 2, simulation: true, paymentAttemptId: 00000000-0000-4000-8000-000000000002, providerBindingRevision: synthetic-binding-v1, paymentReceiptId: synthetic-receipt-001, providerReference: SYNTHETIC-PAID-001, receiptDigest: dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd} + expect: {outcome: refusal, status: 412, problemCode: action.guard_failed} + + - id: changed-provider-binding-cannot-report-receipt + action: record-payment-receipt + accessProfile: payment-adapter-reporter + claims: {principal: synthetic-payment-adapter, scopes: [registry:payment-receipt:report], purpose: payment-processing, actorKind: service, requesterClient: payment-adapter} + request: + type: invoke + idempotencyKey: changed-provider-binding-receipt + preconditions: {billId: {conditionCapture: bill-condition-after-bind}} + input: {billId: {recordCapture: bill}, billVersion: 1, billDigest: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, institutionId: institution-a, serviceId: licence-issuance, requestId: request-001, tariffId: synthetic-licence-fee, tariffVersion: 1, tariffDigest: cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc, payerId: payer-001, payerFinancialAddress: "+99123456789", amountMinor: 2500, currency: USD, currencyScale: 2, simulation: true, paymentAttemptId: 00000000-0000-4000-8000-000000000001, providerBindingRevision: other-binding-v1, paymentReceiptId: synthetic-receipt-001, providerReference: SYNTHETIC-PAID-001, receiptDigest: dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd} + expect: {outcome: refusal, status: 412, problemCode: action.guard_failed} + + - id: simulation-mode-cannot-change-at-receipt + action: record-payment-receipt + accessProfile: payment-adapter-reporter + claims: {principal: synthetic-payment-adapter, scopes: [registry:payment-receipt:report], purpose: payment-processing, actorKind: service, requesterClient: payment-adapter} + request: + type: invoke + idempotencyKey: changed-simulation-receipt + preconditions: {billId: {conditionCapture: bill-condition-after-bind}} + input: {billId: {recordCapture: bill}, billVersion: 1, billDigest: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, institutionId: institution-a, serviceId: licence-issuance, requestId: request-001, tariffId: synthetic-licence-fee, tariffVersion: 1, tariffDigest: cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc, payerId: payer-001, payerFinancialAddress: "+99123456789", amountMinor: 2500, currency: USD, currencyScale: 2, simulation: false, paymentAttemptId: 00000000-0000-4000-8000-000000000001, providerBindingRevision: synthetic-binding-v1, paymentReceiptId: synthetic-receipt-001, providerReference: SYNTHETIC-PAID-001, receiptDigest: dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd} + expect: {outcome: refusal, status: 412, problemCode: action.guard_failed} + + - id: record-exact-synthetic-receipt + action: record-payment-receipt + accessProfile: payment-adapter-reporter + claims: {principal: synthetic-payment-adapter, scopes: [registry:payment-receipt:report], purpose: payment-processing, actorKind: service, requesterClient: payment-adapter} + request: + type: invoke + idempotencyKey: record-exact-synthetic-receipt + preconditions: {billId: {conditionCapture: bill-condition-after-bind}} + input: {billId: {recordCapture: bill}, billVersion: 1, billDigest: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, institutionId: institution-a, serviceId: licence-issuance, requestId: request-001, tariffId: synthetic-licence-fee, tariffVersion: 1, tariffDigest: cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc, payerId: payer-001, payerFinancialAddress: "+99123456789", amountMinor: 2500, currency: USD, currencyScale: 2, simulation: true, paymentAttemptId: 00000000-0000-4000-8000-000000000001, providerBindingRevision: synthetic-binding-v1, paymentReceiptId: synthetic-receipt-001, providerReference: SYNTHETIC-PAID-001, receiptDigest: dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd} + expect: {outcome: success, status: 200} + + - id: recover-exact-receipt + action: record-payment-receipt + accessProfile: payment-adapter-reporter + claims: {principal: synthetic-payment-adapter, scopes: [registry:payment-receipt:report], purpose: payment-processing, actorKind: service, requesterClient: payment-adapter} + request: + type: invoke + idempotencyKey: record-exact-synthetic-receipt + preconditions: {billId: {conditionCapture: bill-condition-after-bind}} + input: {billId: {recordCapture: bill}, billVersion: 1, billDigest: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, institutionId: institution-a, serviceId: licence-issuance, requestId: request-001, tariffId: synthetic-licence-fee, tariffVersion: 1, tariffDigest: cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc, payerId: payer-001, payerFinancialAddress: "+99123456789", amountMinor: 2500, currency: USD, currencyScale: 2, simulation: true, paymentAttemptId: 00000000-0000-4000-8000-000000000001, providerBindingRevision: synthetic-binding-v1, paymentReceiptId: synthetic-receipt-001, providerReference: SYNTHETIC-PAID-001, receiptDigest: dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd} + expect: {outcome: success, status: 200} + + - id: read-exact-receipt-after-lost-acknowledgement + recordType: service-fee-bill + accessProfile: payment-adapter-reporter + claims: {principal: synthetic-payment-adapter, scopes: [registry:payment-receipt:report], purpose: payment-processing, actorKind: service, requesterClient: payment-adapter} + request: {type: get, recordCapture: bill} + expect: + outcome: success + status: 200 + fields: {billVersion: 1, billDigest: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, institutionId: institution-a, serviceId: licence-issuance, requestId: request-001, payerId: payer-001, payerFinancialAddress: "+99123456789", tariffId: synthetic-licence-fee, tariffVersion: 1, tariffDigest: cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc, amountMinor: 2500, currency: USD, currencyScale: 2, simulation: true, paymentState: paid, paymentAttemptId: 00000000-0000-4000-8000-000000000001, providerBindingRevision: synthetic-binding-v1, paymentReceiptId: synthetic-receipt-001, providerReference: SYNTHETIC-PAID-001, receiptDigest: dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd} + + - id: capture-bill-condition-after-receipt + action: issue-paid-service + accessProfile: service-issuer + claims: {principal: synthetic-issuance-service, scopes: [registry:paid-service:issue], purpose: service-issuance, actorKind: service, requesterClient: issuance-service} + request: {type: target-conditions, input: {billId: {recordCapture: bill}}} + expect: {outcome: success, status: 200} + capture: bill-condition-after-receipt + + - id: capture-receipt-condition-after-receipt + action: record-payment-receipt + accessProfile: payment-adapter-reporter + claims: {principal: synthetic-payment-adapter, scopes: [registry:payment-receipt:report], purpose: payment-processing, actorKind: service, requesterClient: payment-adapter} + request: {type: target-conditions, input: {billId: {recordCapture: bill}}} + expect: {outcome: success, status: 200} + capture: receipt-condition-after-receipt + + - id: new-request-identity-cannot-replace-receipt + action: record-payment-receipt + accessProfile: payment-adapter-reporter + claims: {principal: synthetic-payment-adapter, scopes: [registry:payment-receipt:report], purpose: payment-processing, actorKind: service, requesterClient: payment-adapter} + request: + type: invoke + idempotencyKey: replacement-receipt + preconditions: {billId: {conditionCapture: receipt-condition-after-receipt}} + input: {billId: {recordCapture: bill}, billVersion: 1, billDigest: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, institutionId: institution-a, serviceId: licence-issuance, requestId: request-001, tariffId: synthetic-licence-fee, tariffVersion: 1, tariffDigest: cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc, payerId: payer-001, payerFinancialAddress: "+99123456789", amountMinor: 2500, currency: USD, currencyScale: 2, simulation: true, paymentAttemptId: 00000000-0000-4000-8000-000000000001, providerBindingRevision: synthetic-binding-v1, paymentReceiptId: synthetic-receipt-002, providerReference: SYNTHETIC-PAID-002, receiptDigest: eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee} + expect: {outcome: refusal, status: 412, problemCode: action.guard_failed} + + - id: issue-after-exact-receipt + action: issue-paid-service + accessProfile: service-issuer + claims: {principal: synthetic-issuance-service, scopes: [registry:paid-service:issue], purpose: service-issuance, actorKind: service, requesterClient: issuance-service} + request: + type: invoke + idempotencyKey: issue-after-exact-receipt + preconditions: {billId: {conditionCapture: bill-condition-after-receipt}} + input: {billId: {recordCapture: bill}, billVersion: 1, requestId: request-001, paymentReceiptId: synthetic-receipt-001, issuanceId: 00000000-0000-4000-8000-000000000201} + expect: {outcome: success, status: 200} + + - id: capture-bill-condition-after-issuance + action: issue-paid-service + accessProfile: service-issuer + claims: {principal: synthetic-issuance-service, scopes: [registry:paid-service:issue], purpose: service-issuance, actorKind: service, requesterClient: issuance-service} + request: {type: target-conditions, input: {billId: {recordCapture: bill}}} + expect: {outcome: success, status: 200} + capture: bill-condition-after-issuance + + - id: issuance-is-single-use + action: issue-paid-service + accessProfile: service-issuer + claims: {principal: synthetic-issuance-service, scopes: [registry:paid-service:issue], purpose: service-issuance, actorKind: service, requesterClient: issuance-service} + request: + type: invoke + idempotencyKey: second-issuance + preconditions: {billId: {conditionCapture: bill-condition-after-issuance}} + input: {billId: {recordCapture: bill}, billVersion: 1, requestId: request-001, paymentReceiptId: synthetic-receipt-001, issuanceId: 00000000-0000-4000-8000-000000000202} + expect: {outcome: refusal, status: 412, problemCode: action.guard_failed} diff --git a/products/breg/examples/payment-fee-issuance/tests/lifecycle-smoke.sh b/products/breg/examples/payment-fee-issuance/tests/lifecycle-smoke.sh new file mode 100755 index 0000000000..76cdc73e99 --- /dev/null +++ b/products/breg/examples/payment-fee-issuance/tests/lifecycle-smoke.sh @@ -0,0 +1,133 @@ +#!/usr/bin/env bash +set -euo pipefail + +script_dir=$( + python3 - "${BASH_SOURCE[0]}" <<'PY' +import sys +from pathlib import Path + +print(Path(sys.argv[1]).resolve().parent) +PY +) +readonly script_dir +readonly lifecycle="$script_dir/../lifecycle.sh" +scratch=$(mktemp -d "${TMPDIR:-/tmp}/payment-fee-lifecycle.XXXXXX") +readonly scratch + +cleanup() { + rm -f \ + "$scratch/child.py" \ + "$scratch/waiter.sh" \ + "$scratch/term-child-signal" \ + "$scratch/term-child-ready" \ + "$scratch/term-bystander-signal" \ + "$scratch/term-bystander-ready" \ + "$scratch/int-child-signal" \ + "$scratch/int-child-ready" \ + "$scratch/int-bystander-signal" \ + "$scratch/int-bystander-ready" \ + "$scratch/hup-child-signal" \ + "$scratch/hup-child-ready" \ + "$scratch/hup-bystander-signal" \ + "$scratch/hup-bystander-ready" + rmdir "$scratch" +} +trap cleanup EXIT + +cat >"$scratch/child.py" <<'PY' +#!/usr/bin/env python3 +import os +import signal +import sys +import time +from pathlib import Path + +signal_file = Path(sys.argv[1]) +ready_file = Path(sys.argv[2]) + +def stop(signum, _frame): + signal_file.write_text(signal.Signals(signum).name.removeprefix("SIG") + "\n") + raise SystemExit(0) + +signal.signal(signal.SIGTERM, stop) +signal.signal(signal.SIGINT, stop) +signal.signal(signal.SIGHUP, signal.SIG_IGN) +ready_file.write_text(f"{os.getpid()}\n") +while True: + time.sleep(1) +PY +chmod 700 "$scratch/child.py" + +cat >"$scratch/waiter.sh" <<'EOF' +#!/usr/bin/env bash +set -euo pipefail +readonly lifecycle=$1 +readonly child_script=$2 +readonly signal_file=$3 +readonly child_ready_file=$4 +source "$lifecycle" +"$child_script" "$signal_file" "$child_ready_file" & +owned_pid=$! +payment_fee_wait_for_owned_child "$owned_pid" +EOF +chmod 700 "$scratch/waiter.sh" + +python3 - "$lifecycle" "$scratch" <<'PY' +import os +import signal +import subprocess +import sys +import time +from pathlib import Path + +lifecycle = sys.argv[1] +scratch = Path(sys.argv[2]) + +def wait_for_file(path): + deadline = time.time() + 5 + while time.time() < deadline: + if path.exists() and path.stat().st_size: + return + time.sleep(0.05) + raise RuntimeError(f"timed out waiting for {path.name}") + +def stop(process): + if process is None or process.poll() is not None: + return + process.terminate() + try: + process.wait(timeout=3) + except subprocess.TimeoutExpired: + process.kill() + process.wait(timeout=3) + +for name, parent_signal, child_signal_name in ( + ("term", signal.SIGTERM, "TERM"), + ("int", signal.SIGINT, "INT"), + ("hup", signal.SIGHUP, "TERM"), +): + child_signal = scratch / f"{name}-child-signal" + child_ready = scratch / f"{name}-child-ready" + bystander_signal = scratch / f"{name}-bystander-signal" + bystander_ready = scratch / f"{name}-bystander-ready" + bystander = None + waiter = None + try: + bystander = subprocess.Popen([scratch / "child.py", bystander_signal, bystander_ready]) + wait_for_file(bystander_ready) + waiter = subprocess.Popen( + [scratch / "waiter.sh", lifecycle, scratch / "child.py", child_signal, child_ready] + ) + wait_for_file(child_ready) + os.kill(waiter.pid, parent_signal) + if waiter.wait(timeout=5) != 0: + raise RuntimeError(f"{name} waiter did not exit cleanly") + if child_signal.read_text().strip() != child_signal_name: + raise RuntimeError(f"{name} did not deliver {child_signal_name} to the owned child") + if bystander.poll() is not None or bystander_signal.exists(): + raise RuntimeError(f"{name} reached a bystander process") + finally: + stop(waiter) + stop(bystander) +PY +printf 'lifecycle smoke passed\n' diff --git a/products/coordinator/CHANGELOG.md b/products/coordinator/CHANGELOG.md index bd7d4ac386..853b7b41ba 100644 --- a/products/coordinator/CHANGELOG.md +++ b/products/coordinator/CHANGELOG.md @@ -96,6 +96,14 @@ and `coordinator --recovery-only` inspects it with admissions and dispatch disabled. Migration: set the audience member to the authorization server's issuer identifier, exactly as its metadata publishes it. +- Add native Adapter payment collection operations: request a collection from + an authoritative bill id and version, read its typed state, and record a + verified receipt under a separate idempotent command. Collection requests + support read-only original-key reconciliation. The host-owned `collection` + completion keeps accepted, pending, and unknown states waiting, correlates + every read to the accepted bill and binding, and settles the collection + attempt only on confirmed or failed state. Only Adapter-verified confirmed + state can produce a registry receipt. ## 0.46.0 - 2026-11-08 diff --git a/products/coordinator/README.md b/products/coordinator/README.md index 490feb3a2a..dfe10b5c9b 100644 --- a/products/coordinator/README.md +++ b/products/coordinator/README.md @@ -65,6 +65,8 @@ project, its mappings, waits, and checks. - [External directory](examples/external-directory/README.md) performs a configured HTTP GET. - [External job](examples/external-job/README.md) uses a bounded completion poll and pure interpreter for one previously selected external job. +- [Payment collection](examples/payment-collections/README.md) requests one Adapter-owned + collection, waits for its named completion, and records only a confirmed receipt. ## Package and deploy diff --git a/products/coordinator/examples/payment-collections/README.md b/products/coordinator/examples/payment-collections/README.md new file mode 100644 index 0000000000..c2fa592cf6 --- /dev/null +++ b/products/coordinator/examples/payment-collections/README.md @@ -0,0 +1,148 @@ +# Payment collection project + +This project accepts one authoritative BReg bill reference, requests collection +through the Adapter connection `licence-fees`, waits for its named `collection` +completion, and records the exact confirmed receipt. The Adapter owns the +provider attempt and BReg reporting authority. Coordinator supplies only +`billId`, `billVersion`, the saved command identity, and workflow sequencing. + +The workflow has three terminal outcomes: + +- `receipt-recorded` returns the Adapter's exact `RegistryReceipt`. This is the + only outcome that may release the paid service. +- `collection-failed` returns the verified failed collection status. It does + not record a receipt or release the service. +- `collection-unresolved` has no output. A wait timeout, or any accepted, + pending, or unknown state that reaches the route, takes this outcome. It does + not prove failure and must not release the service or authorize a new attempt. + +An uncertain `request-collection` or `record-receipt` call does not reach a +terminal outcome. Inspect it. Reconcile `request-collection` through its +read-only original-request lookup. Recover `record-receipt` with +`retry-same`, which reuses the saved command and key. Do not start a new run +or send a fresh command. This also applies to an ambiguous +`adapter.payment.provider-protocol` response after dispatch. + +## Check and package + +From the repository root, use binaries built from this checkout: + +```sh +coordinatorctl check --project products/coordinator/examples/payment-collections --explain +coordinatorctl test --project products/coordinator/examples/payment-collections +coordinatorctl package \ + --project products/coordinator/examples/payment-collections \ + --output /absolute/private/payment-collections-package +``` + +Copy `runtime.yaml` outside the package. Replace its package root and +digest with the package command's output. Set the actual database URLs, +PostgreSQL role, issuer, JWKS source, Adapter and token endpoints, listener, +secret root, and audit path. The loopback values match the neighbouring +synthetic Adapter example, but they name real processes in a joined run, not +HTTP doubles. Then run the normal deployment sequence: + +```sh +coordinatorctl --runtime-config /absolute/path/runtime.yaml check --deny-warnings +coordinatorctl --runtime-config /absolute/path/runtime.yaml plan +coordinatorctl --runtime-config /absolute/path/runtime.yaml apply +coordinatorctl --runtime-config /absolute/path/runtime.yaml deployment-status +coordinator --runtime-config /absolute/path/runtime.yaml +``` + +The runtime's payment connection must select Adapter connection +`licence-fees`. That Adapter connection is bound to BReg institution +`institution-a`, service `licence-issuance`, and a synthetic USD 25.00 bill. +Replace `input.example.json`'s UUID with the root UUID returned by the fixture's +`create-fee-bill` Action. Its protocol `billVersion` is `1`, not the BReg +record revision or HTTP condition. + +## Identity requirements + +Coordinator's outbound payment credential is a confidential OAuth client: + +- The client identifier is `coordinator-payments`, and its private signing JWK + is available at `secret:file/coordinator-payments-jwk`. +- Its token request asks for resource `urn:registry:payment-adapter` and scope + `payments:collect`. The issued token's audience must equal Adapter's + configured audience. The issuer registers the signing key and permits that + exact grant. +- Adapter verifies that token, resolves the caller as `coordinator-payments`, + and admits it to `licence-fees`. Coordinator receives no Adapter reporter's + BReg bill-binding or receipt-reporting grants. + +Coordinator's inbound caller tokens are separate: + +- The runtime sets `scopeClaim: scope`, so both tokens carry their scopes in + the standard `scope` claim rather than Coordinator's default + `registry_scopes` claim. +- The licence service token has Coordinator's configured issuer and audience, + exact subject `licence-service`, scope `coordinator:start`, and no `act` + claim. Policy `licence-service` permits `start` and `status` only for + `payment-collections`. +- The operator token has the same issuer and audience, exact subject + `payment-operator`, scope `coordinator:operate`, and no `act` claim. Policy + `payment-operator` permits inspection and exact-command recovery. It is not + a payment-provider or BReg reporter credential. + +If the joined issuer emits different service-account subjects, copy the exact +verified `sub` values into the two policies and use those tokens consistently. +Do not assume a client identifier is also its token subject. + +## Start and observe one joined run + +Write the actual bill input to a private file. Write a unique logical request +key and each access token to separate regular files with mode `0600`; never put +tokens on the command line. Discover the active revision, then pass that exact +revision to `start`: + +```sh +coordinatorctl --format json workflow \ + --workflow payment-collections \ + --url http://127.0.0.1:8108 \ + --token-file /absolute/private/licence-service.token + +coordinatorctl --format json start \ + --workflow payment-collections \ + --workflow-revision sha256: \ + --input /absolute/private/payment-input.json \ + --key-file /absolute/private/payment-run.key \ + --url http://127.0.0.1:8108 \ + --token-file /absolute/private/licence-service.token + +coordinatorctl --format json status \ + --run \ + --url http://127.0.0.1:8108 \ + --token-file /absolute/private/licence-service.token +``` + +The same producer subject owns the run and may read its status. Use the +operator token for bounded diagnostics and recovery: + +```sh +coordinatorctl --format json inspect \ + --run \ + --url http://127.0.0.1:8108 \ + --token-file /absolute/private/payment-operator.token + +coordinatorctl --format json reconcile \ + --run \ + --reason joined-payment-response-loss \ + --url http://127.0.0.1:8108 \ + --token-file /absolute/private/payment-operator.token + +coordinatorctl --format json retry-same \ + --run \ + --reason joined-receipt-response-loss \ + --url http://127.0.0.1:8108 \ + --token-file /absolute/private/payment-operator.token +``` + +Do not use either recovery command merely because collection status is pending +or unknown. The named completion performs read-only status observations at the +configured 60-second floor. Use `reconcile` only for a held +`request-collection`, and `retry-same` only for a held `record-receipt`, as +reported by inspection. After a terminal status, +accept only named outcome `receipt-recorded` and verify its bill ID, bill version, +collection ID, binding revision, exact money, provider reference, simulation +flag, and receipt ID before the service proceeds. diff --git a/products/coordinator/examples/payment-collections/input.example.json b/products/coordinator/examples/payment-collections/input.example.json new file mode 100644 index 0000000000..2e2fc9df09 --- /dev/null +++ b/products/coordinator/examples/payment-collections/input.example.json @@ -0,0 +1,4 @@ +{ + "billId": "00000000-0000-4000-8000-000000000101", + "billVersion": 1 +} diff --git a/products/coordinator/examples/payment-collections/runtime.yaml b/products/coordinator/examples/payment-collections/runtime.yaml new file mode 100644 index 0000000000..7c71f7f76b --- /dev/null +++ b/products/coordinator/examples/payment-collections/runtime.yaml @@ -0,0 +1,57 @@ +# yaml-language-server: $schema=https://id.registrystack.org/schemas/coordinator/runtime/runtime.v1alpha1.schema.json +apiVersion: id.registrystack.org/formats/coordinator/runtime/v1alpha1 +kind: CoordinatorRuntimeConfig +secretProviders: + environment: {} + file: + root: /run/registry-coordinator/secrets +database: + runtimeUrlRef: secret:env/COORDINATOR_DATABASE_URL + migrationUrlRef: secret:env/COORDINATOR_MIGRATION_URL +namespace: coordinator_payment_collections +connections: + licence-fees: + type: payments + baseUrl: http://127.0.0.1:8098 + paymentConnection: licence-fees + authorization: + tokenEndpoint: http://127.0.0.1:8090/token + clientAssertionAudience: http://127.0.0.1:8090 + clientId: coordinator-payments + signingKeyRef: secret:file/coordinator-payments-jwk + resource: urn:registry:payment-adapter + scopes: [payments:collect] + resultCheckSeconds: 60 +deployment: + databaseId: coordinator-institution-payment-collections + runtimeRole: coordinator_runtime + packages: + - root: /opt/registry-coordinator/payment-collections-package + expectedDigest: sha256:0000000000000000000000000000000000000000000000000000000000000000 + listener: + bind: 127.0.0.1:8108 + tlsTermination: operator-controlled-upstream + authentication: + issuer: https://issuer.example.org + audience: urn:example:coordinator + jwksSource: {type: discovery} + scopeClaim: scope + policies: + licence-service: + subjects: [licence-service] + requiredScopes: [coordinator:start] + workflows: [payment-collections] + actions: [start, status] + payment-operator: + subjects: [payment-operator] + requiredScopes: [coordinator:operate] + workflows: [payment-collections] + actions: [status, inspect, retry-same, cancel, reconcile] + operator: true + auditFile: /var/lib/registry-coordinator/payment-collections-audit.jsonl + auditKeyRef: secret:file/audit-key + activeStateKey: 1 + stateKeys: + '1': + keyRef: secret:file/state-key-1 + admissionKeyRef: secret:file/admission-key diff --git a/products/coordinator/examples/payment-collections/scenarios.yaml b/products/coordinator/examples/payment-collections/scenarios.yaml new file mode 100644 index 0000000000..289652e1a5 --- /dev/null +++ b/products/coordinator/examples/payment-collections/scenarios.yaml @@ -0,0 +1,237 @@ +# yaml-language-server: $schema=https://id.registrystack.org/schemas/coordinator/scenarios/scenarios.v1alpha1.schema.json +# Synthetic replies exercise the compiled model. HTTP authority and durability are tested separately. +apiVersion: id.registrystack.org/formats/coordinator/scenarios/v1alpha1 +kind: CoordinatorScenarios +cases: +- id: confirmed-collection-records-receipt + admittedAt: '2026-11-12T00:00:00Z' + input: + billId: 00000000-0000-4000-8000-000000000101 + billVersion: 1 + replies: + request-collection: + - type: success + value: + collectionId: 00000000-0000-4000-8000-000000000201 + billId: 00000000-0000-4000-8000-000000000101 + billVersion: 1 + bindingRevision: sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa + simulation: true + record-receipt: + - type: success + value: + collectionId: 00000000-0000-4000-8000-000000000201 + billId: 00000000-0000-4000-8000-000000000101 + billVersion: 1 + bindingRevision: sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa + simulation: true + money: {value: '25.00', currency: USD, scale: 2} + providerReference: SIM-PAID-001 + receiptId: payment-00000000-0000-4000-8000-000000000201 + waits: + await-collection: + type: event + value: + collectionId: 00000000-0000-4000-8000-000000000201 + billId: 00000000-0000-4000-8000-000000000101 + billVersion: 1 + bindingRevision: sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa + simulation: true + state: confirmed + money: {value: '25.00', currency: USD, scale: 2} + providerReference: SIM-PAID-001 + expect: + path: [request-collection, await-collection, route-collection, record-receipt, receipt-recorded] + state: completed + outcome: {type: named, value: receipt-recorded} + output: + collectionId: 00000000-0000-4000-8000-000000000201 + billId: 00000000-0000-4000-8000-000000000101 + billVersion: 1 + bindingRevision: sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa + simulation: true + money: {value: '25.00', currency: USD, scale: 2} + providerReference: SIM-PAID-001 + receiptId: payment-00000000-0000-4000-8000-000000000201 +- id: failed-collection-does-not-record-receipt + admittedAt: '2026-11-12T00:00:00Z' + input: + billId: 00000000-0000-4000-8000-000000000101 + billVersion: 1 + replies: + request-collection: + - type: success + value: + collectionId: 00000000-0000-4000-8000-000000000201 + billId: 00000000-0000-4000-8000-000000000101 + billVersion: 1 + bindingRevision: sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa + simulation: true + waits: + await-collection: + type: event + value: + collectionId: 00000000-0000-4000-8000-000000000201 + billId: 00000000-0000-4000-8000-000000000101 + billVersion: 1 + bindingRevision: sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa + simulation: true + state: failed + money: {value: '25.00', currency: USD, scale: 2} + failureReason: provider-declined + expect: + path: [request-collection, await-collection, route-collection, collection-failed] + state: completed + outcome: {type: named, value: collection-failed} + output: + collectionId: 00000000-0000-4000-8000-000000000201 + billId: 00000000-0000-4000-8000-000000000101 + billVersion: 1 + bindingRevision: sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa + simulation: true + state: failed + money: {value: '25.00', currency: USD, scale: 2} + failureReason: provider-declined +- id: pending-until-timeout-remains-unresolved + admittedAt: '2026-11-12T00:00:00Z' + input: + billId: 00000000-0000-4000-8000-000000000101 + billVersion: 1 + replies: + request-collection: + - type: success + value: + collectionId: 00000000-0000-4000-8000-000000000201 + billId: 00000000-0000-4000-8000-000000000101 + billVersion: 1 + bindingRevision: sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa + simulation: true + waits: + await-collection: {type: timeout} + expect: + path: [request-collection, await-collection, collection-unresolved] + state: completed + outcome: {type: named, value: collection-unresolved} + output: null + workflowElapsedSeconds: 3600 +- id: unknown-request-response-stays-uncertain + admittedAt: '2026-11-12T00:00:00Z' + input: + billId: 00000000-0000-4000-8000-000000000101 + billVersion: 1 + replies: + request-collection: + - type: uncertain + code: payment-outcome-unknown + expect: + path: [request-collection] + state: uncertain + outcome: {type: none} +- id: request-reconciliation-recovers-original-acceptance + admittedAt: '2026-11-12T00:00:00Z' + input: + billId: 00000000-0000-4000-8000-000000000101 + billVersion: 1 + replies: + request-collection: + - type: uncertain + code: payment-provider-protocol + - type: success + value: + collectionId: 00000000-0000-4000-8000-000000000201 + billId: 00000000-0000-4000-8000-000000000101 + billVersion: 1 + bindingRevision: sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa + simulation: true + record-receipt: + - type: success + value: + collectionId: 00000000-0000-4000-8000-000000000201 + billId: 00000000-0000-4000-8000-000000000101 + billVersion: 1 + bindingRevision: sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa + simulation: true + money: {value: '25.00', currency: USD, scale: 2} + providerReference: SIM-PAID-001 + receiptId: payment-00000000-0000-4000-8000-000000000201 + waits: + await-collection: + type: event + value: + collectionId: 00000000-0000-4000-8000-000000000201 + billId: 00000000-0000-4000-8000-000000000101 + billVersion: 1 + bindingRevision: sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa + simulation: true + state: confirmed + money: {value: '25.00', currency: USD, scale: 2} + providerReference: SIM-PAID-001 + recovery: + request-collection: reconcile + expect: + path: [request-collection, await-collection, route-collection, record-receipt, receipt-recorded] + state: completed + outcome: {type: named, value: receipt-recorded} + output: + collectionId: 00000000-0000-4000-8000-000000000201 + billId: 00000000-0000-4000-8000-000000000101 + billVersion: 1 + bindingRevision: sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa + simulation: true + money: {value: '25.00', currency: USD, scale: 2} + providerReference: SIM-PAID-001 + receiptId: payment-00000000-0000-4000-8000-000000000201 +- id: receipt-exact-retry-recovers-original-result + admittedAt: '2026-11-12T00:00:00Z' + input: + billId: 00000000-0000-4000-8000-000000000101 + billVersion: 1 + replies: + request-collection: + - type: success + value: + collectionId: 00000000-0000-4000-8000-000000000201 + billId: 00000000-0000-4000-8000-000000000101 + billVersion: 1 + bindingRevision: sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa + simulation: true + record-receipt: + - type: uncertain + code: payment-outcome-unknown + - type: success + value: + collectionId: 00000000-0000-4000-8000-000000000201 + billId: 00000000-0000-4000-8000-000000000101 + billVersion: 1 + bindingRevision: sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa + simulation: true + money: {value: '25.00', currency: USD, scale: 2} + providerReference: SIM-PAID-001 + receiptId: payment-00000000-0000-4000-8000-000000000201 + waits: + await-collection: + type: event + value: + collectionId: 00000000-0000-4000-8000-000000000201 + billId: 00000000-0000-4000-8000-000000000101 + billVersion: 1 + bindingRevision: sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa + simulation: true + state: confirmed + money: {value: '25.00', currency: USD, scale: 2} + providerReference: SIM-PAID-001 + recovery: + record-receipt: retry-same + expect: + path: [request-collection, await-collection, route-collection, record-receipt, receipt-recorded] + state: completed + outcome: {type: named, value: receipt-recorded} + output: + collectionId: 00000000-0000-4000-8000-000000000201 + billId: 00000000-0000-4000-8000-000000000101 + billVersion: 1 + bindingRevision: sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa + simulation: true + money: {value: '25.00', currency: USD, scale: 2} + providerReference: SIM-PAID-001 + receiptId: payment-00000000-0000-4000-8000-000000000201 diff --git a/products/coordinator/examples/payment-collections/workflow.yaml b/products/coordinator/examples/payment-collections/workflow.yaml new file mode 100644 index 0000000000..dbedc3b962 --- /dev/null +++ b/products/coordinator/examples/payment-collections/workflow.yaml @@ -0,0 +1,70 @@ +# yaml-language-server: $schema=https://id.registrystack.org/schemas/coordinator/project/project.v1alpha1.schema.json +apiVersion: id.registrystack.org/formats/coordinator/project/v1alpha1 +kind: CoordinatorProject +project: + id: payment-collections + version: '1' +operations: + request-collection: + uses: payments.request-collection/v1 + connection: licence-fees + record-receipt: + uses: payments.record-receipt/v1 + connection: licence-fees +workflow: + input: + operationInput: request-collection + deadlineSeconds: 7200 + start: request-collection + steps: + request-collection: + type: call + operation: request-collection + input: {type: input} + next: await-collection + await-collection: + type: wait-for + completion: {step: request-collection, name: collection} + timeoutSeconds: 3600 + next: route-collection + onTimeout: collection-unresolved + route-collection: + type: choose + choose: + type: step + step: await-collection + path: /state + cases: + accepted: collection-unresolved + pending: collection-unresolved + confirmed: record-receipt + failed: collection-failed + unknown: collection-unresolved + record-receipt: + type: call + operation: record-receipt + input: + type: fields + fields: + collectionId: + type: step + step: await-collection + path: /collectionId + next: receipt-recorded + receipt-recorded: + type: finish + outcome: receipt-recorded + output: {type: step, step: record-receipt} + collection-failed: + type: finish + outcome: collection-failed + output: {type: step, step: await-collection} + collection-unresolved: + type: finish + outcome: collection-unresolved + outcomes: + receipt-recorded: + operationOutput: record-receipt + collection-failed: + completionOutput: {operation: request-collection, name: collection} + collection-unresolved: {type: 'null'} diff --git a/products/coordinator/generated/openapi/coordinator.openapi.json b/products/coordinator/generated/openapi/coordinator.openapi.json index 2e69033446..fe8cf4e684 100644 --- a/products/coordinator/generated/openapi/coordinator.openapi.json +++ b/products/coordinator/generated/openapi/coordinator.openapi.json @@ -461,7 +461,10 @@ "breg.submit-proposal/v1", "breg.cancel-proposal/v1", "breg.lookup-record/v1", - "breg.read-record/v2" + "breg.read-record/v2", + "payments.request-collection/v1", + "payments.read-collection/v1", + "payments.record-receipt/v1" ], "type": "string" }, diff --git a/products/coordinator/generated/operations/README.md b/products/coordinator/generated/operations/README.md index 65763903a4..cb372f50b6 100644 --- a/products/coordinator/generated/operations/README.md +++ b/products/coordinator/generated/operations/README.md @@ -30,6 +30,9 @@ Each catalog operation has an input contract, the type its adapter decodes, and | [`breg.cancel-proposal/v1`](#breg.cancel-proposal/v1) | 1 | `breg` | mutation | required | required | same-command | none | none | | [`breg.lookup-record/v1`](#breg.lookup-record/v1) | 1 | `breg` | read | none | none | read-again | none | [`onDeclaredRefusal`](breg.lookup-record.v1.declared-refusal.schema.json) | | [`breg.read-record/v2`](#breg.read-record/v2) | 2 | `breg` | read | none | none | read-again | none | none | +| [`payments.request-collection/v1`](#payments.request-collection/v1) | 1 | `payments` | mutation | required | none | same-command-and-receipt | read | none | +| [`payments.read-collection/v1`](#payments.read-collection/v1) | 1 | `payments` | read | none | none | read-again | none | none | +| [`payments.record-receipt/v1`](#payments.record-receipt/v1) | 1 | `payments` | mutation | required | none | same-command | none | none | ## breg.read-record/v1 @@ -1825,6 +1828,264 @@ Output ([`breg.read-record.v2.output.schema.json`](breg.read-record.v2.output.sc Other members are tolerated. +## payments.request-collection/v1 + +Host execution and completion contract: + +```json +{ + "authority": "current-bound-connection-authority", + "completionObservation": { + "acceptedBinding": [ + "collectionId", + "billId", + "billVersion", + "bindingRevision", + "simulation" + ], + "authenticatedWake": false, + "authority": "current-bound-payment-connection", + "deadline": "original-wait-timeout-within-original-run-deadline", + "defaultIntervalSeconds": 900, + "maximumRetryAfterSeconds": 86400, + "minimumIntervalSeconds": 30, + "name": "collection", + "observationLimit": "1 + ceil(waitDurationSeconds / effectiveIntervalSeconds)", + "paymentSuccessState": "confirmed", + "pendingStates": [ + "accepted", + "pending", + "unknown" + ], + "profile": "payment-collection", + "settledStates": [ + "confirmed", + "failed" + ], + "signalCarriesResult": false, + "terminalEvidence": "validated-authoritative-collection-read" + }, + "connectionInterface": "payments", + "identity": { + "effect": "mutation", + "id": "payments.request-collection/v1", + "keyRequirement": "required", + "product": "payments", + "readReceipt": true, + "recovery": "same-command-and-receipt", + "requiresPreparation": false, + "version": 1 + }, + "limits": { + "attemptTimeoutSeconds": 10, + "http": { + "attemptTimeoutMilliseconds": 2000, + "connectTimeoutMilliseconds": 1000, + "maximumMutationRetries": 0, + "maximumResponseBytes": 65536 + }, + "maximumCallAttempts": 10, + "maximumCallRetryDelaySeconds": 300, + "maximumConcurrentAttemptsPerRun": 1, + "maximumPreparationBytes": 65536, + "maximumRunDurationSeconds": 31536000, + "value": { + "maximumArrayItems": 256, + "maximumBytes": 131072, + "maximumDepth": 32, + "maximumNodes": 4096, + "maximumObjectMembers": 256, + "maximumStringBytes": 16384 + } + } +} +``` + +Input ([`payments.request-collection.v1.input.schema.json`](payments.request-collection.v1.input.schema.json)): + +| Member | Type | Required | +|---|---|---| +| `billId` | string (uuid) | yes | +| `billVersion` | integer | yes | + +No other members are accepted. + +Output ([`payments.request-collection.v1.output.schema.json`](payments.request-collection.v1.output.schema.json)): + +| Member | Type | Required | +|---|---|---| +| `billId` | string (uuid) | yes | +| `billVersion` | integer | yes | +| `bindingRevision` | string | yes | +| `collectionId` | string (uuid) | yes | +| `simulation` | boolean | yes | + +No other members are accepted. + +## payments.read-collection/v1 + +Host execution and completion contract: + +```json +{ + "authority": "current-bound-connection-authority", + "completionObservation": { + "acceptedBinding": [ + "collectionId", + "billId", + "billVersion", + "bindingRevision", + "simulation" + ], + "authenticatedWake": false, + "authority": "current-bound-payment-connection", + "deadline": "original-wait-timeout-within-original-run-deadline", + "defaultIntervalSeconds": 900, + "maximumRetryAfterSeconds": 86400, + "minimumIntervalSeconds": 30, + "name": "collection", + "observationLimit": "1 + ceil(waitDurationSeconds / effectiveIntervalSeconds)", + "paymentSuccessState": "confirmed", + "pendingStates": [ + "accepted", + "pending", + "unknown" + ], + "profile": "payment-collection", + "settledStates": [ + "confirmed", + "failed" + ], + "signalCarriesResult": false, + "terminalEvidence": "validated-authoritative-collection-read" + }, + "connectionInterface": "payments", + "identity": { + "effect": "read", + "id": "payments.read-collection/v1", + "keyRequirement": "none", + "product": "payments", + "readReceipt": false, + "recovery": "read-again", + "requiresPreparation": false, + "version": 1 + }, + "limits": { + "attemptTimeoutSeconds": 10, + "http": { + "attemptTimeoutMilliseconds": 2000, + "connectTimeoutMilliseconds": 1000, + "maximumMutationRetries": 0, + "maximumResponseBytes": 65536 + }, + "maximumCallAttempts": 10, + "maximumCallRetryDelaySeconds": 300, + "maximumConcurrentAttemptsPerRun": 1, + "maximumPreparationBytes": 65536, + "maximumRunDurationSeconds": 31536000, + "value": { + "maximumArrayItems": 256, + "maximumBytes": 131072, + "maximumDepth": 32, + "maximumNodes": 4096, + "maximumObjectMembers": 256, + "maximumStringBytes": 16384 + } + } +} +``` + +Input ([`payments.read-collection.v1.input.schema.json`](payments.read-collection.v1.input.schema.json)): + +| Member | Type | Required | +|---|---|---| +| `collectionId` | string (uuid) | yes | + +No other members are accepted. + +Output ([`payments.read-collection.v1.output.schema.json`](payments.read-collection.v1.output.schema.json)): + +| Member | Type | Required | +|---|---|---| +| `billId` | string (uuid) | yes | +| `billVersion` | integer | yes | +| `bindingRevision` | string | yes | +| `collectionId` | string (uuid) | yes | +| `failureReason` | string or null | no | +| `money` | `Money` | yes | +| `providerReference` | string or null | no | +| `simulation` | boolean | yes | +| `state` | `CollectionState` | yes | + +No other members are accepted. + +## payments.record-receipt/v1 + +Host execution and completion contract: + +```json +{ + "authority": "current-bound-connection-authority", + "completionObservation": null, + "connectionInterface": "payments", + "identity": { + "effect": "mutation", + "id": "payments.record-receipt/v1", + "keyRequirement": "required", + "product": "payments", + "readReceipt": false, + "recovery": "same-command", + "requiresPreparation": false, + "version": 1 + }, + "limits": { + "attemptTimeoutSeconds": 10, + "http": { + "attemptTimeoutMilliseconds": 2000, + "connectTimeoutMilliseconds": 1000, + "maximumMutationRetries": 0, + "maximumResponseBytes": 65536 + }, + "maximumCallAttempts": 10, + "maximumCallRetryDelaySeconds": 300, + "maximumConcurrentAttemptsPerRun": 1, + "maximumPreparationBytes": 65536, + "maximumRunDurationSeconds": 31536000, + "value": { + "maximumArrayItems": 256, + "maximumBytes": 131072, + "maximumDepth": 32, + "maximumNodes": 4096, + "maximumObjectMembers": 256, + "maximumStringBytes": 16384 + } + } +} +``` + +Input ([`payments.record-receipt.v1.input.schema.json`](payments.record-receipt.v1.input.schema.json)): + +| Member | Type | Required | +|---|---|---| +| `collectionId` | string (uuid) | yes | + +No other members are accepted. + +Output ([`payments.record-receipt.v1.output.schema.json`](payments.record-receipt.v1.output.schema.json)): + +| Member | Type | Required | +|---|---|---| +| `billId` | string (uuid) | yes | +| `billVersion` | integer | yes | +| `bindingRevision` | string | yes | +| `collectionId` | string (uuid) | yes | +| `money` | `Money` | yes | +| `providerReference` | string | yes | +| `receiptId` | string | yes | +| `simulation` | boolean | yes | + +No other members are accepted. + ## Completions A `wait-for` step observes a named completion on an accepted Operation. The host reads the authoritative result under current connection authority, using the saved command and exact correlation. A terminal result continues through `next` as the step output. A step reached by `onTimeout` has no completion output. Authenticated signals only wake an eligible read and never carry the result. Durable read spacing, the observation budget and the original deadline survive retries and restarts. diff --git a/products/coordinator/generated/operations/catalog.json b/products/coordinator/generated/operations/catalog.json index cb4dc17b97..5420c6ffd3 100644 --- a/products/coordinator/generated/operations/catalog.json +++ b/products/coordinator/generated/operations/catalog.json @@ -2643,6 +2643,474 @@ "type": "object" } }, + "payments.read-collection/v1": { + "host": { + "authority": "current-bound-connection-authority", + "completionObservation": { + "acceptedBinding": [ + "collectionId", + "billId", + "billVersion", + "bindingRevision", + "simulation" + ], + "authenticatedWake": false, + "authority": "current-bound-payment-connection", + "deadline": "original-wait-timeout-within-original-run-deadline", + "defaultIntervalSeconds": 900, + "maximumRetryAfterSeconds": 86400, + "minimumIntervalSeconds": 30, + "name": "collection", + "observationLimit": "1 + ceil(waitDurationSeconds / effectiveIntervalSeconds)", + "paymentSuccessState": "confirmed", + "pendingStates": [ + "accepted", + "pending", + "unknown" + ], + "profile": "payment-collection", + "settledStates": [ + "confirmed", + "failed" + ], + "signalCarriesResult": false, + "terminalEvidence": "validated-authoritative-collection-read" + }, + "connectionInterface": "payments", + "identity": { + "effect": "read", + "id": "payments.read-collection/v1", + "keyRequirement": "none", + "product": "payments", + "readReceipt": false, + "recovery": "read-again", + "requiresPreparation": false, + "version": 1 + }, + "limits": { + "attemptTimeoutSeconds": 10, + "http": { + "attemptTimeoutMilliseconds": 2000, + "connectTimeoutMilliseconds": 1000, + "maximumMutationRetries": 0, + "maximumResponseBytes": 65536 + }, + "maximumCallAttempts": 10, + "maximumCallRetryDelaySeconds": 300, + "maximumConcurrentAttemptsPerRun": 1, + "maximumPreparationBytes": 65536, + "maximumRunDurationSeconds": 31536000, + "value": { + "maximumArrayItems": 256, + "maximumBytes": 131072, + "maximumDepth": 32, + "maximumNodes": 4096, + "maximumObjectMembers": 256, + "maximumStringBytes": 16384 + } + } + }, + "input": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "description": "Input for an authoritative provider observation through the bound module.", + "properties": { + "collectionId": { + "format": "uuid", + "not": { + "const": "00000000-0000-0000-0000-000000000000" + }, + "type": "string" + } + }, + "required": [ + "collectionId" + ], + "title": "payments.read-collection/v1 input", + "type": "object" + }, + "output": { + "$defs": { + "CollectionState": { + "description": "Provider state. Unknown is unresolved and never authorizes a replacement.", + "enum": [ + "accepted", + "pending", + "confirmed", + "failed", + "unknown" + ], + "type": "string" + }, + "Money": { + "additionalProperties": false, + "description": "An exact positive decimal amount. Scale belongs to the configured currency\npolicy; wire amounts are strings so no binary floating-point rounding occurs.", + "properties": { + "currency": { + "pattern": "^[A-Z]{3}$", + "type": "string" + }, + "scale": { + "maximum": 6, + "minimum": 0, + "type": "integer" + }, + "value": { + "maxLength": 24, + "minLength": 1, + "not": { + "pattern": "^0(\\.0{1,6})?$" + }, + "pattern": "^(0|[1-9][0-9]*)(\\.[0-9]{1,6})?$", + "type": "string" + } + }, + "required": [ + "value", + "currency", + "scale" + ], + "type": "object" + } + }, + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "description": "Verified observation, retaining the attempt's original binding and provenance.", + "properties": { + "billId": { + "format": "uuid", + "not": { + "const": "00000000-0000-0000-0000-000000000000" + }, + "type": "string" + }, + "billVersion": { + "maximum": 9007199254740991, + "minimum": 1, + "type": "integer" + }, + "bindingRevision": { + "type": "string" + }, + "collectionId": { + "format": "uuid", + "not": { + "const": "00000000-0000-0000-0000-000000000000" + }, + "type": "string" + }, + "failureReason": { + "type": [ + "string", + "null" + ] + }, + "money": { + "$ref": "#/$defs/Money" + }, + "providerReference": { + "type": [ + "string", + "null" + ] + }, + "simulation": { + "type": "boolean" + }, + "state": { + "$ref": "#/$defs/CollectionState" + } + }, + "required": [ + "collectionId", + "billId", + "billVersion", + "bindingRevision", + "simulation", + "state", + "money" + ], + "title": "payments.read-collection/v1 output", + "type": "object" + } + }, + "payments.record-receipt/v1": { + "host": { + "authority": "current-bound-connection-authority", + "completionObservation": null, + "connectionInterface": "payments", + "identity": { + "effect": "mutation", + "id": "payments.record-receipt/v1", + "keyRequirement": "required", + "product": "payments", + "readReceipt": false, + "recovery": "same-command", + "requiresPreparation": false, + "version": 1 + }, + "limits": { + "attemptTimeoutSeconds": 10, + "http": { + "attemptTimeoutMilliseconds": 2000, + "connectTimeoutMilliseconds": 1000, + "maximumMutationRetries": 0, + "maximumResponseBytes": 65536 + }, + "maximumCallAttempts": 10, + "maximumCallRetryDelaySeconds": 300, + "maximumConcurrentAttemptsPerRun": 1, + "maximumPreparationBytes": 65536, + "maximumRunDurationSeconds": 31536000, + "value": { + "maximumArrayItems": 256, + "maximumBytes": 131072, + "maximumDepth": 32, + "maximumNodes": 4096, + "maximumObjectMembers": 256, + "maximumStringBytes": 16384 + } + } + }, + "input": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "description": "Input for the restricted receipt operation. An identifier is a lookup key,\nnot receipt evidence and not authorization.", + "properties": { + "collectionId": { + "format": "uuid", + "not": { + "const": "00000000-0000-0000-0000-000000000000" + }, + "type": "string" + } + }, + "required": [ + "collectionId" + ], + "title": "payments.record-receipt/v1 input", + "type": "object" + }, + "output": { + "$defs": { + "Money": { + "additionalProperties": false, + "description": "An exact positive decimal amount. Scale belongs to the configured currency\npolicy; wire amounts are strings so no binary floating-point rounding occurs.", + "properties": { + "currency": { + "pattern": "^[A-Z]{3}$", + "type": "string" + }, + "scale": { + "maximum": 6, + "minimum": 0, + "type": "integer" + }, + "value": { + "maxLength": 24, + "minLength": 1, + "not": { + "pattern": "^0(\\.0{1,6})?$" + }, + "pattern": "^(0|[1-9][0-9]*)(\\.[0-9]{1,6})?$", + "type": "string" + } + }, + "required": [ + "value", + "currency", + "scale" + ], + "type": "object" + } + }, + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "description": "Exact receipt recorded by the service-owned registry Action.", + "properties": { + "billId": { + "format": "uuid", + "not": { + "const": "00000000-0000-0000-0000-000000000000" + }, + "type": "string" + }, + "billVersion": { + "maximum": 9007199254740991, + "minimum": 1, + "type": "integer" + }, + "bindingRevision": { + "type": "string" + }, + "collectionId": { + "format": "uuid", + "not": { + "const": "00000000-0000-0000-0000-000000000000" + }, + "type": "string" + }, + "money": { + "$ref": "#/$defs/Money" + }, + "providerReference": { + "type": "string" + }, + "receiptId": { + "type": "string" + }, + "simulation": { + "type": "boolean" + } + }, + "required": [ + "collectionId", + "billId", + "billVersion", + "bindingRevision", + "simulation", + "money", + "providerReference", + "receiptId" + ], + "title": "payments.record-receipt/v1 output", + "type": "object" + } + }, + "payments.request-collection/v1": { + "host": { + "authority": "current-bound-connection-authority", + "completionObservation": { + "acceptedBinding": [ + "collectionId", + "billId", + "billVersion", + "bindingRevision", + "simulation" + ], + "authenticatedWake": false, + "authority": "current-bound-payment-connection", + "deadline": "original-wait-timeout-within-original-run-deadline", + "defaultIntervalSeconds": 900, + "maximumRetryAfterSeconds": 86400, + "minimumIntervalSeconds": 30, + "name": "collection", + "observationLimit": "1 + ceil(waitDurationSeconds / effectiveIntervalSeconds)", + "paymentSuccessState": "confirmed", + "pendingStates": [ + "accepted", + "pending", + "unknown" + ], + "profile": "payment-collection", + "settledStates": [ + "confirmed", + "failed" + ], + "signalCarriesResult": false, + "terminalEvidence": "validated-authoritative-collection-read" + }, + "connectionInterface": "payments", + "identity": { + "effect": "mutation", + "id": "payments.request-collection/v1", + "keyRequirement": "required", + "product": "payments", + "readReceipt": true, + "recovery": "same-command-and-receipt", + "requiresPreparation": false, + "version": 1 + }, + "limits": { + "attemptTimeoutSeconds": 10, + "http": { + "attemptTimeoutMilliseconds": 2000, + "connectTimeoutMilliseconds": 1000, + "maximumMutationRetries": 0, + "maximumResponseBytes": 65536 + }, + "maximumCallAttempts": 10, + "maximumCallRetryDelaySeconds": 300, + "maximumConcurrentAttemptsPerRun": 1, + "maximumPreparationBytes": 65536, + "maximumRunDurationSeconds": 31536000, + "value": { + "maximumArrayItems": 256, + "maximumBytes": 131072, + "maximumDepth": 32, + "maximumNodes": 4096, + "maximumObjectMembers": 256, + "maximumStringBytes": 16384 + } + } + }, + "input": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "description": "Caller intent names a bill, never financial facts or provider routing.", + "properties": { + "billId": { + "format": "uuid", + "not": { + "const": "00000000-0000-0000-0000-000000000000" + }, + "type": "string" + }, + "billVersion": { + "maximum": 9007199254740991, + "minimum": 1, + "type": "integer" + } + }, + "required": [ + "billId", + "billVersion" + ], + "title": "payments.request-collection/v1 input", + "type": "object" + }, + "output": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "description": "Returned only after the provider's durable acceptance is established.", + "properties": { + "billId": { + "format": "uuid", + "not": { + "const": "00000000-0000-0000-0000-000000000000" + }, + "type": "string" + }, + "billVersion": { + "maximum": 9007199254740991, + "minimum": 1, + "type": "integer" + }, + "bindingRevision": { + "type": "string" + }, + "collectionId": { + "format": "uuid", + "not": { + "const": "00000000-0000-0000-0000-000000000000" + }, + "type": "string" + }, + "simulation": { + "type": "boolean" + } + }, + "required": [ + "collectionId", + "billId", + "billVersion", + "bindingRevision", + "simulation" + ], + "title": "payments.request-collection/v1 output", + "type": "object" + } + }, "scheduling.cancel-appointment/v1": { "host": { "authority": "current-bound-connection-authority", diff --git a/products/coordinator/generated/operations/payments.collection.completion.schema.json b/products/coordinator/generated/operations/payments.collection.completion.schema.json new file mode 100644 index 0000000000..19a3fc59ae --- /dev/null +++ b/products/coordinator/generated/operations/payments.collection.completion.schema.json @@ -0,0 +1,104 @@ +{ + "$defs": { + "CollectionState": { + "description": "Provider state. Unknown is unresolved and never authorizes a replacement.", + "enum": [ + "accepted", + "pending", + "confirmed", + "failed", + "unknown" + ], + "type": "string" + }, + "Money": { + "additionalProperties": false, + "description": "An exact positive decimal amount. Scale belongs to the configured currency\npolicy; wire amounts are strings so no binary floating-point rounding occurs.", + "properties": { + "currency": { + "pattern": "^[A-Z]{3}$", + "type": "string" + }, + "scale": { + "maximum": 6, + "minimum": 0, + "type": "integer" + }, + "value": { + "maxLength": 24, + "minLength": 1, + "not": { + "pattern": "^0(\\.0{1,6})?$" + }, + "pattern": "^(0|[1-9][0-9]*)(\\.[0-9]{1,6})?$", + "type": "string" + } + }, + "required": [ + "value", + "currency", + "scale" + ], + "type": "object" + } + }, + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "description": "Verified observation, retaining the attempt's original binding and provenance.", + "properties": { + "billId": { + "format": "uuid", + "not": { + "const": "00000000-0000-0000-0000-000000000000" + }, + "type": "string" + }, + "billVersion": { + "maximum": 9007199254740991, + "minimum": 1, + "type": "integer" + }, + "bindingRevision": { + "type": "string" + }, + "collectionId": { + "format": "uuid", + "not": { + "const": "00000000-0000-0000-0000-000000000000" + }, + "type": "string" + }, + "failureReason": { + "type": [ + "string", + "null" + ] + }, + "money": { + "$ref": "#/$defs/Money" + }, + "providerReference": { + "type": [ + "string", + "null" + ] + }, + "simulation": { + "type": "boolean" + }, + "state": { + "$ref": "#/$defs/CollectionState" + } + }, + "required": [ + "collectionId", + "billId", + "billVersion", + "bindingRevision", + "simulation", + "state", + "money" + ], + "title": "Payment collection completion", + "type": "object" +} diff --git a/products/coordinator/generated/operations/payments.read-collection.v1.input.schema.json b/products/coordinator/generated/operations/payments.read-collection.v1.input.schema.json new file mode 100644 index 0000000000..8834cc36e5 --- /dev/null +++ b/products/coordinator/generated/operations/payments.read-collection.v1.input.schema.json @@ -0,0 +1,19 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "description": "Input for an authoritative provider observation through the bound module.", + "properties": { + "collectionId": { + "format": "uuid", + "not": { + "const": "00000000-0000-0000-0000-000000000000" + }, + "type": "string" + } + }, + "required": [ + "collectionId" + ], + "title": "payments.read-collection/v1 input", + "type": "object" +} diff --git a/products/coordinator/generated/operations/payments.read-collection.v1.output.schema.json b/products/coordinator/generated/operations/payments.read-collection.v1.output.schema.json new file mode 100644 index 0000000000..890885245b --- /dev/null +++ b/products/coordinator/generated/operations/payments.read-collection.v1.output.schema.json @@ -0,0 +1,104 @@ +{ + "$defs": { + "CollectionState": { + "description": "Provider state. Unknown is unresolved and never authorizes a replacement.", + "enum": [ + "accepted", + "pending", + "confirmed", + "failed", + "unknown" + ], + "type": "string" + }, + "Money": { + "additionalProperties": false, + "description": "An exact positive decimal amount. Scale belongs to the configured currency\npolicy; wire amounts are strings so no binary floating-point rounding occurs.", + "properties": { + "currency": { + "pattern": "^[A-Z]{3}$", + "type": "string" + }, + "scale": { + "maximum": 6, + "minimum": 0, + "type": "integer" + }, + "value": { + "maxLength": 24, + "minLength": 1, + "not": { + "pattern": "^0(\\.0{1,6})?$" + }, + "pattern": "^(0|[1-9][0-9]*)(\\.[0-9]{1,6})?$", + "type": "string" + } + }, + "required": [ + "value", + "currency", + "scale" + ], + "type": "object" + } + }, + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "description": "Verified observation, retaining the attempt's original binding and provenance.", + "properties": { + "billId": { + "format": "uuid", + "not": { + "const": "00000000-0000-0000-0000-000000000000" + }, + "type": "string" + }, + "billVersion": { + "maximum": 9007199254740991, + "minimum": 1, + "type": "integer" + }, + "bindingRevision": { + "type": "string" + }, + "collectionId": { + "format": "uuid", + "not": { + "const": "00000000-0000-0000-0000-000000000000" + }, + "type": "string" + }, + "failureReason": { + "type": [ + "string", + "null" + ] + }, + "money": { + "$ref": "#/$defs/Money" + }, + "providerReference": { + "type": [ + "string", + "null" + ] + }, + "simulation": { + "type": "boolean" + }, + "state": { + "$ref": "#/$defs/CollectionState" + } + }, + "required": [ + "collectionId", + "billId", + "billVersion", + "bindingRevision", + "simulation", + "state", + "money" + ], + "title": "payments.read-collection/v1 output", + "type": "object" +} diff --git a/products/coordinator/generated/operations/payments.record-receipt.v1.input.schema.json b/products/coordinator/generated/operations/payments.record-receipt.v1.input.schema.json new file mode 100644 index 0000000000..43f41687e0 --- /dev/null +++ b/products/coordinator/generated/operations/payments.record-receipt.v1.input.schema.json @@ -0,0 +1,19 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "description": "Input for the restricted receipt operation. An identifier is a lookup key,\nnot receipt evidence and not authorization.", + "properties": { + "collectionId": { + "format": "uuid", + "not": { + "const": "00000000-0000-0000-0000-000000000000" + }, + "type": "string" + } + }, + "required": [ + "collectionId" + ], + "title": "payments.record-receipt/v1 input", + "type": "object" +} diff --git a/products/coordinator/generated/operations/payments.record-receipt.v1.output.schema.json b/products/coordinator/generated/operations/payments.record-receipt.v1.output.schema.json new file mode 100644 index 0000000000..b7b2b18330 --- /dev/null +++ b/products/coordinator/generated/operations/payments.record-receipt.v1.output.schema.json @@ -0,0 +1,85 @@ +{ + "$defs": { + "Money": { + "additionalProperties": false, + "description": "An exact positive decimal amount. Scale belongs to the configured currency\npolicy; wire amounts are strings so no binary floating-point rounding occurs.", + "properties": { + "currency": { + "pattern": "^[A-Z]{3}$", + "type": "string" + }, + "scale": { + "maximum": 6, + "minimum": 0, + "type": "integer" + }, + "value": { + "maxLength": 24, + "minLength": 1, + "not": { + "pattern": "^0(\\.0{1,6})?$" + }, + "pattern": "^(0|[1-9][0-9]*)(\\.[0-9]{1,6})?$", + "type": "string" + } + }, + "required": [ + "value", + "currency", + "scale" + ], + "type": "object" + } + }, + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "description": "Exact receipt recorded by the service-owned registry Action.", + "properties": { + "billId": { + "format": "uuid", + "not": { + "const": "00000000-0000-0000-0000-000000000000" + }, + "type": "string" + }, + "billVersion": { + "maximum": 9007199254740991, + "minimum": 1, + "type": "integer" + }, + "bindingRevision": { + "type": "string" + }, + "collectionId": { + "format": "uuid", + "not": { + "const": "00000000-0000-0000-0000-000000000000" + }, + "type": "string" + }, + "money": { + "$ref": "#/$defs/Money" + }, + "providerReference": { + "type": "string" + }, + "receiptId": { + "type": "string" + }, + "simulation": { + "type": "boolean" + } + }, + "required": [ + "collectionId", + "billId", + "billVersion", + "bindingRevision", + "simulation", + "money", + "providerReference", + "receiptId" + ], + "title": "payments.record-receipt/v1 output", + "type": "object" +} diff --git a/products/coordinator/generated/operations/payments.request-collection.v1.input.schema.json b/products/coordinator/generated/operations/payments.request-collection.v1.input.schema.json new file mode 100644 index 0000000000..57ea7618a5 --- /dev/null +++ b/products/coordinator/generated/operations/payments.request-collection.v1.input.schema.json @@ -0,0 +1,25 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "description": "Caller intent names a bill, never financial facts or provider routing.", + "properties": { + "billId": { + "format": "uuid", + "not": { + "const": "00000000-0000-0000-0000-000000000000" + }, + "type": "string" + }, + "billVersion": { + "maximum": 9007199254740991, + "minimum": 1, + "type": "integer" + } + }, + "required": [ + "billId", + "billVersion" + ], + "title": "payments.request-collection/v1 input", + "type": "object" +} diff --git a/products/coordinator/generated/operations/payments.request-collection.v1.output.schema.json b/products/coordinator/generated/operations/payments.request-collection.v1.output.schema.json new file mode 100644 index 0000000000..1b19960cc1 --- /dev/null +++ b/products/coordinator/generated/operations/payments.request-collection.v1.output.schema.json @@ -0,0 +1,41 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "description": "Returned only after the provider's durable acceptance is established.", + "properties": { + "billId": { + "format": "uuid", + "not": { + "const": "00000000-0000-0000-0000-000000000000" + }, + "type": "string" + }, + "billVersion": { + "maximum": 9007199254740991, + "minimum": 1, + "type": "integer" + }, + "bindingRevision": { + "type": "string" + }, + "collectionId": { + "format": "uuid", + "not": { + "const": "00000000-0000-0000-0000-000000000000" + }, + "type": "string" + }, + "simulation": { + "type": "boolean" + } + }, + "required": [ + "collectionId", + "billId", + "billVersion", + "bindingRevision", + "simulation" + ], + "title": "payments.request-collection/v1 output", + "type": "object" +} diff --git a/products/coordinator/generated/project/project.schema.json b/products/coordinator/generated/project/project.schema.json index 1f13a4cc48..9ac61615ec 100644 --- a/products/coordinator/generated/project/project.schema.json +++ b/products/coordinator/generated/project/project.schema.json @@ -961,7 +961,10 @@ "breg.submit-proposal/v1", "breg.cancel-proposal/v1", "breg.lookup-record/v1", - "breg.read-record/v2" + "breg.read-record/v2", + "payments.request-collection/v1", + "payments.read-collection/v1", + "payments.record-receipt/v1" ], "type": "string" }, diff --git a/products/coordinator/generated/runtime/runtime.schema.json b/products/coordinator/generated/runtime/runtime.schema.json index f57b6e5068..ccabc57ffc 100644 --- a/products/coordinator/generated/runtime/runtime.schema.json +++ b/products/coordinator/generated/runtime/runtime.schema.json @@ -322,6 +322,40 @@ ], "type": "object" }, + { + "additionalProperties": false, + "properties": { + "authorization": { + "$ref": "#/$defs/AuthorizationConfig" + }, + "baseUrl": { + "$ref": "#/$defs/Url" + }, + "paymentConnection": { + "$ref": "#/$defs/LocalId", + "description": "The Adapter payment connection selected by this Coordinator binding." + }, + "resultCheckSeconds": { + "default": 900, + "description": "Spacing between authoritative payment status observations.", + "format": "uint32", + "maximum": 86400, + "minimum": 60, + "type": "integer" + }, + "type": { + "const": "payments", + "type": "string" + } + }, + "required": [ + "type", + "baseUrl", + "paymentConnection", + "authorization" + ], + "type": "object" + }, { "additionalProperties": false, "allOf": [ diff --git a/products/identifiers/contracts/catalog-source.json b/products/identifiers/contracts/catalog-source.json index b4934cd5e1..75077af100 100644 --- a/products/identifiers/contracts/catalog-source.json +++ b/products/identifiers/contracts/catalog-source.json @@ -539,7 +539,7 @@ "owner": "adapter", "status": "active", "compatibilityLine": "v1alpha1", - "description": "Registry Adapter project, profile, pack, fixture, runtime configuration, ingestion job, job runtime configuration, and effective contract JSON Schema." + "description": "Registry Adapter project, profile, pack, fixture, runtime configuration, payment connections, ingestion job, job runtime configuration, and effective contract JSON Schema." }, { "glob": "products/render/schemas/*.schema.json", diff --git a/products/identifiers/generated/catalog.v1.json b/products/identifiers/generated/catalog.v1.json index c65f446be8..163328395b 100644 --- a/products/identifiers/generated/catalog.v1.json +++ b/products/identifiers/generated/catalog.v1.json @@ -4578,10 +4578,10 @@ "compatibilityLine": "v1alpha1", "owner": "adapter", "title": "Registry Adapter effective contract", - "description": "Registry Adapter project, profile, pack, fixture, runtime configuration, ingestion job, job runtime configuration, and effective contract JSON Schema.", + "description": "Registry Adapter project, profile, pack, fixture, runtime configuration, payment connections, ingestion job, job runtime configuration, and effective contract JSON Schema.", "source": { "path": "crates/registry-adapterctl/src/schemas.rs", - "sha256": "f922ce5b87701c57598a05db64d3a905bcaabe7e186b7437c90d64134b1a7279" + "sha256": "5a7292b400c08e61c1a64d98c5bb008b577898c341235d4b16b9c892fa147e60" }, "artifact": { "path": "products/adapter/schemas/effective-contract.v1alpha1.schema.json", @@ -4596,10 +4596,10 @@ "compatibilityLine": "v1alpha1", "owner": "adapter", "title": "Registry Adapter fixture suite", - "description": "Registry Adapter project, profile, pack, fixture, runtime configuration, ingestion job, job runtime configuration, and effective contract JSON Schema.", + "description": "Registry Adapter project, profile, pack, fixture, runtime configuration, payment connections, ingestion job, job runtime configuration, and effective contract JSON Schema.", "source": { "path": "crates/registry-adapterctl/src/schemas.rs", - "sha256": "f922ce5b87701c57598a05db64d3a905bcaabe7e186b7437c90d64134b1a7279" + "sha256": "5a7292b400c08e61c1a64d98c5bb008b577898c341235d4b16b9c892fa147e60" }, "artifact": { "path": "products/adapter/schemas/fixture.v1alpha1.schema.json", @@ -4614,10 +4614,10 @@ "compatibilityLine": "v1alpha1", "owner": "adapter", "title": "Registry Adapter ingestion job runtime configuration", - "description": "Registry Adapter project, profile, pack, fixture, runtime configuration, ingestion job, job runtime configuration, and effective contract JSON Schema.", + "description": "Registry Adapter project, profile, pack, fixture, runtime configuration, payment connections, ingestion job, job runtime configuration, and effective contract JSON Schema.", "source": { "path": "crates/registry-adapterctl/src/schemas.rs", - "sha256": "f922ce5b87701c57598a05db64d3a905bcaabe7e186b7437c90d64134b1a7279" + "sha256": "5a7292b400c08e61c1a64d98c5bb008b577898c341235d4b16b9c892fa147e60" }, "artifact": { "path": "products/adapter/schemas/job-runtime.v1alpha1.schema.json", @@ -4632,10 +4632,10 @@ "compatibilityLine": "v1alpha1", "owner": "adapter", "title": "Registry Adapter ingestion job", - "description": "Registry Adapter project, profile, pack, fixture, runtime configuration, ingestion job, job runtime configuration, and effective contract JSON Schema.", + "description": "Registry Adapter project, profile, pack, fixture, runtime configuration, payment connections, ingestion job, job runtime configuration, and effective contract JSON Schema.", "source": { "path": "crates/registry-adapterctl/src/schemas.rs", - "sha256": "f922ce5b87701c57598a05db64d3a905bcaabe7e186b7437c90d64134b1a7279" + "sha256": "5a7292b400c08e61c1a64d98c5bb008b577898c341235d4b16b9c892fa147e60" }, "artifact": { "path": "products/adapter/schemas/job.v1alpha1.schema.json", @@ -4650,10 +4650,10 @@ "compatibilityLine": "v1alpha1", "owner": "adapter", "title": "Registry Adapter mapping model", - "description": "Registry Adapter project, profile, pack, fixture, runtime configuration, ingestion job, job runtime configuration, and effective contract JSON Schema.", + "description": "Registry Adapter project, profile, pack, fixture, runtime configuration, payment connections, ingestion job, job runtime configuration, and effective contract JSON Schema.", "source": { "path": "crates/registry-adapterctl/src/schemas.rs", - "sha256": "f922ce5b87701c57598a05db64d3a905bcaabe7e186b7437c90d64134b1a7279" + "sha256": "5a7292b400c08e61c1a64d98c5bb008b577898c341235d4b16b9c892fa147e60" }, "artifact": { "path": "products/adapter/schemas/mapping.v1alpha1.schema.json", @@ -4668,10 +4668,10 @@ "compatibilityLine": "v1alpha1", "owner": "adapter", "title": "Registry Adapter pack", - "description": "Registry Adapter project, profile, pack, fixture, runtime configuration, ingestion job, job runtime configuration, and effective contract JSON Schema.", + "description": "Registry Adapter project, profile, pack, fixture, runtime configuration, payment connections, ingestion job, job runtime configuration, and effective contract JSON Schema.", "source": { "path": "crates/registry-adapterctl/src/schemas.rs", - "sha256": "f922ce5b87701c57598a05db64d3a905bcaabe7e186b7437c90d64134b1a7279" + "sha256": "5a7292b400c08e61c1a64d98c5bb008b577898c341235d4b16b9c892fa147e60" }, "artifact": { "path": "products/adapter/schemas/pack.v1alpha1.schema.json", @@ -4679,6 +4679,24 @@ "mediaType": "application/schema+json" } }, + { + "uri": "https://id.registrystack.org/schemas/adapter/payments/payments.v1alpha1.schema.json", + "kind": "schema", + "status": "active", + "compatibilityLine": "v1alpha1", + "owner": "adapter", + "title": "Registry Adapter payment connections", + "description": "Registry Adapter project, profile, pack, fixture, runtime configuration, payment connections, ingestion job, job runtime configuration, and effective contract JSON Schema.", + "source": { + "path": "crates/registry-adapterctl/src/schemas.rs", + "sha256": "5a7292b400c08e61c1a64d98c5bb008b577898c341235d4b16b9c892fa147e60" + }, + "artifact": { + "path": "products/adapter/schemas/payments.v1alpha1.schema.json", + "sha256": "00209fbf08637effcf1497601601d17196e34de84157bd72fc578e61871a029b", + "mediaType": "application/schema+json" + } + }, { "uri": "https://id.registrystack.org/schemas/adapter/preview-expectations/preview-expectations.v1alpha1.schema.json", "kind": "schema", @@ -4686,10 +4704,10 @@ "compatibilityLine": "v1alpha1", "owner": "adapter", "title": "Registry Adapter preview expectations", - "description": "Registry Adapter project, profile, pack, fixture, runtime configuration, ingestion job, job runtime configuration, and effective contract JSON Schema.", + "description": "Registry Adapter project, profile, pack, fixture, runtime configuration, payment connections, ingestion job, job runtime configuration, and effective contract JSON Schema.", "source": { "path": "crates/registry-adapterctl/src/schemas.rs", - "sha256": "f922ce5b87701c57598a05db64d3a905bcaabe7e186b7437c90d64134b1a7279" + "sha256": "5a7292b400c08e61c1a64d98c5bb008b577898c341235d4b16b9c892fa147e60" }, "artifact": { "path": "products/adapter/schemas/preview-expectations.v1alpha1.schema.json", @@ -4704,10 +4722,10 @@ "compatibilityLine": "v1alpha1", "owner": "adapter", "title": "Registry Adapter facade profile", - "description": "Registry Adapter project, profile, pack, fixture, runtime configuration, ingestion job, job runtime configuration, and effective contract JSON Schema.", + "description": "Registry Adapter project, profile, pack, fixture, runtime configuration, payment connections, ingestion job, job runtime configuration, and effective contract JSON Schema.", "source": { "path": "crates/registry-adapterctl/src/schemas.rs", - "sha256": "f922ce5b87701c57598a05db64d3a905bcaabe7e186b7437c90d64134b1a7279" + "sha256": "5a7292b400c08e61c1a64d98c5bb008b577898c341235d4b16b9c892fa147e60" }, "artifact": { "path": "products/adapter/schemas/profile.v1alpha1.schema.json", @@ -4722,10 +4740,10 @@ "compatibilityLine": "v1alpha1", "owner": "adapter", "title": "Registry Adapter project", - "description": "Registry Adapter project, profile, pack, fixture, runtime configuration, ingestion job, job runtime configuration, and effective contract JSON Schema.", + "description": "Registry Adapter project, profile, pack, fixture, runtime configuration, payment connections, ingestion job, job runtime configuration, and effective contract JSON Schema.", "source": { "path": "crates/registry-adapterctl/src/schemas.rs", - "sha256": "f922ce5b87701c57598a05db64d3a905bcaabe7e186b7437c90d64134b1a7279" + "sha256": "5a7292b400c08e61c1a64d98c5bb008b577898c341235d4b16b9c892fa147e60" }, "artifact": { "path": "products/adapter/schemas/project.v1alpha1.schema.json", @@ -4740,10 +4758,10 @@ "compatibilityLine": "v1alpha1", "owner": "adapter", "title": "Registry Adapter runtime configuration", - "description": "Registry Adapter project, profile, pack, fixture, runtime configuration, ingestion job, job runtime configuration, and effective contract JSON Schema.", + "description": "Registry Adapter project, profile, pack, fixture, runtime configuration, payment connections, ingestion job, job runtime configuration, and effective contract JSON Schema.", "source": { "path": "crates/registry-adapterctl/src/schemas.rs", - "sha256": "f922ce5b87701c57598a05db64d3a905bcaabe7e186b7437c90d64134b1a7279" + "sha256": "5a7292b400c08e61c1a64d98c5bb008b577898c341235d4b16b9c892fa147e60" }, "artifact": { "path": "products/adapter/schemas/runtime.v1alpha1.schema.json", @@ -5301,7 +5319,7 @@ "description": "Registry Coordinator deterministic scenario authoring JSON Schema.", "source": { "path": "crates/registry-coordinator/src/scenarios.rs", - "sha256": "5e5de3c3a4ca9d36a2286b0abd1d3f551acb28691ae4a16439ee3fafcb83d4ef" + "sha256": "6610fb0146afc7fce8b1339af0ed56d4b99e7a8bb37a3dfb6b695e7e8cbd475c" }, "artifact": { "path": "products/coordinator/generated/scenarios/scenarios.schema.json", diff --git a/products/platform/config-formats.yaml b/products/platform/config-formats.yaml index 15ae3c3cbe..7a00a17171 100644 --- a/products/platform/config-formats.yaml +++ b/products/platform/config-formats.yaml @@ -4505,6 +4505,62 @@ formats: whenOmitted: closed restrictingMembers: [/allowedPrivateCidrs, /oidc/audience, /oidc/issuer] + - id: adapter/payments + product: adapter + title: Registry Adapter payment connections + files: [payments.yaml, payments.example.yaml] + syntax: yaml + audience: operator + stability: experimental + current: + apiVersion: id.registrystack.org/formats/adapter/payments/v1alpha1 + kind: AdapterPayments + checkedBy: + file: crates/registry-adapter/src/payments/config.rs + symbol: API_VERSION + target: + apiVersion: id.registrystack.org/formats/adapter/payments/v1alpha1 + kind: AdapterPayments + schema: + path: products/adapter/schemas/payments.v1alpha1.schema.json + id: https://id.registrystack.org/schemas/adapter/payments/payments.v1alpha1.schema.json + origin: generated + generator: cargo run -p registry-adapterctl -- schemas --output-dir products/adapter/schemas + driftCheck: products/adapter/scripts/check-contracts.sh + reader: + crate: registry-adapter + file: crates/registry-adapter/src/payments/http.rs + function: load_config + type: PaymentsConfig + check: adapterctl payments check {file} + example: products/adapter/examples/payment-collections/payments.example.yaml + conformance: + requiredText: /connections/0/id + optionalText: none + integer: /connections/0/binding/replayWindowSeconds + boolean: /connections/0/binding/simulation + securityMembers: + - {pointer: /connections, whenOmitted: refused} + - {pointer: /connections/*/allowedClients, whenOmitted: refused} + - {pointer: /connections/*/requiredScope, whenOmitted: refused} + - {pointer: /connections/*/institutionId, whenOmitted: refused} + - {pointer: /connections/*/serviceId, whenOmitted: refused} + - {pointer: /connections/*/binding/simulation, whenOmitted: refused} + - {pointer: /connections/*/binding/provider/baseUrl, whenOmitted: refused} + - {pointer: /connections/*/binding/provider/tenant, whenOmitted: refused} + - {pointer: /connections/*/binding/provider/biller, whenOmitted: refused} + - {pointer: /connections/*/binding/providerCredentialRef, whenOmitted: refused} + - {pointer: /connections/*/binding/providerCredentialIdentity, whenOmitted: refused} + - {pointer: /connections/*/binding/replayWindowSeconds, whenOmitted: refused} + - {pointer: /connections/*/binding/registry/baseUrl, whenOmitted: refused} + - {pointer: /connections/*/binding/registry/credentialRef, whenOmitted: refused} + - {pointer: /connections/*/binding/registry/credentialIdentity, whenOmitted: refused} + - {pointer: /connections/*/binding/registry/bindProfile, whenOmitted: refused} + - {pointer: /connections/*/binding/registry/receiptProfile, whenOmitted: refused} + - {pointer: /connections/*/binding/registry/bindAction, whenOmitted: refused} + - {pointer: /connections/*/binding/registry/receiptAction, whenOmitted: refused} + restrictingMembers: [/connections, /connections/*/allowedClients, /connections/*/requiredScope, /connections/*/institutionId, /connections/*/serviceId, /connections/*/binding/simulation] + - id: adapter/job-runtime product: adapter title: Registry Adapter ingestion job runtime configuration diff --git a/tools/payment-simulator/README.md b/tools/payment-simulator/README.md index 0b7e0e3d73..0e57ba8a97 100644 --- a/tools/payment-simulator/README.md +++ b/tools/payment-simulator/README.md @@ -21,12 +21,17 @@ destination snapshots, replay responses and simulated credits across restarts. Amounts use exact minor units. Everything stays in this directory, with no Registry Stack runtime imports or Rust build. +The maintained P2G integration uses the [Adapter payment host](../../products/adapter/examples/payment-collections/README.md) +and native Coordinator payment operations. The host owns provider correlation, +durable attempts, recovery and restricted registry receipt reporting. The +simulator's HTTP profile also remains independently usable for connector tests. + The Coordinator's generic `external.get/v1` and `external.command/v1` operations cannot call these seven APIs as written. They send only a bearer token, `Accept`, `Content-Type` and, for a command, `Idempotency-Key`, while every API here requires a tenant header (`Platform-TenantId` for G2P, `X-Platform-TenantId` for P2G). A command also POSTs one JSON object to one exact path with no query string, there is no `PUT`, and `GET /transferRequests/{transferRequestId}` has a path -parameter. Payment meanings stay in the workflow definition. A compatible service can replace this simulator for new work after existing commands have settled. +parameter. A compatible service can replace this simulator for new work after existing commands have settled. ## Start locally From 0d481a132cdab5608a6efe5b39c786566b0c8c98 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Thu, 12 Nov 2026 20:05:30 +0700 Subject: [PATCH 02/40] fix: enforce payment integration validation boundaries Signed-off-by: Jeremi Joslin --- AGENTS.md | 7 +- products/adapter/scripts/check-contracts.sh | 1 + .../scripts/payment-native-support.mjs | 21 +++-- .../scripts/payment-native-support.test.mjs | 88 +++++++++++++++++++ products/coordinator/AGENTS.md | 17 ++-- .../scripts/check_dependency_direction.py | 56 +++++++++--- .../scripts/test_dependency_direction.py | 60 ++++++++++++- 7 files changed, 222 insertions(+), 28 deletions(-) create mode 100644 products/adapter/scripts/payment-native-support.test.mjs diff --git a/AGENTS.md b/AGENTS.md index 3aaada2132..e542fd462e 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -292,8 +292,11 @@ and its bindings) owns its reviewed workflow packages, durable run state, prepared commands, waits, and audit journal, and never product authority, data, eligibility, or capacity. A wait never renews an approval or creates downstream authority. The runtime may depend on product clients, product -cores, `registry-record`, and `registry-platform-*`, never on a product -runtime, adopter tooling, a supporting service, or a binding; it reaches +cores, `registry-record`, and `registry-platform-*`. It may depend directly on +the runtime-free `registry-review-protocol` handoff contract and may reach +`registry-payment-protocol` only through `registry-payment-client`; these do +not admit other protocol crates. It never depends on a product runtime, +adopter tooling, a supporting service, or a binding; it reaches Casework through `registry-casework-client` alone; its client reaches `registry-platform-*` only. No product crate depends on a Coordinator crate (only `registry-cli-docs` may), and the Casework, Scheduling, and Messaging diff --git a/products/adapter/scripts/check-contracts.sh b/products/adapter/scripts/check-contracts.sh index 6f36882036..d808eb0613 100755 --- a/products/adapter/scripts/check-contracts.sh +++ b/products/adapter/scripts/check-contracts.sh @@ -10,6 +10,7 @@ cd "$repo_root" source "$repo_root/products/adapter/scripts/contract-lane-cache.sh" python3 -m unittest discover -s products/adapter/scripts -p 'test_contract_lane_cache.py' python3 -m unittest discover -s products/adapter/scripts -p 'test_effective_contract_example.py' +node --test "$repo_root/products/adapter/scripts/payment-native-support.test.mjs" # The dependency-direction gate runs first, before any cargo build: its # unittest, then the check against the resolved graph and the engine diff --git a/products/adapter/scripts/payment-native-support.mjs b/products/adapter/scripts/payment-native-support.mjs index 081f20b61a..aaa0c7270c 100644 --- a/products/adapter/scripts/payment-native-support.mjs +++ b/products/adapter/scripts/payment-native-support.mjs @@ -80,26 +80,35 @@ export function start(binary, args, logPath, env = process.env) { }; } -export function loopback(origin) { - const url = new URL(origin); +function numericLoopbackHttp(value, message) { + let url; + try { url = new URL(value); } catch { assert.fail(message); } assert(url.protocol === 'http:' && ['127.0.0.1', '[::1]'].includes(url.hostname) - && !url.username && !url.password && !url.search && !url.hash && url.pathname === '/', - 'native payment acceptance requires a numeric loopback HTTP origin'); + && !url.username && !url.password, message); + return url; +} + +export function loopback(origin) { + const message = 'native payment acceptance requires a numeric loopback HTTP origin'; + const url = numericLoopbackHttp(origin, message); + assert(!url.search && !url.hash && url.pathname === '/', message); return url.origin; } export async function exchange(method, url, { token, body, key, expected = [200] } = {}) { + const requestUrl = numericLoopbackHttp(url, + 'native payment acceptance requires a numeric loopback HTTP request without user information').href; const headers = {}; if (token) headers.Authorization = `Bearer ${token}`; if (key) headers['Idempotency-Key'] = key; if (body !== undefined) headers['Content-Type'] = 'application/json'; - const response = await fetch(url, { method, headers, body: body === undefined ? undefined : JSON.stringify(body), + const response = await fetch(requestUrl, { method, headers, body: body === undefined ? undefined : JSON.stringify(body), redirect: 'manual', signal: AbortSignal.timeout(20000) }); const bytes = await response.arrayBuffer(); assert(bytes.byteLength <= 1048576, 'native response exceeded its fixture bound'); const value = bytes.byteLength ? JSON.parse(Buffer.from(bytes).toString()) : null; const code = typeof value?.code === 'string' && /^[a-z][a-z0-9_.-]{1,100}$/.test(value.code) ? ` (${value.code})` : ''; - assert(expected.includes(response.status), `native ${method} ${new URL(url).pathname} returned HTTP ${response.status}${code}`); + assert(expected.includes(response.status), `native ${method} ${new URL(requestUrl).pathname} returned HTTP ${response.status}${code}`); return { status: response.status, body: value }; } diff --git a/products/adapter/scripts/payment-native-support.test.mjs b/products/adapter/scripts/payment-native-support.test.mjs new file mode 100644 index 0000000000..11ced66679 --- /dev/null +++ b/products/adapter/scripts/payment-native-support.test.mjs @@ -0,0 +1,88 @@ +// SPDX-License-Identifier: Apache-2.0 +import assert from 'node:assert/strict'; +import http from 'node:http'; +import { test } from 'node:test'; + +import { exchange } from './payment-native-support.mjs'; + +async function listen(server) { + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); + return `http://127.0.0.1:${server.address().port}`; +} + +async function close(server) { + server.closeAllConnections(); + await new Promise((resolve) => server.close(resolve)); +} + +test('exchange rejects a substituted route that escapes loopback before fetch', async () => { + const originalFetch = globalThis.fetch; + let fetches = 0; + globalThis.fetch = async () => { + fetches += 1; + return new Response('{}', { status: 200, headers: { 'Content-Type': 'application/json' } }); + }; + try { + for (const destination of [ + 'http://127.0.0.1:4321@203.0.113.1/probe', + 'http://localhost:4321/probe', + 'https://127.0.0.1:4321/probe', + 'http://synthetic-user@127.0.0.1:4321/probe', + ]) { + await assert.rejects( + exchange('POST', destination, { + token: 'synthetic-token', body: { mode: 'synthetic' }, key: 'synthetic-key', + }), + /numeric loopback HTTP request/, + ); + } + assert.equal(fetches, 0); + } finally { + globalThis.fetch = originalFetch; + } +}); + +test('exchange preserves valid loopback path, query, headers and body', async (t) => { + let received; + const server = http.createServer(async (request, response) => { + const chunks = []; + for await (const chunk of request) chunks.push(chunk); + received = { method: request.method, url: request.url, headers: request.headers, + body: JSON.parse(Buffer.concat(chunks).toString()) }; + response.writeHead(200, { 'Content-Type': 'application/json' }); + response.end(JSON.stringify({ accepted: true })); + }); + const origin = await listen(server); + t.after(() => close(server)); + + const response = await exchange('POST', `${origin}/v1/collections?mode=synthetic`, { + token: 'synthetic-token', body: { amount: '25.00' }, key: 'synthetic-key', + }); + + assert.deepEqual(response, { status: 200, body: { accepted: true } }); + assert.equal(received.method, 'POST'); + assert.equal(received.url, '/v1/collections?mode=synthetic'); + assert.equal(received.headers.authorization, 'Bearer synthetic-token'); + assert.equal(received.headers['idempotency-key'], 'synthetic-key'); + assert.equal(received.headers['content-type'], 'application/json'); + assert.deepEqual(received.body, { amount: '25.00' }); +}); + +test('exchange leaves redirects unfollowed', async (t) => { + let followed = 0; + const server = http.createServer((request, response) => { + if (request.url === '/redirect') { + response.writeHead(302, { Location: '/followed' }); + response.end(); + return; + } + followed += 1; + response.writeHead(200, { 'Content-Type': 'application/json' }); + response.end('{}'); + }); + const origin = await listen(server); + t.after(() => close(server)); + + assert.deepEqual(await exchange('GET', `${origin}/redirect`, { expected: [302] }), { status: 302, body: null }); + assert.equal(followed, 0); +}); diff --git a/products/coordinator/AGENTS.md b/products/coordinator/AGENTS.md index 14230f4223..2daa65a41c 100644 --- a/products/coordinator/AGENTS.md +++ b/products/coordinator/AGENTS.md @@ -13,13 +13,16 @@ receives the call, which decides it under its own authorization. - Reach a product only over its public HTTP contract, through its maintained Rust client. The runtime may depend on product clients, product cores, - `registry-record`, and `registry-platform-*`; never on a product runtime, - adopter tooling, a supporting service, or a language binding. Never write - to another product's database. Tests compose with another product the same - way, through its built executable and public HTTP contract, never through a - runtime dev-dependency. Its combined CLI may use `registry-cli-api` for - product-neutral HTTP and connection handling; that helper carries no - product runtime or authority. + `registry-record`, and `registry-platform-*`. It may depend directly on the + runtime-free `registry-review-protocol` handoff contract and may reach + `registry-payment-protocol` only through `registry-payment-client`; these + are not a general allowance for protocol crates. It never depends on a + product runtime, adopter tooling, a supporting service, or a language binding. + Never write to another product's database. Tests compose with another + product the same way, through its built executable and public HTTP contract, + never through a runtime dev-dependency. Its combined CLI may use + `registry-cli-api` for product-neutral HTTP and connection handling; that + helper carries no product runtime or authority. - The Coordinator inherits no authorization. A caller allowed to start a run is not thereby allowed the effects its workflow requests: every product decides each call it receives under its own policy, and a wait never renews an diff --git a/products/coordinator/scripts/check_dependency_direction.py b/products/coordinator/scripts/check_dependency_direction.py index a9a2821531..1284891fef 100644 --- a/products/coordinator/scripts/check_dependency_direction.py +++ b/products/coordinator/scripts/check_dependency_direction.py @@ -2,11 +2,12 @@ """Check Coordinator dependency direction from Cargo's resolved graph. The Coordinator composes products only through their public product clients. -Its runtime may reach product clients, product cores, `registry-record` and -shared platform primitives, and nothing else of the workspace: never another -product's runtime, adopter tooling, supporting service or binding. A core named -below is reached only through its product client, never as a direct dependency -of the runtime. Its client +Its runtime may reach product clients, their named runtime-free support +contracts, product cores, `registry-record` and shared platform primitives, +and nothing else of the workspace: never another product's runtime, adopter +tooling, supporting service or binding. A support package or core in a +client-only map below is reached only through its product client, never as a +direct dependency of the runtime. Its client reaches the runtime over the public HTTP contract only and links shared platform primitives alone. No crate outside the Coordinator depends on a Coordinator crate unless it is named below. @@ -42,6 +43,12 @@ "registry-review-protocol": "the review handoff contract registry-casework-client carries", } +# Runtime-free contracts the runtime reaches only through their product client. +# Keep this exact: a `*-protocol` suffix does not by itself make a package safe. +CLIENT_ONLY_SUPPORT = { + "registry-payment-protocol": "registry-payment-client", +} + # The combined Coordinator crate also publishes coordinatorctl. This helper # supplies its product-neutral request/connection CLI and reaches no product. CLI_SUPPORT = frozenset({"registry-cli-api"}) @@ -88,16 +95,22 @@ def package_graph( return names, every, linked -def closure(start: str, every: dict[str, set[str]], linked: dict[str, set[str]]) -> set[str]: +def closure( + start: str, + every: dict[str, set[str]], + linked: dict[str, set[str]], + excluded: set[str] | None = None, +) -> set[str]: """Every package the start builds with, its own dev-dependencies included.""" + excluded = excluded or set() seen: set[str] = set() - pending = list(every.get(start, set())) + pending = list(every.get(start, set()) - excluded) while pending: package = pending.pop() if package in seen: continue seen.add(package) - pending.extend(linked.get(package, set()) - seen) + pending.extend(linked.get(package, set()) - seen - excluded) return seen @@ -108,6 +121,8 @@ def runtime_may_reach(name: str) -> bool: return True if name in CLIENT_SUPPORT: return True + if name in CLIENT_ONLY_SUPPORT: + return True if name in CLI_SUPPORT: return True if name.endswith("-core"): @@ -123,17 +138,36 @@ def client_may_reach(name: str) -> bool: def violations(metadata: dict) -> list[str]: names, every, linked = package_graph(metadata) + package_ids = {name: package_id for package_id, name in names.items()} failures: list[str] = [] for package_id, name in sorted(names.items(), key=lambda item: item[1]): - reached = {names[item] for item in closure(package_id, every, linked)} + reached_ids = closure(package_id, every, linked) + reached = {names[item] for item in reached_ids} if name == COORDINATOR_RUNTIME: refused = sorted(item for item in reached if not runtime_may_reach(item)) if refused: failures.append( - f"{name} reaches package(s) outside product clients, product cores, " - f"registry-record and registry-platform-*: {', '.join(refused)}" + f"{name} reaches package(s) outside product clients, named client " + f"support, product cores, registry-record and registry-platform-*: " + f"{', '.join(refused)}" ) direct = sorted(names[item] for item in every.get(package_id, set())) + for support in (item for item in direct if item in CLIENT_ONLY_SUPPORT): + failures.append( + f"{name} depends on {support} directly; " + f"reach it through {CLIENT_ONLY_SUPPORT[support]}" + ) + for support, client in CLIENT_ONLY_SUPPORT.items(): + support_id = package_ids.get(support) + client_id = package_ids.get(client) + if support_id not in reached_ids or support in direct: + continue + excluded = {client_id} if client_id else set() + if support_id in closure(package_id, every, linked, excluded): + failures.append( + f"{name} reaches {support} by a path outside {client}; " + f"reach it only through {client}" + ) for core in (item for item in direct if item in CLIENT_ONLY_CORES): failures.append( f"{name} depends on {core} directly; " diff --git a/products/coordinator/scripts/test_dependency_direction.py b/products/coordinator/scripts/test_dependency_direction.py index b8fa60fa46..f65538c8df 100644 --- a/products/coordinator/scripts/test_dependency_direction.py +++ b/products/coordinator/scripts/test_dependency_direction.py @@ -35,6 +35,9 @@ "messaging-client": "registry-messaging-client", "messaging-client-node": "registry-messaging-client-node", "messaging-core": "registry-messaging-core", + "payment-client": "registry-payment-client", + "payment-protocol": "registry-payment-protocol", + "other-protocol": "registry-other-protocol", "scheduling": "registry-scheduling", "scheduling-client": "registry-scheduling-client", "scheduling-core": "registry-scheduling-core", @@ -52,6 +55,7 @@ "casework-client", "messaging-client", "messaging-core", + "payment-client", "scheduling-client", "scheduling-core", "platform", @@ -77,6 +81,9 @@ "messaging-client": ["messaging-core", "platform"], "messaging-client-node": ["messaging-client"], "messaging-core": ["serde"], + "payment-client": ["payment-protocol", "platform"], + "payment-protocol": ["serde"], + "other-protocol": ["serde"], "scheduling": ["scheduling-core", "platform"], "scheduling-client": ["scheduling-core", "platform"], "scheduling-core": ["serde"], @@ -132,7 +139,8 @@ def test_the_runtime_reaching_a_product_runtime_is_refused(self): with self.subTest(product=product): self.assertIn( f"registry-coordinator reaches package(s) outside product clients, " - f"product cores, registry-record and registry-platform-*: " + f"named client support, product cores, registry-record and " + f"registry-platform-*: " f"{NAMES[product]}", failures(runtime=[*INTENDED["runtime"], product]), ) @@ -161,7 +169,8 @@ def test_a_product_runtime_behind_a_client_is_refused(self): def test_a_dev_dependency_of_the_runtime_counts(self): self.assertIn( "registry-coordinator reaches package(s) outside product clients, " - "product cores, registry-record and registry-platform-*: registry-messaging", + "named client support, product cores, registry-record and " + "registry-platform-*: registry-messaging", failures(runtime=[*INTENDED["runtime"], ("messaging", "dev")]), ) @@ -186,6 +195,53 @@ def test_client_support_is_admitted_only_by_name(self): ) self.assertEqual(MODULE.violations(metadata()), []) + def test_payment_protocol_is_admitted_only_through_its_client(self): + self.assertEqual( + MODULE.CLIENT_ONLY_SUPPORT, + {"registry-payment-protocol": "registry-payment-client"}, + ) + self.assertEqual(MODULE.violations(metadata()), []) + for kind in (None, "dev", "build"): + with self.subTest(kind=kind): + self.assertIn( + "registry-coordinator depends on registry-payment-protocol directly; " + "reach it through registry-payment-client", + failures( + runtime=[ + *INTENDED["runtime"], + ("payment-protocol", kind), + ] + ), + ) + + def test_payment_protocol_through_another_client_is_refused(self): + without_payment_client = [ + dependency + for dependency in INTENDED["runtime"] + if dependency != "payment-client" + ] + for runtime in (without_payment_client, INTENDED["runtime"]): + with self.subTest(payment_client_reached="payment-client" in runtime): + self.assertIn( + "registry-coordinator reaches registry-payment-protocol by a path " + "outside registry-payment-client; reach it only through " + "registry-payment-client", + failures( + runtime=runtime, + scheduling_client=[ + "scheduling-core", + "platform", + "payment-protocol", + ], + ), + ) + + def test_an_unlisted_protocol_is_refused(self): + self.assertIn( + "registry-other-protocol", + failures(runtime=[*INTENDED["runtime"], "other-protocol"]), + ) + def test_a_direct_casework_core_dependency_is_refused(self): for kind in (None, "dev", "build"): with self.subTest(kind=kind): From f80733e3965f2246f2b068b73d53f873c7e57ad2 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Thu, 12 Nov 2026 20:40:22 +0700 Subject: [PATCH 03/40] fix(breg): preserve operational database diagnostics Signed-off-by: Jeremi Joslin --- crates/registry-bregctl/src/lib.rs | 73 ++++++++++++++- crates/registry-bregctl/tests/cli.rs | 130 +++++++++++++++++++++++++-- 2 files changed, 194 insertions(+), 9 deletions(-) diff --git a/crates/registry-bregctl/src/lib.rs b/crates/registry-bregctl/src/lib.rs index 5c5f704f4c..7fc097600e 100644 --- a/crates/registry-bregctl/src/lib.rs +++ b/crates/registry-bregctl/src/lib.rs @@ -15269,7 +15269,7 @@ fn write_failure( let exit = if report .diagnostics .iter() - .any(|diagnostic| diagnostic.code.ends_with(".unavailable")) + .any(tool_diagnostic_is_operational) { OPERATIONAL_FAILURE_EXIT } else { @@ -15278,6 +15278,12 @@ fn write_failure( write_failure_with_exit(report, format, stdout, stderr, exit) } +fn tool_diagnostic_is_operational(diagnostic: &ToolDiagnostic) -> bool { + diagnostic.code.ends_with(".unavailable") + || (diagnostic.artifact == DiagnosticArtifact::SchemaTestDatabase + && diagnostic.suggested_action == SuggestedAction::PrepareSchemaTestDatabase) +} + fn write_failure_with_exit( report: &FailureReport, format: OutputFormat, @@ -15465,6 +15471,71 @@ mod tests { ); } + #[test] + fn schema_test_connection_causes_keep_their_result_class() { + use registry_breg::postgres::DatabaseConnectionCause; + + for (cause, code, exit, status) in [ + ( + DatabaseConnectionCause::Unreachable, + "test.database.unreachable", + OPERATIONAL_FAILURE_EXIT, + "operational-failure", + ), + ( + DatabaseConnectionCause::Capacity, + "test.database.capacity-exhausted", + OPERATIONAL_FAILURE_EXIT, + "operational-failure", + ), + ( + DatabaseConnectionCause::Tls, + "test.database.tls-refused", + OPERATIONAL_FAILURE_EXIT, + "operational-failure", + ), + ( + DatabaseConnectionCause::Authentication, + "test.database.authentication-refused", + OPERATIONAL_FAILURE_EXIT, + "operational-failure", + ), + ( + DatabaseConnectionCause::DatabaseMissing, + "test.database.missing", + OPERATIONAL_FAILURE_EXIT, + "operational-failure", + ), + ( + DatabaseConnectionCause::Timeout, + "test.database.timeout", + OPERATIONAL_FAILURE_EXIT, + "operational-failure", + ), + ( + DatabaseConnectionCause::Configuration, + "test.database.configuration-refused", + DOMAIN_REFUSAL_EXIT, + "domain-refusal", + ), + ( + DatabaseConnectionCause::Secret, + "test.database.secret-refused", + DOMAIN_REFUSAL_EXIT, + "domain-refusal", + ), + ] { + let report = schema_test_database_connection_failure(cause); + let (mut stdout, mut stderr) = (Vec::new(), Vec::new()); + let actual_exit = write_failure(&report, OutputFormat::Json, &mut stdout, &mut stderr); + assert_eq!(actual_exit, ExitCode::from(exit), "{code}"); + assert!(stderr.is_empty(), "{code}"); + let value: Value = serde_json::from_slice(&stdout).unwrap(); + assert_eq!(value["diagnostics"][0]["code"], code); + assert_eq!(value["status"], status, "{code}"); + } + } + #[test] fn diagnostic_and_assurance_words_use_the_public_kebab_case_contract() { assert_eq!( diff --git a/crates/registry-bregctl/tests/cli.rs b/crates/registry-bregctl/tests/cli.rs index c1c7e35ff0..729f89caea 100644 --- a/crates/registry-bregctl/tests/cli.rs +++ b/crates/registry-bregctl/tests/cli.rs @@ -2506,6 +2506,51 @@ fn test_candidate_command( ]) } +fn test_candidate_command_with_unreachable_database( + project: &TestProject, + runtime_config: &Path, + credentials: &Path, + output: &Path, +) -> Output { + bregctl_schema_test_with_unreachable_database(&[ + "--format", + "json", + "test", + path(project.path()), + "--runtime-config", + path(runtime_config), + "--credentials", + path(credentials), + "--output", + path(output), + ]) +} + +fn test_candidate_command_with_refused_database_secrets( + project: &TestProject, + runtime_config: &Path, + credentials: &Path, + output: &Path, +) -> Output { + Command::new(env!("CARGO_BIN_EXE_bregctl")) + .env_remove(VERIFY_RUNTIME_DATABASE_SECRET_CANARY) + .env_remove(VERIFY_MIGRATION_DATABASE_SECRET_CANARY) + .args([ + "--format", + "json", + "test", + path(project.path()), + "--runtime-config", + path(runtime_config), + "--credentials", + path(credentials), + "--output", + path(output), + ]) + .output() + .expect("bregctl starts") +} + fn json_stdout(output: &Output) -> Value { let report: Value = serde_json::from_slice(&output.stdout).expect("command stdout is JSON"); let status = match output.status.code().expect("command exited normally") { @@ -8061,10 +8106,11 @@ fn test_fingerprint_only_needs_only_the_runtime_configuration() { ); // Without credentials or an output, the measurement still reaches the - // configured database; the fixture names one that is unavailable. + // configured database; both connection secrets resolve to an address + // where nothing listens. let candidate = packaging_project(); let candidate_runtime = test_runtime_config(&candidate); - let measured = bregctl(&[ + let measured = bregctl_schema_test_with_unreachable_database(&[ "--format", "json", "test", @@ -8078,7 +8124,7 @@ fn test_fingerprint_only_needs_only_the_runtime_configuration() { assert_eq!(report["command"], "test"); assert_eq!( report["diagnostics"][0]["code"], - "test.database.unavailable" + "test.database.unreachable" ); assert!(!candidate.path().join("schema-test-receipt.json").exists()); } @@ -8411,14 +8457,15 @@ fn test_valid_credentials_reach_database_and_never_publish_partial_receipts() { ) .expect("credential fixture writes"); let output = project.path().join("schema-test-receipt.json"); - let result = test_candidate_command(&project, &runtime, &credentials, &output); + let result = + test_candidate_command_with_unreachable_database(&project, &runtime, &credentials, &output); assert_schema_test_refusal( result, 3, - "test.database.unavailable", + "test.database.unreachable", "schema-test-database", - "recreate-disposable-database", + "prepare-schema-test-database", &output, &[ path(project.path()), @@ -8426,6 +8473,8 @@ fn test_valid_credentials_reach_database_and_never_publish_partial_receipts() { path(&credentials), "aaa.bbb.ccc", "secret:file/operator-token", + "postgresql://registry_runtime@127.0.0.1:1/breg", + "postgresql://registry_migration@127.0.0.1:1/breg", PACKAGE_VALUE_CANARY, ], ); @@ -8443,6 +8492,45 @@ fn test_valid_credentials_reach_database_and_never_publish_partial_receipts() { ); } +#[test] +fn test_database_secret_refusal_is_value_free_and_never_publishes_a_receipt() { + let project = packaging_project(); + let runtime = test_runtime_config(&project); + write_test_secret(&project, "operator-token", b"aaa.bbb.ccc"); + let credentials = project.path().join("valid-credentials.yaml"); + fs::write( + &credentials, + credential_source("type: bearer\n tokenRef: secret:file/operator-token\n"), + ) + .expect("credential fixture writes"); + let output = project.path().join("schema-test-receipt.json"); + let result = test_candidate_command_with_refused_database_secrets( + &project, + &runtime, + &credentials, + &output, + ); + + assert_schema_test_refusal( + result, + 1, + "test.database.secret-refused", + "schema-test-database", + "correct-runtime-configuration", + &output, + &[ + path(project.path()), + path(&runtime), + path(&credentials), + "aaa.bbb.ccc", + "secret:file/operator-token", + PACKAGE_VALUE_CANARY, + VERIFY_RUNTIME_DATABASE_SECRET_CANARY, + VERIFY_MIGRATION_DATABASE_SECRET_CANARY, + ], + ); +} + #[test] fn authoring_and_test_candidate_sources_are_read_once_and_bounded() { let oversized_yaml_comment = vec![b'#'; SCHEMA_TEST_AUTHORED_SOURCE_CEILING_BYTES + 1]; @@ -9019,8 +9107,8 @@ fn plan_and_status_refuse_before_database_authority_and_name_the_next_command() } /// Runs bregctl with the fixture's migration credential set to a database -/// URL nothing listens on, so a refusal that reaches database contact reports -/// the database as unavailable. +/// URL nothing listens on, so a refusal that reaches migration database +/// contact reports the connection as unavailable. fn bregctl_with_unreachable_database(arguments: &[&str]) -> Output { Command::new(env!("CARGO_BIN_EXE_bregctl")) .env( @@ -9032,6 +9120,24 @@ fn bregctl_with_unreachable_database(arguments: &[&str]) -> Output { .expect("bregctl starts") } +/// Schema-test opens both configured database roles. Supply both connection +/// secrets with addresses where nothing listens so the specific connection +/// refusal, rather than secret resolution, is exercised. +fn bregctl_schema_test_with_unreachable_database(arguments: &[&str]) -> Output { + Command::new(env!("CARGO_BIN_EXE_bregctl")) + .env( + VERIFY_RUNTIME_DATABASE_SECRET_CANARY, + "postgresql://registry_runtime@127.0.0.1:1/breg", + ) + .env( + VERIFY_MIGRATION_DATABASE_SECRET_CANARY, + "postgresql://registry_migration@127.0.0.1:1/breg", + ) + .args(arguments) + .output() + .expect("bregctl starts") +} + #[test] fn apply_and_plan_refuse_a_package_other_than_the_expected_digest_before_database_contact() { let fixture = RuntimePackageFixture::production("127.0.0.1:1".parse().unwrap()); @@ -10891,6 +10997,14 @@ fn assert_schema_test_refusal( } let report: Value = serde_json::from_str(&rendered).expect("refusal JSON parses"); assert_eq!(report["command"], "test"); + assert_eq!( + report["status"], + match expected_exit { + 1 => "domain-refusal", + 3 => "operational-failure", + exit => panic!("unsupported refusal exit in test helper: {exit}"), + } + ); assert_eq!(report["diagnostics"][0]["code"], expected_code); assert_tool_diagnostic(&report["diagnostics"][0], artifact, action); } From d6d629ae037897bfb6e0981d2dd20db53f049abe Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 13 Nov 2026 03:29:25 +0700 Subject: [PATCH 04/40] feat(platform): bind legacy RSA signatures to pinned Transit keys Signed-off-by: Jeremi Joslin --- crates/registry-platform-crypto/README.md | 10 + crates/registry-platform-crypto/src/lib.rs | 25 +- .../src/transit_rsa_no_oid.rs | 1288 +++++++++++++++++ ...ifos-bulk-v1.12.1-response-signatures.json | 13 + 4 files changed, 1332 insertions(+), 4 deletions(-) create mode 100644 crates/registry-platform-crypto/src/transit_rsa_no_oid.rs create mode 100644 crates/registry-platform-crypto/tests/fixtures/mifos-bulk-v1.12.1-response-signatures.json diff --git a/crates/registry-platform-crypto/README.md b/crates/registry-platform-crypto/README.md index ce26784d7a..f7ca3557d4 100644 --- a/crates/registry-platform-crypto/README.md +++ b/crates/registry-platform-crypto/README.md @@ -237,6 +237,16 @@ interoperability and security policy. key, so the caller anchors it before relying on a signature: it requests a certificate for the key, or checks the key against the certificate that certifies it, as a document seal does. +- `transit_rsa_no_oid` is the opt-in raw Transit primitive for a reviewed + legacy profile that signs a 64-byte lowercase hexadecimal digest with RSA + PKCS#1 v1.5 and no digest OID. It pins the exact RSA public SPKI DER SHA-256 + and key version, revalidates that binding and custody metadata before every + sign or verify, uses fixed `/none` endpoints through the bounded Unix-socket + proxy with redirects disabled, and verifies each signer result through the + pinned key before release. The signer requires a service-created key. The + `imported_key` flag records the origin of the verification entry. Operators + import only the provider's public key for that entry and grant the trusted + proxy verify-only access to it. - Readiness-gated live apply should use `KeyReadinessSnapshot`; only `status = active` plus `readiness = ready` is accepted. Degraded, not-ready, unknown, publish-only, and disabled keys fail closed before diff --git a/crates/registry-platform-crypto/src/lib.rs b/crates/registry-platform-crypto/src/lib.rs index 76c10fada7..faccbc2ced 100644 --- a/crates/registry-platform-crypto/src/lib.rs +++ b/crates/registry-platform-crypto/src/lib.rs @@ -15,6 +15,8 @@ pub mod sealed_value; pub mod transit_datakey; #[cfg(all(test, unix, feature = "transit"))] mod transit_mock; +#[cfg(feature = "transit")] +pub mod transit_rsa_no_oid; #[cfg(feature = "xchacha-seal")] pub mod xchacha_seal; @@ -1163,13 +1165,18 @@ fn transit_public_jwk(pem: &str) -> Result { #[cfg(feature = "transit")] fn build_transit_client(socket_path: &Path) -> Result { + transit_client_builder(socket_path)? + .build() + .map_err(|_| transit_error("transit provider configuration is invalid")) +} + +#[cfg(feature = "transit")] +fn transit_client_builder(socket_path: &Path) -> Result { #[cfg(unix)] { - reqwest::Client::builder() + Ok(reqwest::Client::builder() .no_proxy() - .unix_socket(socket_path.to_path_buf()) - .build() - .map_err(|_| transit_error("transit provider configuration is invalid")) + .unix_socket(socket_path.to_path_buf())) } #[cfg(not(unix))] { @@ -1180,6 +1187,16 @@ fn build_transit_client(socket_path: &Path) -> Result Result { + transit_client_builder(socket_path)? + .redirect(reqwest::redirect::Policy::none()) + .build() + .map_err(|_| transit_error("transit provider configuration is invalid")) +} + #[cfg(feature = "transit")] async fn read_bounded_transit_response( mut response: reqwest::Response, diff --git a/crates/registry-platform-crypto/src/transit_rsa_no_oid.rs b/crates/registry-platform-crypto/src/transit_rsa_no_oid.rs new file mode 100644 index 0000000000..bbdd41b39c --- /dev/null +++ b/crates/registry-platform-crypto/src/transit_rsa_no_oid.rs @@ -0,0 +1,1288 @@ +// SPDX-License-Identifier: Apache-2.0 + +//! Raw RSA PKCS#1 v1.5 Transit signing and verification without a digest OID. +//! +//! The primitive sends a fixed-size lowercase hexadecimal digest to the +//! Unix-socket Transit provider. Product code owns headers, roles, custody +//! configuration, authorization, and outer signature encoding. + +use std::fmt; +use std::path::PathBuf; +use std::time::Duration; + +use aws_lc_rs::rsa::PublicKey as RsaPublicKey; +use base64::engine::general_purpose::STANDARD; +use base64::Engine as _; +use pkcs1::der::Decode as _; +use serde_json::{json, Value}; +use sha2::{Digest as _, Sha256}; +use thiserror::Error; +use zeroize::Zeroizing; + +use crate::{ + build_transit_client_no_redirects, send_transit_json, transit_metadata_url, + valid_transit_binding, TransitRequestFault, +}; + +const SELF_TEST_DIGEST: &[u8; 64] = + b"0000000000000000000000000000000000000000000000000000000000000000"; + +/// Validated connection, provider identity, and immutable RSA key binding. +/// +/// Socket, mount, and key names are deliberately absent from `Debug` and all +/// errors because they reveal deployment topology. +#[derive(Clone)] +pub struct TransitRsaNoOidKeyConfig { + socket_path: PathBuf, + mount_path: String, + key_name: String, + key_version: u32, + public_key_sha256: [u8; 32], + request_timeout: Duration, +} + +impl TransitRsaNoOidKeyConfig { + /// Bind the exact SPKI DER identity of one RSA Transit key version. + /// + /// # Errors + /// + /// Returns [`TransitRsaNoOidError::InvalidConfiguration`] when any local + /// binding or request bound is unsafe. + pub fn new( + socket_path: PathBuf, + mount_path: String, + key_name: String, + key_version: u32, + public_key_sha256: [u8; 32], + request_timeout: Duration, + ) -> Result { + if !valid_transit_binding( + &socket_path, + &mount_path, + &key_name, + key_version, + request_timeout, + ) { + return Err(TransitRsaNoOidError::InvalidConfiguration); + } + Ok(Self { + socket_path, + mount_path, + key_name, + key_version, + public_key_sha256, + request_timeout, + }) + } +} + +impl fmt::Debug for TransitRsaNoOidKeyConfig { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter + .debug_struct("TransitRsaNoOidKeyConfig") + .finish_non_exhaustive() + } +} + +/// A raw RSA signature whose allocation is erased on drop. +pub struct TransitRsaNoOidSignature(Zeroizing>); + +impl TransitRsaNoOidSignature { + /// Borrow the exact RSA signature bytes, without an outer encoding. + #[must_use] + pub fn as_bytes(&self) -> &[u8] { + self.0.as_slice() + } +} + +/// A redacted refusal from the raw RSA Transit primitive. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Error)] +#[non_exhaustive] +pub enum TransitRsaNoOidError { + #[error("the Transit RSA configuration is invalid")] + InvalidConfiguration, + #[error("the Transit client could not be built for the configured Unix socket")] + Client, + #[error("the Transit provider did not answer on the configured Unix socket")] + Unavailable, + #[error("the Transit provider refused the request")] + Refused, + #[error("the Transit provider failed the request")] + ProviderFailed, + #[error("the Transit provider response is malformed or too large")] + InvalidResponse, + #[error("the Transit RSA key custody metadata is unsafe for this role")] + UnsafeCustody, + #[error("the configured Transit RSA key version has not been created")] + KeyVersionNotCreated, + #[error("the configured Transit RSA key version is retired for this operation")] + KeyVersionRetired, + #[error("the Transit RSA public key is invalid or has the wrong size")] + InvalidPublicKey, + #[error("the Transit RSA public key does not match the configured SPKI digest")] + PublicKeyMismatch, + #[error("the Transit RSA signer self-test failed")] + SelfTest, + #[error("the Transit RSA verifier policy probe failed")] + PolicyProbe, + #[error("the digest must be exactly 64 lowercase hexadecimal ASCII bytes")] + InvalidDigest, + #[error("the Transit RSA signature is malformed")] + InvalidSignature, + #[error("the Transit RSA signature did not verify")] + VerificationFailed, +} + +fn request_error(fault: TransitRequestFault) -> TransitRsaNoOidError { + match fault { + TransitRequestFault::Unavailable => TransitRsaNoOidError::Unavailable, + TransitRequestFault::Refused => TransitRsaNoOidError::Refused, + TransitRequestFault::ProviderFailed => TransitRsaNoOidError::ProviderFailed, + TransitRequestFault::InvalidResponse => TransitRsaNoOidError::InvalidResponse, + } +} + +#[derive(Clone, Copy)] +enum KeyRole { + Signer, + Verifier, +} + +struct TransitRsaNoOidClient { + client: reqwest::Client, + metadata_url: String, + sign_url: String, + verify_url: String, + key_version: u32, + public_key_sha256: [u8; 32], + request_timeout: Duration, + modulus_bytes: usize, + role: KeyRole, +} + +impl TransitRsaNoOidClient { + async fn initialize( + config: TransitRsaNoOidKeyConfig, + role: KeyRole, + ) -> Result { + let client = build_transit_client_no_redirects(&config.socket_path) + .map_err(|_| TransitRsaNoOidError::Client)?; + let mut binding = Self { + client, + metadata_url: transit_metadata_url(&config.mount_path, &config.key_name), + sign_url: format!( + "http://localhost/v1/{}/sign/{}/none", + config.mount_path, config.key_name + ), + verify_url: format!( + "http://localhost/v1/{}/verify/{}/none", + config.mount_path, config.key_name + ), + key_version: config.key_version, + public_key_sha256: config.public_key_sha256, + request_timeout: config.request_timeout, + modulus_bytes: 0, + role, + }; + binding.modulus_bytes = binding.read_and_validate_metadata().await?; + Ok(binding) + } + + async fn request_json( + &self, + method: reqwest::Method, + url: &str, + body: Option<&Value>, + ) -> Result { + send_transit_json(&self.client, self.request_timeout, method, url, body) + .await + .map_err(request_error) + } + + async fn read_and_validate_metadata(&self) -> Result { + let document = self + .request_json(reqwest::Method::GET, &self.metadata_url, None) + .await?; + self.validate_metadata(&document) + } + + async fn revalidate_metadata(&self) -> Result<(), TransitRsaNoOidError> { + if self.read_and_validate_metadata().await? != self.modulus_bytes { + return Err(TransitRsaNoOidError::InvalidPublicKey); + } + Ok(()) + } + + fn validate_metadata(&self, document: &Value) -> Result { + let data = document + .get("data") + .and_then(Value::as_object) + .ok_or(TransitRsaNoOidError::InvalidResponse)?; + let required_false = ["derived", "exportable", "allow_plaintext_backup"]; + let imported_key = data + .get("imported_key") + .and_then(Value::as_bool) + .ok_or(TransitRsaNoOidError::InvalidResponse)?; + let role_custody_matches = match self.role { + KeyRole::Signer => !imported_key, + KeyRole::Verifier => imported_key, + }; + if data.get("supports_signing").and_then(Value::as_bool) != Some(true) + || required_false + .iter() + .any(|field| data.get(*field).and_then(Value::as_bool) != Some(false)) + || !role_custody_matches + { + return Err(TransitRsaNoOidError::UnsafeCustody); + } + + let latest_version = metadata_u32(data, "latest_version")?; + if self.key_version > latest_version { + return Err(TransitRsaNoOidError::KeyVersionNotCreated); + } + let minimum_field = match self.role { + KeyRole::Signer => "min_encryption_version", + KeyRole::Verifier => "min_decryption_version", + }; + let minimum_version = metadata_u32(data, minimum_field)?; + if minimum_version != 0 && self.key_version < minimum_version { + return Err(TransitRsaNoOidError::KeyVersionRetired); + } + + let version = self.key_version.to_string(); + let public_pem = data + .get("keys") + .and_then(Value::as_object) + .and_then(|keys| keys.get(&version)) + .and_then(Value::as_object) + .and_then(|key| key.get("public_key")) + .and_then(Value::as_str) + .ok_or(TransitRsaNoOidError::InvalidPublicKey)?; + let spki_der = decode_public_key_pem(public_pem)?; + let actual_spki_sha256: [u8; 32] = Sha256::digest(spki_der.as_slice()).into(); + if actual_spki_sha256 != self.public_key_sha256 { + return Err(TransitRsaNoOidError::PublicKeyMismatch); + } + let key = RsaPublicKey::from_der(spki_der.as_slice()) + .map_err(|_| TransitRsaNoOidError::InvalidPublicKey)?; + let pkcs1 = pkcs1::RsaPublicKey::from_der(key.as_ref()) + .map_err(|_| TransitRsaNoOidError::InvalidPublicKey)?; + let modulus = pkcs1.modulus.as_bytes(); + let modulus_bits = exact_bit_length(modulus)?; + let metadata_bits = match data.get("type").and_then(Value::as_str) { + Some("rsa-2048") => 2048, + Some("rsa-3072") => 3072, + Some("rsa-4096") => 4096, + _ => return Err(TransitRsaNoOidError::InvalidPublicKey), + }; + if modulus_bits != metadata_bits { + return Err(TransitRsaNoOidError::InvalidPublicKey); + } + Ok(modulus.len()) + } + + async fn request_signature( + &self, + input: &[u8; 64], + ) -> Result { + validate_digest(input)?; + self.revalidate_metadata().await?; + let body = json!({ + "input": STANDARD.encode(input), + "key_version": self.key_version, + "prehashed": true, + "signature_algorithm": "pkcs1v15", + }); + let mut document = self + .request_json(reqwest::Method::POST, &self.sign_url, Some(&body)) + .await?; + let signature = document + .get_mut("data") + .and_then(Value::as_object_mut) + .and_then(|data| data.get_mut("signature")) + .and_then(|value| match value { + Value::String(signature) => Some(signature), + _ => None, + }) + .ok_or(TransitRsaNoOidError::InvalidSignature)?; + let signature = Zeroizing::new(std::mem::take(signature)); + let prefix = format!("vault:v{}:", self.key_version); + let encoded = signature + .strip_prefix(&prefix) + .ok_or(TransitRsaNoOidError::InvalidSignature)?; + let decoded = Zeroizing::new( + STANDARD + .decode(encoded) + .map_err(|_| TransitRsaNoOidError::InvalidSignature)?, + ); + if decoded.len() != self.modulus_bytes || STANDARD.encode(decoded.as_slice()) != encoded { + return Err(TransitRsaNoOidError::InvalidSignature); + } + Ok(TransitRsaNoOidSignature(decoded)) + } + + async fn request_verification( + &self, + input: &[u8; 64], + signature: &[u8], + ) -> Result { + validate_digest(input)?; + if signature.len() != self.modulus_bytes { + return Err(TransitRsaNoOidError::InvalidSignature); + } + self.revalidate_metadata().await?; + let body = json!({ + "input": STANDARD.encode(input), + "prehashed": true, + "signature": format!( + "vault:v{}:{}", + self.key_version, + STANDARD.encode(signature) + ), + "signature_algorithm": "pkcs1v15", + }); + let document = self + .request_json(reqwest::Method::POST, &self.verify_url, Some(&body)) + .await?; + document + .get("data") + .and_then(|data| data.get("valid")) + .and_then(Value::as_bool) + .ok_or(TransitRsaNoOidError::InvalidResponse) + } +} + +/// Service-created raw RSA signer reached through a trusted local proxy. +pub struct TransitRsaNoOidSigner(TransitRsaNoOidClient); + +impl fmt::Debug for TransitRsaNoOidSigner { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter + .debug_struct("TransitRsaNoOidSigner") + .finish_non_exhaustive() + } +} + +impl TransitRsaNoOidSigner { + /// Validate the service-created key and prove sign plus pinned-key verify. + /// + /// # Errors + /// + /// Returns a redacted provider, custody, key-binding, or self-test error. + pub async fn initialize( + config: TransitRsaNoOidKeyConfig, + ) -> Result { + let client = TransitRsaNoOidClient::initialize(config, KeyRole::Signer).await?; + let signature = client + .request_signature(SELF_TEST_DIGEST) + .await + .map_err(|_| TransitRsaNoOidError::SelfTest)?; + let valid = client + .request_verification(SELF_TEST_DIGEST, signature.as_bytes()) + .await + .map_err(|_| TransitRsaNoOidError::SelfTest)?; + if !valid { + return Err(TransitRsaNoOidError::SelfTest); + } + Ok(Self(client)) + } + + /// Sign one 64-byte lowercase hexadecimal digest string and verify the + /// provider result with the same pinned key before releasing it. + /// + /// # Errors + /// + /// Returns a redacted validation, provider, key-binding, signature, or + /// verification error. + pub async fn sign_digest_hex( + &self, + input: &[u8; 64], + ) -> Result { + let signature = self.0.request_signature(input).await?; + if !self + .0 + .request_verification(input, signature.as_bytes()) + .await? + { + return Err(TransitRsaNoOidError::VerificationFailed); + } + Ok(signature) + } +} + +/// Operator-imported public-key verifier reached through a trusted local proxy. +pub struct TransitRsaNoOidVerifier(TransitRsaNoOidClient); + +impl fmt::Debug for TransitRsaNoOidVerifier { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter + .debug_struct("TransitRsaNoOidVerifier") + .finish_non_exhaustive() + } +} + +impl TransitRsaNoOidVerifier { + /// Validate the imported public key and prove the verify endpoint rejects + /// a fixed, deliberately invalid modulus-width signature before serving. + /// + /// # Errors + /// + /// Returns a redacted provider, custody, key-binding, or policy-probe + /// error. + pub async fn initialize( + config: TransitRsaNoOidKeyConfig, + ) -> Result { + let client = TransitRsaNoOidClient::initialize(config, KeyRole::Verifier).await?; + let invalid_signature = Zeroizing::new(vec![0_u8; client.modulus_bytes]); + match client + .request_verification(SELF_TEST_DIGEST, &invalid_signature) + .await + { + Ok(false) => Ok(Self(client)), + Ok(true) | Err(_) => Err(TransitRsaNoOidError::PolicyProbe), + } + } + + /// Verify a raw modulus-width signature over one lowercase hex digest. + /// + /// # Errors + /// + /// Returns a redacted validation, provider, key-binding, signature, or + /// verification error. + pub async fn verify_digest_hex( + &self, + input: &[u8; 64], + signature: &[u8], + ) -> Result<(), TransitRsaNoOidError> { + if self.0.request_verification(input, signature).await? { + Ok(()) + } else { + Err(TransitRsaNoOidError::VerificationFailed) + } + } +} + +fn metadata_u32( + data: &serde_json::Map, + field: &str, +) -> Result { + data.get(field) + .and_then(Value::as_u64) + .and_then(|value| u32::try_from(value).ok()) + .ok_or(TransitRsaNoOidError::InvalidResponse) +} + +fn decode_public_key_pem(pem: &str) -> Result>, TransitRsaNoOidError> { + let (label, document) = + p256::pkcs8::Document::from_pem(pem).map_err(|_| TransitRsaNoOidError::InvalidPublicKey)?; + if label != "PUBLIC KEY" { + return Err(TransitRsaNoOidError::InvalidPublicKey); + } + let _: p256::pkcs8::SubjectPublicKeyInfoRef<'_> = document + .decode_msg() + .map_err(|_| TransitRsaNoOidError::InvalidPublicKey)?; + Ok(Zeroizing::new(document.into_vec())) +} + +fn exact_bit_length(bytes: &[u8]) -> Result { + let first = *bytes + .first() + .ok_or(TransitRsaNoOidError::InvalidPublicKey)?; + if first == 0 { + return Err(TransitRsaNoOidError::InvalidPublicKey); + } + Ok((bytes.len() - 1) * 8 + (8 - first.leading_zeros() as usize)) +} + +fn validate_digest(input: &[u8; 64]) -> Result<(), TransitRsaNoOidError> { + if input + .iter() + .all(|byte| byte.is_ascii_digit() || matches!(byte, b'a'..=b'f')) + { + Ok(()) + } else { + Err(TransitRsaNoOidError::InvalidDigest) + } +} + +#[cfg(all(test, unix, feature = "transit"))] +mod tests { + use std::sync::OnceLock; + use std::time::Duration; + + use aws_lc_rs::encoding::{AsDer as _, PublicKeyX509Der}; + use aws_lc_rs::signature::KeyPair as _; + use base64::engine::general_purpose::STANDARD; + use base64::Engine as _; + use serde_json::{json, Value}; + use sha2::{Digest as _, Sha256}; + use tokio::io::{AsyncReadExt as _, AsyncWriteExt as _}; + use tokio::net::UnixListener; + + use super::{ + TransitRsaNoOidError, TransitRsaNoOidKeyConfig, TransitRsaNoOidSigner, + TransitRsaNoOidVerifier, + }; + use crate::transit_mock::{spawn_transit_mock, transit_reply, MockTransitReply}; + use crate::{generate_private_jwk, rsa_private_key, GeneratedKeyAlgorithm}; + + const TIMEOUT: Duration = Duration::from_secs(2); + const MOUNT: &str = "transit"; + const KEY: &str = "mifos-request"; + const VERSION: u32 = 7; + const METADATA_PATH: &str = "/v1/transit/keys/mifos-request"; + const SIGN_PATH: &str = "/v1/transit/sign/mifos-request/none"; + const VERIFY_PATH: &str = "/v1/transit/verify/mifos-request/none"; + const DUMMY_DIGEST: &[u8; 64] = + b"0000000000000000000000000000000000000000000000000000000000000000"; + const DIGEST: &[u8; 64] = b"0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"; + + struct RsaFixture { + public_pem: String, + public_spki: Vec, + public_spki_sha256: [u8; 32], + signature: Vec, + } + + fn rsa_fixture() -> &'static RsaFixture { + static FIXTURE: OnceLock = OnceLock::new(); + FIXTURE.get_or_init(|| { + let private = + generate_private_jwk(GeneratedKeyAlgorithm::Rs384).expect("generate test RSA key"); + let key_pair = rsa_private_key(&private).expect("load generated RSA key"); + let spki: PublicKeyX509Der<'_> = key_pair + .public_key() + .as_der() + .expect("encode test RSA SPKI"); + let spki = spki.as_ref(); + let encoded = STANDARD.encode(spki); + let mut public_pem = String::from("-----BEGIN PUBLIC KEY-----\n"); + for line in encoded.as_bytes().chunks(64) { + public_pem.push_str(std::str::from_utf8(line).expect("base64 is ASCII")); + public_pem.push('\n'); + } + public_pem.push_str("-----END PUBLIC KEY-----\n"); + RsaFixture { + public_pem, + public_spki: spki.to_vec(), + public_spki_sha256: Sha256::digest(spki).into(), + signature: vec![0x5a; 256], + } + }) + } + + fn metadata(imported_key: bool) -> Value { + json!({ + "data": { + "type": "rsa-2048", + "derived": false, + "exportable": false, + "allow_plaintext_backup": false, + "supports_signing": true, + "latest_version": VERSION, + "min_encryption_version": 1, + "min_decryption_version": 1, + "imported_key": imported_key, + "keys": { + VERSION.to_string(): { + "public_key": rsa_fixture().public_pem.as_str(), + } + } + } + }) + } + + fn config(socket_path: std::path::PathBuf) -> TransitRsaNoOidKeyConfig { + TransitRsaNoOidKeyConfig::new( + socket_path, + MOUNT.to_owned(), + KEY.to_owned(), + VERSION, + rsa_fixture().public_spki_sha256, + TIMEOUT, + ) + .expect("fixture config validates") + } + + fn sign_body(input: &[u8; 64]) -> Value { + json!({ + "input": STANDARD.encode(input), + "key_version": VERSION, + "prehashed": true, + "signature_algorithm": "pkcs1v15", + }) + } + + fn verify_body(input: &[u8; 64], signature: &[u8]) -> Value { + json!({ + "input": STANDARD.encode(input), + "prehashed": true, + "signature": format!("vault:v{VERSION}:{}", STANDARD.encode(signature)), + "signature_algorithm": "pkcs1v15", + }) + } + + fn signer_startup_replies() -> Vec { + vec![ + transit_reply("GET", METADATA_PATH, None, metadata(false)), + transit_reply("GET", METADATA_PATH, None, metadata(false)), + transit_reply( + "POST", + SIGN_PATH, + Some(sign_body(DUMMY_DIGEST)), + json!({ + "data": { + "signature": format!( + "vault:v{VERSION}:{}", + STANDARD.encode(&rsa_fixture().signature) + ) + } + }), + ), + transit_reply("GET", METADATA_PATH, None, metadata(false)), + transit_reply( + "POST", + VERIFY_PATH, + Some(verify_body(DUMMY_DIGEST, &rsa_fixture().signature)), + json!({"data": {"valid": true}}), + ), + ] + } + + fn verifier_startup_replies() -> Vec { + vec![ + transit_reply("GET", METADATA_PATH, None, metadata(true)), + transit_reply("GET", METADATA_PATH, None, metadata(true)), + transit_reply( + "POST", + VERIFY_PATH, + Some(verify_body(DUMMY_DIGEST, &[0_u8; 256])), + json!({"data": {"valid": false}}), + ), + ] + } + + #[tokio::test] + async fn signer_initialization_pins_exact_metadata_and_no_oid_wire_contract() { + let (directory, socket_path, server) = spawn_transit_mock(signer_startup_replies()); + TransitRsaNoOidSigner::initialize(config(socket_path)) + .await + .expect("signer initializes"); + server.await.expect("mock Transit server completed"); + drop(directory); + } + + #[tokio::test] + async fn verifier_initialization_requires_imported_key_and_probes_false_verification() { + let (directory, socket_path, server) = spawn_transit_mock(verifier_startup_replies()); + TransitRsaNoOidVerifier::initialize(config(socket_path)) + .await + .expect("verifier initializes"); + server.await.expect("mock Transit server completed"); + drop(directory); + } + + #[tokio::test] + async fn signer_releases_only_a_canonical_signature_the_pinned_key_verifies() { + let mut replies = signer_startup_replies(); + replies.push(transit_reply("GET", METADATA_PATH, None, metadata(false))); + replies.push(transit_reply( + "POST", + SIGN_PATH, + Some(sign_body(DIGEST)), + json!({ + "data": { + "signature": format!( + "vault:v{VERSION}:{}", + STANDARD.encode(&rsa_fixture().signature) + ) + } + }), + )); + replies.push(transit_reply("GET", METADATA_PATH, None, metadata(false))); + replies.push(transit_reply( + "POST", + VERIFY_PATH, + Some(verify_body(DIGEST, &rsa_fixture().signature)), + json!({"data": {"valid": true}}), + )); + let (directory, socket_path, server) = spawn_transit_mock(replies); + let signer = TransitRsaNoOidSigner::initialize(config(socket_path)) + .await + .expect("signer initializes"); + let signature = signer.sign_digest_hex(DIGEST).await.expect("digest signs"); + assert_eq!(signature.as_bytes(), rsa_fixture().signature); + server.await.expect("mock Transit server completed"); + drop(directory); + } + + #[tokio::test] + async fn signer_refuses_a_provider_signature_that_the_pinned_key_does_not_verify() { + let mut replies = signer_startup_replies(); + replies.push(transit_reply("GET", METADATA_PATH, None, metadata(false))); + replies.push(transit_reply( + "POST", + SIGN_PATH, + Some(sign_body(DIGEST)), + json!({ + "data": { + "signature": format!( + "vault:v{VERSION}:{}", + STANDARD.encode(&rsa_fixture().signature) + ) + } + }), + )); + replies.push(transit_reply("GET", METADATA_PATH, None, metadata(false))); + replies.push(transit_reply( + "POST", + VERIFY_PATH, + Some(verify_body(DIGEST, &rsa_fixture().signature)), + json!({"data": {"valid": false}}), + )); + let (directory, socket_path, server) = spawn_transit_mock(replies); + let signer = TransitRsaNoOidSigner::initialize(config(socket_path)) + .await + .expect("signer initializes"); + let error = signer + .sign_digest_hex(DIGEST) + .await + .err() + .expect("unverified signature is withheld"); + assert_eq!(error, TransitRsaNoOidError::VerificationFailed); + server.await.expect("mock Transit server completed"); + drop(directory); + } + + #[tokio::test] + async fn verifier_sends_the_exact_wrapped_signature_and_requires_true() { + let mut replies = verifier_startup_replies(); + replies.push(transit_reply("GET", METADATA_PATH, None, metadata(true))); + replies.push(transit_reply( + "POST", + VERIFY_PATH, + Some(verify_body(DIGEST, &rsa_fixture().signature)), + json!({"data": {"valid": true}}), + )); + replies.push(transit_reply("GET", METADATA_PATH, None, metadata(true))); + replies.push(transit_reply( + "POST", + VERIFY_PATH, + Some(verify_body(DIGEST, &rsa_fixture().signature)), + json!({"data": {"valid": false}}), + )); + let (directory, socket_path, server) = spawn_transit_mock(replies); + let verifier = TransitRsaNoOidVerifier::initialize(config(socket_path)) + .await + .expect("verifier initializes"); + verifier + .verify_digest_hex(DIGEST, &rsa_fixture().signature) + .await + .expect("valid signature verifies"); + assert_eq!( + verifier + .verify_digest_hex(DIGEST, &rsa_fixture().signature) + .await, + Err(TransitRsaNoOidError::VerificationFailed) + ); + server.await.expect("mock Transit server completed"); + drop(directory); + } + + #[tokio::test] + async fn replaced_named_key_is_refused_before_sign_or_verify() { + let mut replacement_spki = rsa_fixture().public_spki.clone(); + *replacement_spki.last_mut().expect("SPKI has an exponent") ^= 2; + let replacement_pem = public_key_pem(&replacement_spki); + let mut replaced_signer = metadata(false); + replaced_signer["data"]["keys"][VERSION.to_string()]["public_key"] = + json!(replacement_pem.as_str()); + let mut signer_replies = signer_startup_replies(); + signer_replies.push(transit_reply("GET", METADATA_PATH, None, replaced_signer)); + let (directory, socket_path, server) = spawn_transit_mock(signer_replies); + let signer = TransitRsaNoOidSigner::initialize(config(socket_path)) + .await + .expect("signer initializes"); + let error = signer + .sign_digest_hex(DIGEST) + .await + .err() + .expect("replaced key refuses before sign"); + assert_eq!(error, TransitRsaNoOidError::PublicKeyMismatch); + server.await.expect("mock Transit server completed"); + drop(directory); + + let mut replaced_verifier = metadata(true); + replaced_verifier["data"]["keys"][VERSION.to_string()]["public_key"] = + json!(replacement_pem.as_str()); + let mut verifier_replies = verifier_startup_replies(); + verifier_replies.push(transit_reply("GET", METADATA_PATH, None, replaced_verifier)); + let (directory, socket_path, server) = spawn_transit_mock(verifier_replies); + let verifier = TransitRsaNoOidVerifier::initialize(config(socket_path)) + .await + .expect("verifier initializes"); + let error = verifier + .verify_digest_hex(DIGEST, &rsa_fixture().signature) + .await + .expect_err("replaced key refuses before verify"); + assert_eq!(error, TransitRsaNoOidError::PublicKeyMismatch); + server.await.expect("mock Transit server completed"); + drop(directory); + } + + #[tokio::test] + async fn rsa_primitive_refuses_redirects() { + let directory = tempfile::tempdir().expect("temporary Transit directory"); + let socket_path = directory.path().join("transit.sock"); + let listener = UnixListener::bind(&socket_path).expect("bind redirect mock"); + let server = tokio::spawn(async move { + let (mut stream, _) = listener.accept().await.expect("accept metadata request"); + let mut request = vec![0_u8; 4096]; + let read = stream + .read(&mut request) + .await + .expect("read metadata request"); + let request = std::str::from_utf8(&request[..read]).expect("request is UTF-8"); + assert!(request.starts_with(&format!("GET {METADATA_PATH} "))); + stream + .write_all( + b"HTTP/1.1 302 Found\r\nLocation: http://localhost/redirected\r\nContent-Length: 0\r\nConnection: close\r\n\r\n", + ) + .await + .expect("write redirect"); + }); + let error = TransitRsaNoOidSigner::initialize(config(socket_path)) + .await + .expect_err("redirect is not followed"); + assert_eq!(error, TransitRsaNoOidError::Refused); + server.await.expect("redirect mock completed"); + drop(directory); + } + + #[tokio::test] + async fn rsa_primitive_bounds_provider_time_and_response_bytes() { + let delayed = MockTransitReply { + method: "GET", + path: METADATA_PATH, + body: None, + status: 200, + response: serde_json::to_vec(&metadata(false)).expect("metadata JSON"), + delay: Duration::from_millis(50), + }; + let (directory, socket_path, server) = spawn_transit_mock(vec![delayed]); + let short_timeout = TransitRsaNoOidKeyConfig::new( + socket_path, + MOUNT.to_owned(), + KEY.to_owned(), + VERSION, + rsa_fixture().public_spki_sha256, + Duration::from_millis(5), + ) + .expect("short bounded timeout validates"); + let error = TransitRsaNoOidSigner::initialize(short_timeout) + .await + .expect_err("slow metadata times out"); + assert_eq!(error, TransitRsaNoOidError::Unavailable); + server.await.expect("slow mock completed"); + drop(directory); + + let oversized = MockTransitReply { + method: "GET", + path: METADATA_PATH, + body: None, + status: 200, + response: vec![b'x'; crate::MAX_TRANSIT_RESPONSE_BYTES + 1], + delay: Duration::ZERO, + }; + let (directory, socket_path, server) = spawn_transit_mock(vec![oversized]); + let error = TransitRsaNoOidSigner::initialize(config(socket_path)) + .await + .expect_err("oversized metadata rejects"); + assert_eq!(error, TransitRsaNoOidError::InvalidResponse); + server.await.expect("oversized mock completed"); + drop(directory); + } + + #[tokio::test] + async fn signer_refuses_unsafe_custody_role_version_and_key_binding() { + let mut cases = Vec::new(); + for field in ["derived", "exportable", "allow_plaintext_backup"] { + let mut document = metadata(false); + document["data"][field] = json!(true); + cases.push((document, TransitRsaNoOidError::UnsafeCustody)); + } + let mut imported = metadata(false); + imported["data"]["imported_key"] = json!(true); + cases.push((imported, TransitRsaNoOidError::UnsafeCustody)); + let mut wrong_type = metadata(false); + wrong_type["data"]["type"] = json!("rsa-3072"); + cases.push((wrong_type, TransitRsaNoOidError::InvalidPublicKey)); + let mut retired = metadata(false); + retired["data"]["min_encryption_version"] = json!(8); + cases.push((retired, TransitRsaNoOidError::KeyVersionRetired)); + let mut future = metadata(false); + future["data"]["latest_version"] = json!(6); + cases.push((future, TransitRsaNoOidError::KeyVersionNotCreated)); + + for (document, expected) in cases { + let (directory, socket_path, server) = + spawn_transit_mock(vec![transit_reply("GET", METADATA_PATH, None, document)]); + let error = TransitRsaNoOidSigner::initialize(config(socket_path)) + .await + .expect_err("unsafe metadata rejects"); + assert_eq!(error, expected); + server.await.expect("mock Transit server completed"); + drop(directory); + } + + let (directory, socket_path, server) = spawn_transit_mock(vec![transit_reply( + "GET", + METADATA_PATH, + None, + metadata(false), + )]); + let mut wrong_hash = rsa_fixture().public_spki_sha256; + wrong_hash[0] ^= 1; + let wrong_config = TransitRsaNoOidKeyConfig::new( + socket_path, + MOUNT.to_owned(), + KEY.to_owned(), + VERSION, + wrong_hash, + TIMEOUT, + ) + .expect("hash shape validates"); + let error = TransitRsaNoOidSigner::initialize(wrong_config) + .await + .expect_err("wrong hash rejects"); + assert_eq!(error, TransitRsaNoOidError::PublicKeyMismatch); + server.await.expect("mock Transit server completed"); + drop(directory); + } + + #[tokio::test] + async fn verifier_refuses_service_created_or_signing_version_retired_metadata() { + let mut retired = metadata(true); + retired["data"]["min_decryption_version"] = json!(8); + for (document, expected) in [ + (metadata(false), TransitRsaNoOidError::UnsafeCustody), + (retired, TransitRsaNoOidError::KeyVersionRetired), + ] { + let (directory, socket_path, server) = + spawn_transit_mock(vec![transit_reply("GET", METADATA_PATH, None, document)]); + let error = TransitRsaNoOidVerifier::initialize(config(socket_path)) + .await + .expect_err("wrong verifier metadata rejects"); + assert_eq!(error, expected); + server.await.expect("mock Transit server completed"); + drop(directory); + } + } + + #[tokio::test] + async fn invalid_digest_and_signature_length_fail_before_provider_access() { + let (directory, socket_path, server) = spawn_transit_mock(signer_startup_replies()); + let signer = TransitRsaNoOidSigner::initialize(config(socket_path)) + .await + .expect("signer initializes"); + let mut uppercase = *DIGEST; + uppercase[10] = b'A'; + let error = signer + .sign_digest_hex(&uppercase) + .await + .err() + .expect("uppercase digest rejects"); + assert_eq!(error, TransitRsaNoOidError::InvalidDigest); + server.await.expect("mock Transit server completed"); + drop(directory); + + let (directory, socket_path, server) = spawn_transit_mock(verifier_startup_replies()); + let verifier = TransitRsaNoOidVerifier::initialize(config(socket_path)) + .await + .expect("verifier initializes"); + assert_eq!( + verifier.verify_digest_hex(DIGEST, &[0_u8; 255]).await, + Err(TransitRsaNoOidError::InvalidSignature) + ); + server.await.expect("mock Transit server completed"); + drop(directory); + } + + #[tokio::test] + async fn signer_rejects_bad_prefix_length_and_noncanonical_base64() { + let cases = [ + format!("vault:v8:{}", STANDARD.encode(&rsa_fixture().signature)), + format!("vault:v{VERSION}:AAAA"), + format!( + "vault:v{VERSION}:{}", + STANDARD.encode([0xff_u8; 256]).replace('/', "_") + ), + format!( + "vault:v{VERSION}:{}", + STANDARD + .encode(&rsa_fixture().signature) + .trim_end_matches('=') + ), + ]; + for provider_signature in cases { + let mut replies = signer_startup_replies(); + replies.push(transit_reply("GET", METADATA_PATH, None, metadata(false))); + replies.push(transit_reply( + "POST", + SIGN_PATH, + Some(sign_body(DIGEST)), + json!({"data": {"signature": provider_signature}}), + )); + let (directory, socket_path, server) = spawn_transit_mock(replies); + let signer = TransitRsaNoOidSigner::initialize(config(socket_path)) + .await + .expect("signer initializes"); + let error = signer + .sign_digest_hex(DIGEST) + .await + .err() + .expect("malformed provider signature rejects"); + assert_eq!(error, TransitRsaNoOidError::InvalidSignature); + server.await.expect("mock Transit server completed"); + drop(directory); + } + } + + #[tokio::test] + async fn false_or_malformed_verify_response_fails_closed_without_raw_json() { + const CANARY: &str = "PRIVATE_PROVIDER_DIAGNOSTIC_CANARY"; + for (response, expected) in [ + ( + json!({"data": {"valid": false}}), + TransitRsaNoOidError::VerificationFailed, + ), + ( + json!({"data": {"valid": "true", "detail": CANARY}}), + TransitRsaNoOidError::InvalidResponse, + ), + ] { + let mut replies = verifier_startup_replies(); + replies.push(transit_reply("GET", METADATA_PATH, None, metadata(true))); + replies.push(transit_reply( + "POST", + VERIFY_PATH, + Some(verify_body(DIGEST, &rsa_fixture().signature)), + response, + )); + let (directory, socket_path, server) = spawn_transit_mock(replies); + let verifier = TransitRsaNoOidVerifier::initialize(config(socket_path)) + .await + .expect("verifier initializes"); + let error = verifier + .verify_digest_hex(DIGEST, &rsa_fixture().signature) + .await + .expect_err("verification must fail closed"); + assert_eq!(error, expected); + assert!(!error.to_string().contains(CANARY)); + server.await.expect("mock Transit server completed"); + drop(directory); + } + } + + #[tokio::test] + async fn released_mifos_response_vector_uses_exact_no_oid_verify_wire() { + const FIXTURE: &[u8] = + include_bytes!("../tests/fixtures/mifos-bulk-v1.12.1-response-signatures.json"); + const FIXTURE_SHA256: &str = + "ed24b1b3e0b580445751a23b9283994e8052534a2e3350bafed96ecff214fa98"; + + assert_eq!(hex_lower(&Sha256::digest(FIXTURE)), FIXTURE_SHA256); + let vector: Value = serde_json::from_slice(FIXTURE).expect("released vector JSON"); + assert_eq!( + fixture_string(&vector, "sourceImage"), + "docker.io/openmf/ph-ee-bulk-processor@sha256:6d58a33751d458fc96b7fa6bb3388456b17b81ad9d61cadd057a825751472c34" + ); + assert_eq!(fixture_string(&vector, "tenantHeader"), "Platform-TenantId"); + assert_eq!(fixture_string(&vector, "tenant"), "pilot"); + + let spki = STANDARD + .decode(fixture_string(&vector, "publicKeySpkiBase64")) + .expect("fixture SPKI base64"); + assert_eq!( + hex_lower(&Sha256::digest(&spki)), + fixture_string(&vector, "publicKeySpkiSha256") + ); + let public_pem = public_key_pem(&spki); + let public_key_sha256: [u8; 32] = Sha256::digest(&spki).into(); + let signature = STANDARD + .decode(fixture_string(&vector, "signatureBase64")) + .expect("fixture raw signature base64"); + let rs256_signature = STANDARD + .decode(fixture_string(&vector, "rs256SignatureBase64")) + .expect("fixture RS256 signature base64"); + assert_eq!(signature.len(), 256); + assert_eq!(rs256_signature.len(), 256); + + let accepted = digest_bytes(fixture_string(&vector, "bodyOnlySha3Hex")); + let altered_header = digest_bytes(fixture_string(&vector, "uppercaseSha3Hex")); + let changed_body = sha3_hex(fixture_string(&vector, "changedBody")); + assert_eq!(sha3_hex(fixture_string(&vector, "body")), accepted); + assert_ne!(accepted, altered_header); + assert_ne!(accepted, changed_body); + + let metadata = || { + json!({ + "data": { + "type": "rsa-2048", + "derived": false, + "exportable": false, + "allow_plaintext_backup": false, + "supports_signing": true, + "latest_version": VERSION, + "min_encryption_version": 1, + "min_decryption_version": 1, + "imported_key": true, + "keys": {VERSION.to_string(): {"public_key": public_pem.as_str()}} + } + }) + }; + let mut replies = vec![ + transit_reply("GET", METADATA_PATH, None, metadata()), + transit_reply("GET", METADATA_PATH, None, metadata()), + transit_reply( + "POST", + VERIFY_PATH, + Some(verify_body(DUMMY_DIGEST, &[0_u8; 256])), + json!({"data": {"valid": false}}), + ), + ]; + for (input, candidate, valid) in [ + (accepted, signature.as_slice(), true), + (altered_header, signature.as_slice(), false), + (changed_body, signature.as_slice(), false), + (accepted, rs256_signature.as_slice(), false), + ] { + replies.push(transit_reply("GET", METADATA_PATH, None, metadata())); + replies.push(transit_reply( + "POST", + VERIFY_PATH, + Some(verify_body(&input, candidate)), + json!({"data": {"valid": valid}}), + )); + } + + let (directory, socket_path, server) = spawn_transit_mock(replies); + let config = TransitRsaNoOidKeyConfig::new( + socket_path, + MOUNT.to_owned(), + KEY.to_owned(), + VERSION, + public_key_sha256, + TIMEOUT, + ) + .expect("released vector config validates"); + let verifier = TransitRsaNoOidVerifier::initialize(config) + .await + .expect("released vector verifier initializes"); + verifier + .verify_digest_hex(&accepted, &signature) + .await + .expect("released raw signature verifies"); + for (input, candidate) in [ + (altered_header, signature.as_slice()), + (changed_body, signature.as_slice()), + (accepted, rs256_signature.as_slice()), + ] { + assert_eq!( + verifier.verify_digest_hex(&input, candidate).await, + Err(TransitRsaNoOidError::VerificationFailed) + ); + } + server.await.expect("released-vector mock completed"); + drop(directory); + } + + #[test] + fn configuration_refuses_unbounded_or_unsafe_bindings_without_identifiers_in_errors() { + let cases = [ + TransitRsaNoOidKeyConfig::new( + "relative.sock".into(), + MOUNT.to_owned(), + KEY.to_owned(), + VERSION, + rsa_fixture().public_spki_sha256, + TIMEOUT, + ), + TransitRsaNoOidKeyConfig::new( + "/run/transit.sock".into(), + "../transit".to_owned(), + KEY.to_owned(), + VERSION, + rsa_fixture().public_spki_sha256, + TIMEOUT, + ), + TransitRsaNoOidKeyConfig::new( + "/run/transit.sock".into(), + MOUNT.to_owned(), + KEY.to_owned(), + 0, + rsa_fixture().public_spki_sha256, + TIMEOUT, + ), + TransitRsaNoOidKeyConfig::new( + "/run/transit.sock".into(), + MOUNT.to_owned(), + KEY.to_owned(), + VERSION, + rsa_fixture().public_spki_sha256, + Duration::from_secs(31), + ), + ]; + for result in cases { + let error = result.expect_err("invalid config rejects"); + assert_eq!(error, TransitRsaNoOidError::InvalidConfiguration); + let rendered = error.to_string(); + assert!(!rendered.contains("transit.sock")); + assert!(!rendered.contains(KEY)); + } + } + + fn fixture_string<'a>(vector: &'a Value, field: &str) -> &'a str { + vector + .get(field) + .and_then(Value::as_str) + .unwrap_or_else(|| panic!("released vector string {field}")) + } + + fn digest_bytes(value: &str) -> [u8; 64] { + value + .as_bytes() + .try_into() + .expect("released digest is 64 ASCII bytes") + } + + fn sha3_hex(value: &str) -> [u8; 64] { + let digest = aws_lc_rs::digest::digest(&aws_lc_rs::digest::SHA3_256, value.as_bytes()); + let encoded = hex_lower(digest.as_ref()); + encoded + .as_bytes() + .try_into() + .expect("SHA3-256 hex is 64 ASCII bytes") + } + + fn hex_lower(bytes: &[u8]) -> String { + const HEX: &[u8; 16] = b"0123456789abcdef"; + let mut encoded = String::with_capacity(bytes.len() * 2); + for &byte in bytes { + encoded.push(char::from(HEX[usize::from(byte >> 4)])); + encoded.push(char::from(HEX[usize::from(byte & 0x0f)])); + } + encoded + } + + fn public_key_pem(spki: &[u8]) -> String { + let encoded = STANDARD.encode(spki); + let mut pem = String::from("-----BEGIN PUBLIC KEY-----\n"); + for line in encoded.as_bytes().chunks(64) { + pem.push_str(std::str::from_utf8(line).expect("base64 is ASCII")); + pem.push('\n'); + } + pem.push_str("-----END PUBLIC KEY-----\n"); + pem + } +} diff --git a/crates/registry-platform-crypto/tests/fixtures/mifos-bulk-v1.12.1-response-signatures.json b/crates/registry-platform-crypto/tests/fixtures/mifos-bulk-v1.12.1-response-signatures.json new file mode 100644 index 0000000000..a8ed5dd48e --- /dev/null +++ b/crates/registry-platform-crypto/tests/fixtures/mifos-bulk-v1.12.1-response-signatures.json @@ -0,0 +1,13 @@ +{ + "sourceImage" : "docker.io/openmf/ph-ee-bulk-processor@sha256:6d58a33751d458fc96b7fa6bb3388456b17b81ad9d61cadd057a825751472c34", + "tenantHeader" : "Platform-TenantId", + "tenant" : "pilot", + "body" : "{\n \"batch_id\": \"batch-1\",\n \"request_id\": \"batch-request-1\",\n \"status\": \"queued\"\n}", + "bodyOnlySha3Hex" : "964c27ce0721f3fb952ff0739220d341f3320250b1023a5a4ce0543217e0ecc7", + "uppercaseSha3Hex" : "d3605a0d01176cc43c7bd938d5e9da19e323dacb403236981ae622343080c805", + "publicKeySpkiSha256" : "4d30ec6f6876a5564261cac5e3cd709afd5388d21540734a37b1a7795935c714", + "publicKeySpkiBase64" : "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA+hpMAHSvw6DuZzNArINktfIonFz2FoRpxRiM8FxAGjrFdxbggmRG4qxFfc0noOF6C09u+JKQ6VkM3HGdeJ6BtBM9BMt+7yKM/0P6yPpRSwy3vopf0hKIKVU+VKi6HUIQEM5bmPkPYXvWXRmS01By+gWw9hTrOUcAf2+mzhTcz8u9bfODeEzug4ymcsQRFcaor3hoUvjUkjpg47cd3RIw1/Co9bLPVcwBzce1tnCwWpIo/KfCWdL0soBD8JsdF228bUyXUirQww5pLIG3bBUFRvhhJp5B/43+Ad8cM3iCQ+adDrUNNrTx0sFX6s4b3ihn3/5tILRWTdbiNvMHBZnh2QIDAQAB", + "signatureBase64" : "5n2h3Yw0RXoKadpSCxA4zaF8XqYQE7W92EpePGtgShV6OM4TrvVGXseBCyOKL4HlaCE///Z+yIqkzypp/7OMFyRcJgzhMi4WkvHuPD7+iAYj46s0IUD8W2Y5QlqYNmLQeN1Kex6qwzgpIVad92M2NWDqxOzY+AS7Wq/NB2aoMysE9S3R2Tvyk/zsqHa9fh+Vt0meSqNBMDv5zLY7BUWnHxz+ddQx+KbKOF+LR/I34s0Q8dV5phMOL2I4J2YoD7uBYeMcyEc5MvoRtCxru92y2ukYdCtqiPUKPFpZWxtO+qWwGg0EAxRguWavY7afBOShiMreUwlvhxdOknkqOG4v2A==", + "rs256SignatureBase64" : "3Z/KPiTarJY2gKdIviEgXj/GaPq+Fm9EYNQidAmivRkZeAE+NJLJ9ePGoLD1R1kl2Qpad6jnpP/2oBcO3qucYNVXNfSKCzRhHGHtHnArQQNEopqKKKzyRv45Mf85HXujT+oi8w9kOL5sjTYqAwW9xq3DymHyI1yQgCRVZORX8/tBa6W9BSbtWFmyVQ4Vu243zYF/7mEtEowYDUKIH0XMYpl6ctz1gW1Frgi0OhIQVfDbnnfbQfZGbe35CntNbzBs6gmjHPjSbdAEL0Vzb472yGaSeLGv1MzKXoS0MgVkcW9U8XteDysdM91yYzgWj7HkM/00GQbm/xDZBLPgeOxl+g==", + "changedBody" : "{\n \"batch_id\": \"batch-1\",\n \"request_id\": \"batch-request-1\",\n \"status\": \"queued\"\n}\n" +} \ No newline at end of file From 49413e3db2acf8c675f2f1e55646a5780b63630c Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 13 Nov 2026 03:29:45 +0700 Subject: [PATCH 05/40] feat(adapter): add governed G2P API and mapped payment packs Signed-off-by: Jeremi Joslin --- .github/scripts/ci_changes.py | 1 + Cargo.lock | 21 + Cargo.toml | 2 + crates/registry-adapter/Cargo.toml | 5 + crates/registry-adapter/src/cli.rs | 54 + crates/registry-adapter/src/main.rs | 2 + .../registry-adapter/src/payments/config.rs | 252 +++- .../src/payments/g2p_config.rs | 37 + .../src/payments/g2p_model.rs | 1043 +++++++++++++++++ .../src/payments/g2p_registry.rs | 400 +++++++ .../src/payments/g2p_service.rs | 786 +++++++++++++ .../src/payments/g2p_store.rs | 652 +++++++++++ crates/registry-adapter/src/payments/http.rs | 638 +++++++++- crates/registry-adapter/src/payments/mod.rs | 7 + crates/registry-adapter/src/payments/model.rs | 291 ++++- crates/registry-adapter/src/payments/pack.rs | 311 +++++ .../src/payments/provider_mapping.rs | 1010 ++++++++++++++++ .../registry-adapter/src/payments/service.rs | 709 ++++++++++- crates/registry-adapter/src/serve.rs | 27 +- crates/registry-adapter/tests/g2p_model.rs | 497 ++++++++ crates/registry-adapter/tests/g2p_postgres.rs | 614 ++++++++++ crates/registry-adapter/tests/g2p_provider.rs | 369 ++++++ .../registry-adapter/tests/payment_config.rs | 346 +++++- .../tests/payment_provider_mapping.rs | 725 ++++++++++++ .../tests/payment_provider_pack.rs | 17 + .../registry-adapter/tests/payment_service.rs | 800 ++++++++++++- crates/registry-adapterctl/Cargo.toml | 1 + crates/registry-adapterctl/src/lib.rs | 1 + .../src/payment_fixtures.rs | 599 ++++++++++ crates/registry-adapterctl/src/payments.rs | 263 ++++- crates/registry-adapterctl/src/schemas.rs | 166 ++- crates/registry-adapterctl/tests/check.rs | 6 +- crates/registry-adapterctl/tests/payments.rs | 103 ++ crates/registry-coordinator/src/adapters.rs | 190 ++- crates/registry-coordinator/src/authoring.rs | 10 + crates/registry-coordinator/src/contracts.rs | 48 + crates/registry-coordinator/src/definition.rs | 7 + crates/registry-coordinator/src/operations.rs | 73 ++ crates/registry-coordinator/src/protocol.rs | 9 + crates/registry-coordinator/src/scenarios.rs | 117 +- .../tests/payment_adapter.rs | 227 ++++ crates/registry-payment-client/src/client.rs | 134 ++- crates/registry-payment-client/src/lib.rs | 8 +- .../tests/http_boundary.rs | 85 +- .../Cargo.toml | 30 + .../README.md | 157 +++ .../src/legacy_web_signature.rs | 224 ++++ .../src/lib.rs | 996 ++++++++++++++++ .../tests/legacy_contract.rs | 534 +++++++++ .../tests/legacy_web_signature.rs | 182 +++ crates/registry-payment-protocol/src/lib.rs | 204 ++++ .../tests/contract.rs | 87 +- crates/registry-platform-crypto/README.md | 3 + crates/registry-platform-crypto/src/lib.rs | 12 + .../tests/sha3_256.rs | 12 + products/adapter/README.md | 17 +- .../payment-collections/payments.example.yaml | 14 +- .../examples/payment-provider-fixture.yaml | 30 + .../adapter/packs/payment-simulator/README.md | 15 + .../adapter/packs/payment-simulator/pack.yaml | 7 + ...ment-provider-fixture.v1alpha1.schema.json | 212 ++++ ...payment-provider-pack.v1alpha1.schema.json | 199 ++++ .../schemas/payments.v1alpha1.schema.json | 428 ++++++- .../scripts/check_dependency_direction.py | 25 +- .../adapter/scripts/test-payment-native.mjs | 4 +- .../scripts/test_dependency_direction.py | 10 + .../breg/examples/g2p-disbursement/README.md | 101 ++ .../examples/g2p-disbursement/registry.yaml | 282 +++++ .../g2p-disbursement/tests/journeys.yaml | 221 ++++ products/coordinator/CHANGELOG.md | 8 + .../examples/g2p-disbursements/README.md | 55 + .../g2p-disbursements/input.example.json | 4 + .../examples/g2p-disbursements/runtime.yaml | 57 + .../examples/g2p-disbursements/scenarios.yaml | 252 ++++ .../examples/g2p-disbursements/workflow.yaml | 70 ++ .../openapi/coordinator.openapi.json | 5 +- .../generated/operations/README.md | 266 +++++ .../generated/operations/catalog.json | 494 ++++++++ ...yments.disbursement.completion.schema.json | 112 ++ ...nts.read-disbursement.v1.input.schema.json | 19 + ...ts.read-disbursement.v1.output.schema.json | 112 ++ ...provider-confirmation.v1.input.schema.json | 19 + ...rovider-confirmation.v1.output.schema.json | 93 ++ ....request-disbursement.v1.input.schema.json | 25 + ...request-disbursement.v1.output.schema.json | 49 + .../generated/project/project.schema.json | 5 +- products/platform/config-formats.yaml | 98 +- 87 files changed, 17231 insertions(+), 181 deletions(-) create mode 100644 crates/registry-adapter/src/payments/g2p_config.rs create mode 100644 crates/registry-adapter/src/payments/g2p_model.rs create mode 100644 crates/registry-adapter/src/payments/g2p_registry.rs create mode 100644 crates/registry-adapter/src/payments/g2p_service.rs create mode 100644 crates/registry-adapter/src/payments/g2p_store.rs create mode 100644 crates/registry-adapter/src/payments/pack.rs create mode 100644 crates/registry-adapter/src/payments/provider_mapping.rs create mode 100644 crates/registry-adapter/tests/g2p_model.rs create mode 100644 crates/registry-adapter/tests/g2p_postgres.rs create mode 100644 crates/registry-adapter/tests/g2p_provider.rs create mode 100644 crates/registry-adapter/tests/payment_provider_mapping.rs create mode 100644 crates/registry-adapter/tests/payment_provider_pack.rs create mode 100644 crates/registry-adapterctl/src/payment_fixtures.rs create mode 100644 crates/registry-payment-mifos-connector/Cargo.toml create mode 100644 crates/registry-payment-mifos-connector/README.md create mode 100644 crates/registry-payment-mifos-connector/src/legacy_web_signature.rs create mode 100644 crates/registry-payment-mifos-connector/src/lib.rs create mode 100644 crates/registry-payment-mifos-connector/tests/legacy_contract.rs create mode 100644 crates/registry-payment-mifos-connector/tests/legacy_web_signature.rs create mode 100644 crates/registry-platform-crypto/tests/sha3_256.rs create mode 100644 products/adapter/examples/payment-provider-fixture.yaml create mode 100644 products/adapter/packs/payment-simulator/README.md create mode 100644 products/adapter/packs/payment-simulator/pack.yaml create mode 100644 products/adapter/schemas/payment-provider-fixture.v1alpha1.schema.json create mode 100644 products/adapter/schemas/payment-provider-pack.v1alpha1.schema.json create mode 100644 products/breg/examples/g2p-disbursement/README.md create mode 100644 products/breg/examples/g2p-disbursement/registry.yaml create mode 100644 products/breg/examples/g2p-disbursement/tests/journeys.yaml create mode 100644 products/coordinator/examples/g2p-disbursements/README.md create mode 100644 products/coordinator/examples/g2p-disbursements/input.example.json create mode 100644 products/coordinator/examples/g2p-disbursements/runtime.yaml create mode 100644 products/coordinator/examples/g2p-disbursements/scenarios.yaml create mode 100644 products/coordinator/examples/g2p-disbursements/workflow.yaml create mode 100644 products/coordinator/generated/operations/payments.disbursement.completion.schema.json create mode 100644 products/coordinator/generated/operations/payments.read-disbursement.v1.input.schema.json create mode 100644 products/coordinator/generated/operations/payments.read-disbursement.v1.output.schema.json create mode 100644 products/coordinator/generated/operations/payments.record-provider-confirmation.v1.input.schema.json create mode 100644 products/coordinator/generated/operations/payments.record-provider-confirmation.v1.output.schema.json create mode 100644 products/coordinator/generated/operations/payments.request-disbursement.v1.input.schema.json create mode 100644 products/coordinator/generated/operations/payments.request-disbursement.v1.output.schema.json diff --git a/.github/scripts/ci_changes.py b/.github/scripts/ci_changes.py index 6db654c2d7..ae2711ffcf 100644 --- a/.github/scripts/ci_changes.py +++ b/.github/scripts/ci_changes.py @@ -110,6 +110,7 @@ "registry-payment-protocol", "registry-payment-client", "registry-payment-simulator-connector", + "registry-payment-mifos-connector", ), "stack-client": ("registry-record", "registry-stack-client"), "evidence": ( diff --git a/Cargo.lock b/Cargo.lock index 860f410e7b..34c80d5165 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5974,6 +5974,7 @@ dependencies = [ "registry-adapter-core", "registry-adapter-engine", "registry-breg-client", + "registry-payment-mifos-connector", "registry-payment-protocol", "registry-payment-simulator-connector", "registry-platform-authcommon", @@ -5985,8 +5986,10 @@ dependencies = [ "registry-platform-httputil", "registry-platform-metrics", "registry-platform-oidc", + "registry-platform-script", "registry-platform-testing", "registry-platform-yaml", + "rhai", "rustls", "schemars", "serde", @@ -6147,6 +6150,7 @@ dependencies = [ "rcgen", "registry-adapter", "registry-adapter-core", + "registry-payment-mifos-connector", "registry-platform-buildinfo", "registry-platform-config", "registry-platform-httputil", @@ -7708,6 +7712,23 @@ dependencies = [ "uuid", ] +[[package]] +name = "registry-payment-mifos-connector" +version = "0.46.1" +dependencies = [ + "registry-platform-crypto", + "registry-platform-httputil", + "registry-platform-yaml", + "reqwest 0.12.28", + "schemars", + "serde", + "serde_json", + "thiserror 2.0.21", + "tokio", + "url", + "zeroize", +] + [[package]] name = "registry-payment-protocol" version = "0.46.1" diff --git a/Cargo.toml b/Cargo.toml index 0921774f05..8be5c1b7cf 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -9,6 +9,7 @@ members = [ "crates/registry-payment-protocol", "crates/registry-payment-client", "crates/registry-payment-simulator-connector", + "crates/registry-payment-mifos-connector", "crates/registry-casework-client-node", "crates/registry-casework-client-py", "crates/registry-casework", @@ -132,6 +133,7 @@ registry-review-protocol = { path = "crates/registry-review-protocol", version = registry-payment-protocol = { path = "crates/registry-payment-protocol", version = "0.49.0" } registry-payment-client = { path = "crates/registry-payment-client", version = "0.49.0" } registry-payment-simulator-connector = { path = "crates/registry-payment-simulator-connector", version = "0.49.0" } +registry-payment-mifos-connector = { path = "crates/registry-payment-mifos-connector", version = "0.49.0" } registry-thunderid-tooling = { path = "crates/registry-thunderid-tooling", version = "0.49.0" } registry-casework = { path = "crates/registry-casework", version = "0.49.0" } registry-caseworkctl = { path = "crates/registry-caseworkctl", version = "0.49.0" } diff --git a/crates/registry-adapter/Cargo.toml b/crates/registry-adapter/Cargo.toml index d4433d8b64..1170a0a221 100644 --- a/crates/registry-adapter/Cargo.toml +++ b/crates/registry-adapter/Cargo.toml @@ -37,8 +37,10 @@ job-file = ["registry-adapter-engine/job-file"] job-postgres = ["registry-adapter-engine/job-postgres"] schema = [ "dep:schemars", + "registry-adapter-core/schema", "registry-payment-protocol/schema", "registry-payment-simulator-connector/schema", + "registry-payment-mifos-connector/schema", "registry-platform-yaml/schema", ] @@ -62,6 +64,7 @@ registry-adapter-core.workspace = true registry-adapter-engine.workspace = true registry-payment-protocol.workspace = true registry-payment-simulator-connector.workspace = true +registry-payment-mifos-connector.workspace = true registry-breg-client.workspace = true uuid = { workspace = true, features = ["serde"] } schemars = { workspace = true, optional = true } @@ -70,6 +73,7 @@ registry-platform-buildinfo.workspace = true registry-platform-config.workspace = true registry-platform-crypto.workspace = true registry-platform-httputil.workspace = true +registry-platform-script.workspace = true registry-platform-httpsec = { workspace = true, features = ["server"] } registry-platform-metrics.workspace = true registry-platform-oidc.workspace = true @@ -79,6 +83,7 @@ clap.workspace = true jsonwebtoken.workspace = true registry-platform-authcommon.workspace = true rustls.workspace = true +rhai.workspace = true serde.workspace = true thiserror.workspace = true tokio-postgres-rustls.workspace = true diff --git a/crates/registry-adapter/src/cli.rs b/crates/registry-adapter/src/cli.rs index 1fc405c908..1212d9020f 100644 --- a/crates/registry-adapter/src/cli.rs +++ b/crates/registry-adapter/src/cli.rs @@ -35,6 +35,9 @@ pub enum Command { /// Typed payment connections hosted on this listener. #[arg(long, value_name = "ABSOLUTE_FILE")] payments_config: Option, + /// Reviewed provider packs for current connections and retained attempts. + #[arg(long, value_name = "FILE", requires = "payments_config")] + payment_provider_pack: Vec, /// The profile file; defaults to profile.yaml beside the project. #[arg(long, value_name = "FILE", requires = "project")] profile: Option, @@ -89,6 +92,26 @@ mod tests { "/runtime.yaml" ]) .is_err()); + assert!(super::Cli::try_parse_from([ + "adapter", + "serve", + "--runtime-config", + "/runtime.yaml", + "--payments-config", + "/payments.yaml", + "--payment-provider-pack", + "/pack.yaml" + ]) + .is_ok()); + assert!(super::Cli::try_parse_from([ + "adapter", + "serve", + "--runtime-config", + "/runtime.yaml", + "--payment-provider-pack", + "/pack.yaml" + ]) + .is_err()); assert!(super::Cli::try_parse_from([ "adapter", "serve", @@ -109,4 +132,35 @@ mod tests { Some(registry_platform_buildinfo::DISPLAY_VERSION) ); } + + #[test] + fn payment_provider_packs_can_be_repeated_for_retained_attempts() { + let parsed = super::Cli::try_parse_from([ + "adapter", + "serve", + "--runtime-config", + "/runtime.yaml", + "--payments-config", + "/payments.yaml", + "--payment-provider-pack", + "/pack-a.yaml", + "--payment-provider-pack", + "/pack-b.yaml", + ]) + .unwrap(); + let super::Command::Serve { + payment_provider_pack, + .. + } = parsed.command + else { + panic!("the serve command was expected") + }; + assert_eq!( + payment_provider_pack, + vec![ + std::path::PathBuf::from("/pack-a.yaml"), + std::path::PathBuf::from("/pack-b.yaml") + ] + ); + } } diff --git a/crates/registry-adapter/src/main.rs b/crates/registry-adapter/src/main.rs index d0f6b3f291..1fa5f0a147 100644 --- a/crates/registry-adapter/src/main.rs +++ b/crates/registry-adapter/src/main.rs @@ -28,6 +28,7 @@ async fn main() { runtime_config, project, payments_config, + payment_provider_pack, profile, pack, } => registry_adapter::serve::run_configured( @@ -36,6 +37,7 @@ async fn main() { pack.as_deref(), &runtime_config, payments_config.as_deref(), + &payment_provider_pack, ) .await .map_err(|error| error.to_string()), diff --git a/crates/registry-adapter/src/payments/config.rs b/crates/registry-adapter/src/payments/config.rs index 82e1f90cbc..458358aad1 100644 --- a/crates/registry-adapter/src/payments/config.rs +++ b/crates/registry-adapter/src/payments/config.rs @@ -1,13 +1,17 @@ // SPDX-License-Identifier: Apache-2.0 //! Operator-owned payment connections and their immutable attempt snapshots. +use registry_payment_mifos_connector::MifosConnection; use registry_payment_protocol::Money; use registry_payment_simulator_connector::SimulatorConnection; use registry_platform_httputil::client::ServiceBaseUrl; use registry_platform_yaml::SecretReference; use serde::{Deserialize, Serialize}; +use serde_json::Value; use std::collections::BTreeSet; +use super::pack::{ConnectorKind, ProviderPackPin}; + pub const API_VERSION: &str = "id.registrystack.org/formats/adapter/payments/v1alpha1"; pub const KIND: &str = "AdapterPayments"; pub const BILL_CONTRACT: &str = "service-fee-bill/v1"; @@ -18,8 +22,11 @@ pub const SCHEMA_ID: &str = #[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub struct PaymentsConfig { - #[cfg_attr(feature = "schema", schemars(length(min = 1, max = 64)))] + #[cfg_attr(feature = "schema", schemars(length(max = 64)))] pub connections: Vec, + #[cfg_attr(feature = "schema", schemars(length(max = 64)))] + #[serde(default)] + pub disbursements: Vec, } #[derive(Clone, Serialize, Deserialize)] @@ -56,14 +63,18 @@ pub struct PaymentConnection { #[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub struct PaymentBinding { - #[cfg_attr(feature = "schema", schemars(extend("const" = true)))] + /// Exact reviewed provider artifact used for new attempts. Older + /// simulator-only configurations omit it; retained attempts keep their + /// original binding unchanged across an upgrade. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub provider_pack: Option, pub simulation: bool, #[cfg_attr(feature = "schema", schemars(pattern("^[A-Z]{3}$")))] pub currency: String, #[cfg_attr(feature = "schema", schemars(range(min = 0, max = 6)))] #[serde(deserialize_with = "currency_scale")] pub currency_scale: u8, - pub provider: SimulatorConnection, + pub provider: CollectionProvider, pub provider_credential_ref: SecretReference, pub provider_credential_identity: String, #[cfg_attr(feature = "schema", schemars(range(min = 1, max = 86_400)))] @@ -72,6 +83,128 @@ pub struct PaymentBinding { pub registry: RegistryBinding, } +/// Closed provider bindings for P2G collections, selected by the authored +/// `type` member. The shared tagged-union reader preserves source positions +/// for errors inside either strict variant (CFG-ID-7, CFG-SCHEMA-8). +#[derive(Clone, Deserialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[serde( + remote = "Self", + rename_all = "kebab-case", + rename_all_fields = "camelCase", + deny_unknown_fields +)] +#[cfg_attr(feature = "schema", schemars(!remote, tag = "type"))] +pub enum CollectionProvider { + Simulator { + connection: SimulatorConnection, + }, + Mifos { + connection: MifosConnection, + payer: MifosPayerMapping, + transaction_type: MifosTransactionType, + }, + Http { + #[cfg_attr(feature = "schema", schemars(with = "registry_platform_yaml::Url"))] + submit_base_url: String, + #[cfg_attr(feature = "schema", schemars(with = "registry_platform_yaml::Url"))] + status_base_url: String, + settings: Value, + }, +} +registry_platform_yaml::tagged_union!(CollectionProvider); + +#[derive(Serialize)] +#[serde( + tag = "type", + rename_all = "kebab-case", + rename_all_fields = "camelCase" +)] +enum CollectionProviderWire<'a> { + Simulator { + connection: &'a SimulatorConnection, + }, + Mifos { + connection: &'a MifosConnection, + payer: &'a MifosPayerMapping, + transaction_type: &'a MifosTransactionType, + }, + Http { + submit_base_url: &'a str, + status_base_url: &'a str, + settings: &'a Value, + }, +} + +impl Serialize for CollectionProvider { + fn serialize(&self, serializer: S) -> Result { + match self { + Self::Simulator { connection } => CollectionProviderWire::Simulator { connection }, + Self::Mifos { + connection, + payer, + transaction_type, + } => CollectionProviderWire::Mifos { + connection, + payer, + transaction_type, + }, + Self::Http { + submit_base_url, + status_base_url, + settings, + } => CollectionProviderWire::Http { + submit_base_url, + status_base_url, + settings, + }, + } + .serialize(serializer) + } +} + +#[derive(Clone, Serialize, Deserialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct MifosPayerMapping { + #[cfg_attr( + feature = "schema", + schemars(length(min = 1, max = 32), pattern(r"^[\x21-\x7e]+$")) + )] + pub financial_address_key: String, + #[cfg_attr( + feature = "schema", + schemars(length(min = 1, max = 32), pattern(r"^[\x21-\x7e]+$")) + )] + pub payer_id_key: String, +} + +#[derive(Clone, Serialize, Deserialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct MifosTransactionType { + #[cfg_attr( + feature = "schema", + schemars(length(min = 1, max = 32), pattern(r"^[\x21-\x7e]+$")) + )] + pub scenario: String, + #[cfg_attr( + feature = "schema", + schemars(length(min = 1, max = 32), pattern(r"^[\x21-\x7e]+$")) + )] + pub sub_scenario: String, + #[cfg_attr( + feature = "schema", + schemars(length(min = 1, max = 32), pattern(r"^[\x21-\x7e]+$")) + )] + pub initiator: String, + #[cfg_attr( + feature = "schema", + schemars(length(min = 1, max = 32), pattern(r"^[\x21-\x7e]+$")) + )] + pub initiator_type: String, +} + #[derive(Clone, Serialize, Deserialize)] #[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] #[serde(rename_all = "camelCase", deny_unknown_fields)] @@ -112,7 +245,10 @@ fn replay_window<'de, D: serde::Deserializer<'de>>(deserializer: D) -> Result Result<(), ConfigError> { - if self.connections.is_empty() || self.connections.len() > 64 { + if (self.connections.is_empty() && self.disbursements.is_empty()) + || self.connections.len() > 64 + || self.disbursements.len() > 64 + { return Err(ConfigError); } let mut ids = BTreeSet::new(); @@ -136,19 +272,65 @@ impl PaymentsConfig { } connection.binding.validate()?; } + for connection in &self.disbursements { + if !ids.insert(&connection.id) { + return Err(ConfigError); + } + connection.validate()?; + } Ok(()) } } impl PaymentBinding { pub fn validate(&self) -> Result<(), ConfigError> { - if !self.simulation - || !text(&self.provider_credential_identity, 128) + if !text(&self.provider_credential_identity, 128) || !(1..=86_400).contains(&self.replay_window_seconds) { return Err(ConfigError); } - self.provider.validate().map_err(|_| ConfigError)?; + match &self.provider { + CollectionProvider::Simulator { connection } if self.simulation => { + connection.validate().map_err(|_| ConfigError)?; + } + CollectionProvider::Mifos { + connection, + payer, + transaction_type, + } if !self.simulation => { + validate_mifos(connection, payer, transaction_type)?; + } + CollectionProvider::Http { + submit_base_url, + status_base_url, + settings, + } if !self.simulation && self.provider_pack.is_some() => { + for origin in [submit_base_url, status_base_url] { + registry_platform_yaml::Url::new(origin.clone()).map_err(|_| ConfigError)?; + ServiceBaseUrl::new(url::Url::parse(origin).map_err(|_| ConfigError)?) + .map_err(|_| ConfigError)?; + } + if !settings.is_object() + || serde_json::to_vec(settings).map_err(|_| ConfigError)?.len() > 16_384 + { + return Err(ConfigError); + } + } + CollectionProvider::Simulator { .. } + | CollectionProvider::Mifos { .. } + | CollectionProvider::Http { .. } => { + return Err(ConfigError); + } + } + if self.provider_pack.as_ref().is_some_and(|pin| { + pin.id.is_empty() + || pin.version.is_empty() + || pin.digest.len() != 71 + || !pin.digest.starts_with("sha256:") + || !pin.digest[7..].bytes().all(|byte| byte.is_ascii_hexdigit()) + }) { + return Err(ConfigError); + } Money { value: "1".into(), currency: self.currency.clone(), @@ -176,19 +358,73 @@ impl PaymentBinding { } pub fn revision(&self) -> Result { + let connector = match &self.provider { + CollectionProvider::Simulator { .. } => { + registry_payment_simulator_connector::CONNECTOR_VERSION + } + CollectionProvider::Mifos { .. } => registry_payment_mifos_connector::CONNECTOR_PROFILE, + CollectionProvider::Http { .. } => "adapter-payment-http/v1", + }; let value = serde_json::json!({ - "connector": registry_payment_simulator_connector::CONNECTOR_VERSION, + "connector": connector, "billContract": BILL_CONTRACT, "binding": self, }); let canonical = registry_platform_canonical_json::canonicalize_json(&value).map_err(|_| ConfigError)?; Ok(registry_platform_config::sha256_uri(&canonical)) } + + #[must_use] + pub const fn connector_kind(&self) -> ConnectorKind { + match &self.provider { + CollectionProvider::Simulator { .. } => ConnectorKind::SimulatorP2gV1, + CollectionProvider::Mifos { .. } => ConnectorKind::MifosPhEeLegacyV1, + CollectionProvider::Http { .. } => ConnectorKind::AdapterPaymentHttpV1, + } + } + + #[must_use] + pub const fn simulator(&self) -> Option<&SimulatorConnection> { + match &self.provider { + CollectionProvider::Simulator { connection } => Some(connection), + CollectionProvider::Mifos { .. } => None, + CollectionProvider::Http { .. } => None, + } + } + + pub fn simulator_mut(&mut self) -> Option<&mut SimulatorConnection> { + match &mut self.provider { + CollectionProvider::Simulator { connection } => Some(connection), + CollectionProvider::Mifos { .. } => None, + CollectionProvider::Http { .. } => None, + } + } +} + +fn validate_mifos( + connection: &MifosConnection, + payer: &MifosPayerMapping, + transaction_type: &MifosTransactionType, +) -> Result<(), ConfigError> { + connection.validate().map_err(|_| ConfigError)?; + if !header_text(&payer.financial_address_key, 32) + || !header_text(&payer.payer_id_key, 32) + || !header_text(&transaction_type.scenario, 32) + || !header_text(&transaction_type.sub_scenario, 32) + || !header_text(&transaction_type.initiator, 32) + || !header_text(&transaction_type.initiator_type, 32) + { + return Err(ConfigError); + } + Ok(()) } pub(crate) fn text(value: &str, max: usize) -> bool { !value.is_empty() && value.len() <= max && value.bytes().all(|b| (0x21..=0x7e).contains(&b)) } +fn header_text(value: &str, max: usize) -> bool { + !value.is_empty() && value.len() <= max && value.bytes().all(|byte| byte.is_ascii_graphic()) +} fn local_id(value: &str) -> bool { text(value, 128) && value diff --git a/crates/registry-adapter/src/payments/g2p_config.rs b/crates/registry-adapter/src/payments/g2p_config.rs new file mode 100644 index 0000000000..a026cc1eea --- /dev/null +++ b/crates/registry-adapter/src/payments/g2p_config.rs @@ -0,0 +1,37 @@ +// SPDX-License-Identifier: Apache-2.0 +//! Caller and provider selection for authoritative BReg disbursements. + +use super::{config::ConfigError, g2p_model::G2pConnectionSnapshot}; +use serde::{Deserialize, Serialize}; +use std::collections::BTreeSet; + +#[derive(Clone, Serialize, Deserialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct G2pConnection { + #[cfg_attr(feature = "schema", schemars(with = "registry_platform_yaml::LocalId"))] + pub id: String, + #[cfg_attr(feature = "schema", schemars(length(min = 1, max = 64), extend("uniqueItems" = true)))] + pub allowed_clients: Vec, + pub required_scope: String, + pub binding: G2pConnectionSnapshot, +} + +impl G2pConnection { + pub fn validate(&self) -> Result<(), ConfigError> { + if registry_platform_yaml::LocalId::new(self.id.clone()).is_err() + || self.allowed_clients.is_empty() + || self.allowed_clients.len() > 64 + || self + .allowed_clients + .iter() + .any(|id| !super::config::text(id, 128)) + || self.allowed_clients.iter().collect::>().len() + != self.allowed_clients.len() + || !super::config::text(&self.required_scope, 128) + { + return Err(ConfigError); + } + self.binding.validate().map_err(|_| ConfigError) + } +} diff --git a/crates/registry-adapter/src/payments/g2p_model.rs b/crates/registry-adapter/src/payments/g2p_model.rs new file mode 100644 index 0000000000..33bd4a4e00 --- /dev/null +++ b/crates/registry-adapter/src/payments/g2p_model.rs @@ -0,0 +1,1043 @@ +// SPDX-License-Identifier: Apache-2.0 +//! Exact G2P instruction and attempt custody. +//! +//! G2P attempts are deliberately separate from fee-bill collection attempts. +//! BReg owns an immutable disbursement instruction, the provider owns its +//! execution, and this module retains only the exact bridge facts required to +//! prevent a second send and to report one correlated provider confirmation. + +use super::{ + pack::{PaymentProviderAuth, ProviderPackPin}, + provider_mapping::{ + PaymentEndpointRole, PaymentHttpMethod, PreparedProviderRequest, ProviderAcceptance, + ProviderObservation, ProviderObservationState, ProviderPartyRole, + }, +}; +use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine}; +use registry_platform_yaml::SecretReference; +use serde::{Deserialize, Serialize}; +use serde_json::{Map, Value}; +use sha2::{Digest, Sha256}; +use uuid::Uuid; + +const MAX_TEXT: usize = 128; +const MAX_MINOR_UNITS: u64 = 9_007_199_254_740_991; + +/// Value-free failures suitable for conversion at the HTTP boundary. +#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)] +pub enum G2pError { + #[error("the G2P request is invalid")] + InvalidRequest, + #[error("the G2P instruction or attempt conflicts with retained custody")] + Conflict, + #[error("the G2P instruction or attempt was not found")] + NotFound, + #[error("the G2P dependency is unavailable")] + Unavailable, + #[error("the G2P mutation outcome is unknown")] + OutcomeUnknown, + #[error("the G2P attempt is held for read-only recovery")] + RecoveryHeld, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct DisbursementInstruction { + pub record_id: Uuid, + pub instruction_id: Uuid, + pub instruction_version: u64, + pub instruction_digest: String, + pub institution_id: String, + pub service_id: String, + pub programme_id: String, + pub cycle_id: String, + pub beneficiary_id: String, + pub beneficiary_destination: String, + pub funding_account_id: String, + pub amount_minor: u64, + pub currency: String, + pub currency_scale: u8, +} + +impl DisbursementInstruction { + pub fn validate(&self) -> Result<(), G2pError> { + if self.record_id.is_nil() + || self.instruction_id.is_nil() + || self.instruction_version == 0 + || self.instruction_version > MAX_MINOR_UNITS + || !digest_text(&self.instruction_digest) + || !text(&self.institution_id, MAX_TEXT) + || !text(&self.service_id, MAX_TEXT) + || !text(&self.programme_id, MAX_TEXT) + || !text(&self.cycle_id, MAX_TEXT) + || !text(&self.beneficiary_id, MAX_TEXT) + || !text(&self.beneficiary_destination, MAX_TEXT) + || !text(&self.funding_account_id, MAX_TEXT) + || self.amount_minor == 0 + || self.amount_minor > MAX_MINOR_UNITS + || self.currency.len() != 3 + || !self.currency.bytes().all(|byte| byte.is_ascii_uppercase()) + || self.currency_scale > 6 + { + return Err(G2pError::Unavailable); + } + Ok(()) + } + + pub fn amount(&self) -> String { + let factor = 10_u64.pow(u32::from(self.currency_scale)); + if self.currency_scale == 0 { + self.amount_minor.to_string() + } else { + format!( + "{}.{:0width$}", + self.amount_minor / factor, + self.amount_minor % factor, + width = usize::from(self.currency_scale) + ) + } + } + + pub fn digest(&self) -> Result { + canonical_digest(self) + } +} + +/// Closed, host-owned authentication profile. Mapping scripts never receive +/// these credentials or choose an authentication mechanism. +#[derive(Clone)] +pub enum G2pHttpAuth { + Bearer, + MifosLegacySignature { + signing_key_identity: String, + signing_key_ref: SecretReference, + response_key_identity: String, + response_key_ref: SecretReference, + }, +} + +#[derive(Deserialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[serde( + remote = "Self", + rename_all = "kebab-case", + rename_all_fields = "camelCase", + deny_unknown_fields +)] +#[cfg_attr(feature = "schema", schemars(!remote, tag = "type"))] +enum G2pHttpAuthReader { + Bearer {}, + MifosLegacySignature { + signing_key_identity: String, + signing_key_ref: SecretReference, + response_key_identity: String, + response_key_ref: SecretReference, + }, +} +registry_platform_yaml::tagged_union!(G2pHttpAuthReader); + +impl<'de> Deserialize<'de> for G2pHttpAuth { + fn deserialize>(deserializer: D) -> Result { + ::deserialize(deserializer).map(|reader| match reader { + G2pHttpAuthReader::Bearer {} => Self::Bearer, + G2pHttpAuthReader::MifosLegacySignature { + signing_key_identity, + signing_key_ref, + response_key_identity, + response_key_ref, + } => Self::MifosLegacySignature { + signing_key_identity, + signing_key_ref, + response_key_identity, + response_key_ref, + }, + }) + } +} + +#[derive(Serialize)] +#[serde( + tag = "type", + rename_all = "kebab-case", + rename_all_fields = "camelCase" +)] +enum G2pHttpAuthWire<'a> { + Bearer {}, + MifosLegacySignature { + signing_key_identity: &'a str, + signing_key_ref: &'a SecretReference, + response_key_identity: &'a str, + response_key_ref: &'a SecretReference, + }, +} + +impl Serialize for G2pHttpAuth { + fn serialize(&self, serializer: S) -> Result { + match self { + Self::Bearer => G2pHttpAuthWire::Bearer {}, + Self::MifosLegacySignature { + signing_key_identity, + signing_key_ref, + response_key_identity, + response_key_ref, + } => G2pHttpAuthWire::MifosLegacySignature { + signing_key_identity, + signing_key_ref, + response_key_identity, + response_key_ref, + }, + } + .serialize(serializer) + } +} + +#[cfg(feature = "schema")] +impl schemars::JsonSchema for G2pHttpAuth { + fn schema_name() -> std::borrow::Cow<'static, str> { + "G2pHttpAuth".into() + } + + fn json_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema { + G2pHttpAuthReader::json_schema(generator) + } +} + +impl G2pHttpAuth { + pub const fn profile(&self) -> PaymentProviderAuth { + match self { + Self::Bearer => PaymentProviderAuth::Bearer, + Self::MifosLegacySignature { .. } => PaymentProviderAuth::MifosLegacySignature, + } + } + + fn validate(&self) -> Result<(), G2pError> { + match self { + Self::Bearer => Ok(()), + Self::MifosLegacySignature { + signing_key_identity, + response_key_identity, + .. + } if text(signing_key_identity, 256) && text(response_key_identity, 256) => Ok(()), + Self::MifosLegacySignature { .. } => Err(G2pError::Unavailable), + } + } + + fn identity(&self) -> Value { + match self { + Self::Bearer => serde_json::json!({"type": "bearer"}), + Self::MifosLegacySignature { + signing_key_identity, + response_key_identity, + .. + } => serde_json::json!({ + "type": "mifos-legacy-signature", + "signingKeyIdentity": signing_key_identity, + "responseKeyIdentity": response_key_identity, + }), + } + } +} + +/// Deployment-owned provider facts frozen into every attempt. +#[derive(Clone, Deserialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[serde( + remote = "Self", + rename_all = "kebab-case", + rename_all_fields = "camelCase", + deny_unknown_fields +)] +#[cfg_attr(feature = "schema", schemars(!remote, tag = "type"))] +pub enum G2pProviderBinding { + Http { + revision: String, + #[cfg_attr(feature = "schema", schemars(with = "registry_platform_yaml::Url"))] + submit_base_url: String, + #[cfg_attr(feature = "schema", schemars(with = "registry_platform_yaml::Url"))] + status_base_url: String, + credential_identity: String, + credential_ref: SecretReference, + auth: G2pHttpAuth, + settings: Value, + }, +} +registry_platform_yaml::tagged_union!(G2pProviderBinding); + +#[derive(Serialize)] +#[serde( + tag = "type", + rename_all = "kebab-case", + rename_all_fields = "camelCase" +)] +enum G2pProviderBindingWire<'a> { + Http { + revision: &'a str, + submit_base_url: &'a str, + status_base_url: &'a str, + credential_identity: &'a str, + credential_ref: &'a SecretReference, + auth: &'a G2pHttpAuth, + settings: &'a Value, + }, +} + +impl Serialize for G2pProviderBinding { + fn serialize(&self, serializer: S) -> Result { + match self { + Self::Http { + revision, + submit_base_url, + status_base_url, + credential_identity, + credential_ref, + auth, + settings, + } => G2pProviderBindingWire::Http { + revision, + submit_base_url, + status_base_url, + credential_identity, + credential_ref, + auth, + settings, + }, + } + .serialize(serializer) + } +} + +impl G2pProviderBinding { + pub fn validate(&self) -> Result<(), G2pError> { + match self { + Self::Http { + revision, + submit_base_url, + status_base_url, + credential_identity, + auth, + settings, + .. + } => { + if !text(revision, 256) + || !text(credential_identity, 256) + || !provider_base_url(submit_base_url) + || !provider_base_url(status_base_url) + || !non_secret_settings(settings) + { + return Err(G2pError::Unavailable); + } + auth.validate() + } + } + } + + pub fn settings(&self) -> &Value { + match self { + Self::Http { settings, .. } => settings, + } + } + + pub fn credential_ref(&self) -> &SecretReference { + match self { + Self::Http { credential_ref, .. } => credential_ref, + } + } + + pub fn auth(&self) -> &G2pHttpAuth { + match self { + Self::Http { auth, .. } => auth, + } + } + + pub const fn auth_profile(&self) -> PaymentProviderAuth { + match self { + Self::Http { auth, .. } => auth.profile(), + } + } + + pub fn base_url(&self, role: PaymentEndpointRole) -> Result<&str, G2pError> { + match (self, role) { + ( + Self::Http { + submit_base_url, .. + }, + PaymentEndpointRole::DisbursementSubmit, + ) => Ok(submit_base_url), + ( + Self::Http { + status_base_url, .. + }, + PaymentEndpointRole::DisbursementStatus, + ) => Ok(status_base_url), + _ => Err(G2pError::Unavailable), + } + } + + fn identity(&self) -> Result { + self.validate()?; + match self { + Self::Http { + revision, + submit_base_url, + status_base_url, + credential_identity, + auth, + settings, + .. + } => Ok(serde_json::json!({ + "type": "http", + "revision": revision, + "submitOrigin": canonical_origin(submit_base_url)?, + "statusOrigin": canonical_origin(status_base_url)?, + "credentialIdentity": credential_identity, + "auth": auth.identity(), + "settings": settings, + })), + } + } +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct G2pProviderMoney { + pub minor_units: String, + pub currency: String, + pub scale: u8, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct G2pProviderParty { + pub scheme: String, + pub value: String, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct G2pProviderIntent { + pub correlation_id: String, + pub instruction_id: Uuid, + pub instruction_version: u64, + pub institution_id: String, + pub service_id: String, + pub programme_id: String, + pub cycle_id: String, + pub beneficiary_id: String, + pub funding: G2pProviderParty, + pub recipient: G2pProviderParty, + pub money: G2pProviderMoney, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "kebab-case")] +pub enum G2pObservationState { + Pending, + ProviderRejected, + ProviderConfirmed, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct G2pProviderObservation { + pub correlation_id: String, + pub provider_reference: Option, + pub state: G2pObservationState, + pub money: G2pProviderMoney, + pub funding: G2pProviderParty, + pub recipient: G2pProviderParty, +} + +/// BReg route and exact Action authority frozen into an attempt. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct G2pRegistryBinding { + #[cfg_attr(feature = "schema", schemars(with = "registry_platform_yaml::Url"))] + pub base_url: String, + pub credential_identity: String, + pub credential_ref: SecretReference, + pub record_route: String, + pub record_type: String, + pub read_profile: String, + pub bind_action: String, + pub bind_profile: String, + pub report_action: String, + pub report_profile: String, +} + +impl G2pRegistryBinding { + pub fn validate(&self) -> Result<(), G2pError> { + let origin = url::Url::parse(&self.base_url).map_err(|_| G2pError::Unavailable)?; + if origin.scheme() != "https" + || !origin.username().is_empty() + || origin.password().is_some() + || origin.query().is_some() + || origin.fragment().is_some() + { + return Err(G2pError::Unavailable); + } + for value in [ + &self.credential_identity, + &self.record_route, + &self.record_type, + &self.read_profile, + &self.bind_action, + &self.bind_profile, + &self.report_action, + &self.report_profile, + ] { + if !text(value, 256) { + return Err(G2pError::Unavailable); + } + } + Ok(()) + } + + /// Stable authority namespace for disbursement uniqueness. Credential and + /// access-profile rotation, and public connection renames, do not create a + /// new authoritative instruction source. + pub fn source_namespace(&self) -> Result { + self.validate()?; + canonical_digest(&serde_json::json!({ + "domain": "registry-adapter/g2p-source-namespace/v1", + "origin": canonical_registry_origin(&self.base_url)?, + "recordRoute": self.record_route, + "recordType": self.record_type, + })) + } +} + +#[derive(Clone, Serialize, Deserialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct G2pConnectionSnapshot { + pub institution_id: String, + pub service_id: String, + pub programme_id: String, + pub funding_account_id: String, + pub currency: String, + #[serde(deserialize_with = "currency_scale")] + #[cfg_attr( + feature = "schema", + schemars(with = "registry_platform_yaml::BoundedU32<0, 6>") + )] + pub currency_scale: u8, + pub provider_pack: ProviderPackPin, + pub funding_party_key: String, + pub recipient_party_key: String, + pub provider: G2pProviderBinding, + pub registry: G2pRegistryBinding, +} + +impl G2pConnectionSnapshot { + pub fn validate(&self) -> Result<(), G2pError> { + if !text(&self.institution_id, MAX_TEXT) + || !text(&self.service_id, MAX_TEXT) + || !text(&self.programme_id, MAX_TEXT) + || !text(&self.funding_account_id, MAX_TEXT) + || self.currency.len() != 3 + || !self.currency.bytes().all(|byte| byte.is_ascii_uppercase()) + || self.currency_scale > 6 + || !provider_pack_pin(&self.provider_pack) + || !text(&self.funding_party_key, MAX_TEXT) + || !text(&self.recipient_party_key, MAX_TEXT) + || self.funding_party_key == self.recipient_party_key + { + return Err(G2pError::Unavailable); + } + self.provider.validate()?; + self.registry.validate() + } + + pub fn validate_instruction( + &self, + instruction: &DisbursementInstruction, + ) -> Result<(), G2pError> { + instruction.validate()?; + if instruction.institution_id != self.institution_id + || instruction.service_id != self.service_id + || instruction.programme_id != self.programme_id + || instruction.funding_account_id != self.funding_account_id + || instruction.currency != self.currency + || instruction.currency_scale != self.currency_scale + { + return Err(G2pError::Conflict); + } + Ok(()) + } + + pub fn revision(&self) -> Result { + canonical_digest(self) + } + + pub fn provider_intent( + &self, + instruction: &DisbursementInstruction, + ) -> Result { + self.validate()?; + self.validate_instruction(instruction)?; + let funding = G2pProviderParty { + scheme: self.funding_party_key.clone(), + value: instruction.funding_account_id.clone(), + }; + let recipient = G2pProviderParty { + scheme: self.recipient_party_key.clone(), + value: instruction.beneficiary_destination.clone(), + }; + let money = G2pProviderMoney { + minor_units: instruction.amount_minor.to_string(), + currency: instruction.currency.clone(), + scale: instruction.currency_scale, + }; + let identity = serde_json::json!({ + "domain": "registry-adapter/g2p-correlation/v3", + "source": { + "origin": canonical_origin(&self.registry.base_url)?, + "credentialIdentity": self.registry.credential_identity, + "recordRoute": self.registry.record_route, + "recordType": self.registry.record_type, + "readProfile": self.registry.read_profile, + "bindAction": self.registry.bind_action, + "bindProfile": self.registry.bind_profile, + "reportAction": self.registry.report_action, + "reportProfile": self.registry.report_profile, + }, + "instruction": instruction, + "providerPack": self.provider_pack, + "provider": self.provider.identity()?, + "exactTuple": { + "funding": funding, + "recipient": recipient, + "money": money, + }, + }); + let canonical = registry_platform_canonical_json::canonicalize_json(&identity) + .map_err(|_| G2pError::Unavailable)?; + let correlation_id = format!("g2p_{}", URL_SAFE_NO_PAD.encode(Sha256::digest(canonical))); + Ok(G2pProviderIntent { + correlation_id, + instruction_id: instruction.instruction_id, + instruction_version: instruction.instruction_version, + institution_id: instruction.institution_id.clone(), + service_id: instruction.service_id.clone(), + programme_id: instruction.programme_id.clone(), + cycle_id: instruction.cycle_id.clone(), + beneficiary_id: instruction.beneficiary_id.clone(), + funding, + recipient, + money, + }) + } + + pub fn attempt_revision( + &self, + prepared_submit: &PreparedProviderRequest, + ) -> Result { + canonical_digest(&serde_json::json!({ + "domain": "registry-adapter/g2p-attempt-binding/v1", + "binding": self, + "preparedSubmitDigest": canonical_digest(prepared_submit)?, + })) + } +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct PreparedG2pRegistryAction { + pub action: String, + pub key: String, + pub inputs: Map, + pub evidence: String, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "kebab-case")] +pub enum G2pAttemptState { + BindPrepared, + Bound, + DispatchStarted, + ProviderAccepted, + ProviderPending, + ProviderUnknown, + ProviderConfirmed, + ProviderFailed, + ConfirmationPrepared, + ConfirmationRecorded, +} + +#[derive(Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct G2pAttempt { + pub id: Uuid, + pub connection: String, + pub principal: String, + pub source_namespace: String, + pub instruction: DisbursementInstruction, + pub instruction_snapshot_digest: String, + pub binding: G2pConnectionSnapshot, + pub binding_revision: String, + pub provider_intent: G2pProviderIntent, + pub prepared_submit: PreparedProviderRequest, + pub prepared_submit_digest: String, + pub state: G2pAttemptState, + pub bind_action: PreparedG2pRegistryAction, + pub first_send_at_unix_seconds: Option, + pub provider_acceptance: Option, + pub provider_observation: Option, + pub confirmation_action: Option, + pub provider_result_digest: Option, +} + +impl G2pAttempt { + pub fn new( + id: Uuid, + connection: String, + principal: String, + instruction: DisbursementInstruction, + binding: G2pConnectionSnapshot, + prepared_submit: PreparedProviderRequest, + bind_action: PreparedG2pRegistryAction, + ) -> Result { + if id.is_nil() || !text(&connection, MAX_TEXT) || !text(&principal, MAX_TEXT) { + return Err(G2pError::InvalidRequest); + } + instruction.validate()?; + binding.validate()?; + binding.validate_instruction(&instruction)?; + let source_namespace = binding.registry.source_namespace()?; + let instruction_snapshot_digest = instruction.digest()?; + let provider_intent = binding.provider_intent(&instruction)?; + validate_prepared_submit(&binding, &prepared_submit)?; + let prepared_submit_digest = canonical_digest(&prepared_submit)?; + let binding_revision = binding.attempt_revision(&prepared_submit)?; + let attempt = Self { + id, + connection, + principal, + source_namespace, + instruction, + instruction_snapshot_digest, + binding, + binding_revision, + provider_intent, + prepared_submit, + prepared_submit_digest, + state: G2pAttemptState::BindPrepared, + bind_action, + first_send_at_unix_seconds: None, + provider_acceptance: None, + provider_observation: None, + confirmation_action: None, + provider_result_digest: None, + }; + attempt.validate_integrity()?; + Ok(attempt) + } + + pub fn status_state(&self) -> G2pObservationState { + match self.state { + G2pAttemptState::ProviderAccepted | G2pAttemptState::ProviderPending => { + G2pObservationState::Pending + } + G2pAttemptState::ProviderConfirmed + | G2pAttemptState::ConfirmationPrepared + | G2pAttemptState::ConfirmationRecorded => G2pObservationState::ProviderConfirmed, + G2pAttemptState::ProviderFailed => G2pObservationState::ProviderRejected, + G2pAttemptState::BindPrepared + | G2pAttemptState::Bound + | G2pAttemptState::DispatchStarted + | G2pAttemptState::ProviderUnknown => G2pObservationState::Pending, + } + } + + pub fn validate_integrity(&self) -> Result<(), G2pError> { + self.instruction.validate()?; + self.binding.validate()?; + self.binding.validate_instruction(&self.instruction)?; + if self.binding.registry.source_namespace()? != self.source_namespace + || self.instruction.digest()? != self.instruction_snapshot_digest + || self.binding.provider_intent(&self.instruction)? != self.provider_intent + || canonical_digest(&self.prepared_submit)? != self.prepared_submit_digest + || self.binding.attempt_revision(&self.prepared_submit)? != self.binding_revision + || validate_prepared_submit(&self.binding, &self.prepared_submit).is_err() + || self.bind_action.action != self.binding.registry.bind_action + { + return Err(G2pError::Unavailable); + } + let dispatched = self.first_send_at_unix_seconds.is_some(); + let accepted = self.provider_acceptance.is_some(); + let observed = self.provider_observation.is_some(); + let confirmation = self.confirmation_action.is_some(); + let result_digest = self.provider_result_digest.is_some(); + let valid_shape = match self.state { + G2pAttemptState::BindPrepared | G2pAttemptState::Bound => { + !dispatched && !accepted && !observed && !confirmation && !result_digest + } + G2pAttemptState::DispatchStarted => { + dispatched && !accepted && !observed && !confirmation && !result_digest + } + G2pAttemptState::ProviderAccepted => { + dispatched && accepted && !observed && !confirmation && !result_digest + } + G2pAttemptState::ProviderPending + | G2pAttemptState::ProviderUnknown + | G2pAttemptState::ProviderConfirmed + | G2pAttemptState::ProviderFailed => { + dispatched && accepted && observed && !confirmation && result_digest + } + G2pAttemptState::ConfirmationPrepared | G2pAttemptState::ConfirmationRecorded => { + dispatched && accepted && observed && confirmation && result_digest + } + }; + if !valid_shape { + return Err(G2pError::Unavailable); + } + if let (Some(accepted), Some(observation)) = + (&self.provider_acceptance, &self.provider_observation) + { + self.validate_observation(accepted, observation)?; + let expected = canonical_digest(observation)?; + if self.provider_result_digest.as_deref() != Some(&expected) { + return Err(G2pError::Unavailable); + } + let expected_state = match observation.state { + G2pObservationState::Pending => G2pAttemptState::ProviderPending, + G2pObservationState::ProviderConfirmed => G2pAttemptState::ProviderConfirmed, + G2pObservationState::ProviderRejected => G2pAttemptState::ProviderFailed, + }; + if !matches!( + self.state, + G2pAttemptState::ConfirmationPrepared | G2pAttemptState::ConfirmationRecorded + ) && self.state != expected_state + { + return Err(G2pError::Unavailable); + } + if matches!( + self.state, + G2pAttemptState::ConfirmationPrepared | G2pAttemptState::ConfirmationRecorded + ) && observation.state != G2pObservationState::ProviderConfirmed + { + return Err(G2pError::Unavailable); + } + } + if let Some(action) = &self.confirmation_action { + if action.action != self.binding.registry.report_action { + return Err(G2pError::Unavailable); + } + } + Ok(()) + } + + pub fn validate_acceptance(&self, accepted: &ProviderAcceptance) -> Result<(), G2pError> { + if accepted.correlation_id != self.provider_intent.correlation_id + || accepted.references.is_empty() + || accepted.references.len() > 16 + || accepted + .references + .iter() + .any(|(key, value)| !text(key, 64) || !text(value, 512)) + { + return Err(G2pError::Conflict); + } + Ok(()) + } + + pub fn validate_mapped_observation( + &self, + accepted: &ProviderAcceptance, + observation: &ProviderObservation, + ) -> Result { + self.validate_acceptance(accepted)?; + let funding = observation + .parties + .iter() + .find(|party| party.role == ProviderPartyRole::Funding) + .ok_or(G2pError::Conflict)?; + let recipient = observation + .parties + .iter() + .find(|party| party.role == ProviderPartyRole::Recipient) + .ok_or(G2pError::Conflict)?; + if observation.correlation_id != accepted.correlation_id + || observation.correlation_id != self.provider_intent.correlation_id + || funding.key != self.provider_intent.funding.scheme + || funding.value != self.provider_intent.funding.value + || recipient.key != self.provider_intent.recipient.scheme + || recipient.value != self.provider_intent.recipient.value + || observation.money.minor_units != self.provider_intent.money.minor_units + || observation.money.currency != self.provider_intent.money.currency + || observation.money.scale != self.provider_intent.money.scale + || !text(&observation.provider_reference, 512) + { + return Err(G2pError::Conflict); + } + Ok(G2pProviderObservation { + correlation_id: observation.correlation_id.clone(), + provider_reference: Some(observation.provider_reference.clone()), + state: match observation.state { + ProviderObservationState::Pending => G2pObservationState::Pending, + ProviderObservationState::ProviderRejected => G2pObservationState::ProviderRejected, + ProviderObservationState::ProviderConfirmed => { + G2pObservationState::ProviderConfirmed + } + }, + money: self.provider_intent.money.clone(), + funding: self.provider_intent.funding.clone(), + recipient: self.provider_intent.recipient.clone(), + }) + } + + pub fn validate_observation( + &self, + accepted: &ProviderAcceptance, + observation: &G2pProviderObservation, + ) -> Result<(), G2pError> { + self.validate_acceptance(accepted)?; + if observation.correlation_id != accepted.correlation_id + || observation.correlation_id != self.provider_intent.correlation_id + || observation.funding != self.provider_intent.funding + || observation.recipient != self.provider_intent.recipient + || observation.money != self.provider_intent.money + || observation + .provider_reference + .as_deref() + .is_none_or(|value| !text(value, 512)) + { + return Err(G2pError::Conflict); + } + Ok(()) + } +} + +pub fn canonical_digest(value: &impl Serialize) -> Result { + let value = serde_json::to_value(value).map_err(|_| G2pError::Unavailable)?; + let bytes = registry_platform_canonical_json::canonicalize_json(&value) + .map_err(|_| G2pError::Unavailable)?; + let digest = Sha256::digest(bytes); + Ok(hex_lower(&digest)) +} + +fn validate_prepared_submit( + binding: &G2pConnectionSnapshot, + request: &PreparedProviderRequest, +) -> Result<(), G2pError> { + if request.provider_pack != binding.provider_pack + || request.role != PaymentEndpointRole::DisbursementSubmit + || request.method != PaymentHttpMethod::Post + || request.path.is_empty() + || !request.path.starts_with('/') + || request.path.len() > 4_096 + || request.body.is_none() + || request + .body + .as_ref() + .is_some_and(|body| body.len() > 65_536) + { + return Err(G2pError::Unavailable); + } + Ok(()) +} + +fn provider_pack_pin(pin: &ProviderPackPin) -> bool { + text(&pin.id, 128) + && text(&pin.version, 64) + && pin.digest.len() == 71 + && pin.digest.starts_with("sha256:") + && pin.digest[7..].bytes().all(|byte| byte.is_ascii_hexdigit()) +} + +fn provider_base_url(value: &str) -> bool { + let Ok(url) = url::Url::parse(value) else { + return false; + }; + if !url.username().is_empty() + || url.password().is_some() + || url.query().is_some() + || url.fragment().is_some() + { + return false; + } + if url.scheme() == "https" { + return true; + } + if url.scheme() != "http" { + return false; + } + match url.host() { + Some(url::Host::Ipv4(address)) => address.is_loopback(), + Some(url::Host::Ipv6(address)) => address.is_loopback(), + Some(url::Host::Domain(_)) | None => false, + } +} + +fn non_secret_settings(value: &Value) -> bool { + let Ok(bytes) = serde_json::to_vec(value) else { + return false; + }; + if bytes.len() > 65_536 || !value.is_object() { + return false; + } + fn safe(value: &Value) -> bool { + match value { + Value::Null | Value::Bool(_) | Value::Number(_) => true, + Value::String(value) => { + value.len() <= 4_096 + && !value.chars().any(char::is_control) + && !value.starts_with("secret:") + } + Value::Array(values) => values.len() <= 256 && values.iter().all(safe), + Value::Object(values) => { + values.len() <= 256 + && values.iter().all(|(key, value)| { + text(key, 128) + && !matches!( + key.to_ascii_lowercase().as_str(), + "authorization" + | "credential" + | "password" + | "secret" + | "token" + | "x-api-key" + ) + && safe(value) + }) + } + } + } + safe(value) +} + +fn hex_lower(bytes: &[u8]) -> String { + const HEX: &[u8; 16] = b"0123456789abcdef"; + let mut output = String::with_capacity(bytes.len() * 2); + for byte in bytes { + output.push(char::from(HEX[usize::from(byte >> 4)])); + output.push(char::from(HEX[usize::from(byte & 0x0f)])); + } + output +} + +fn digest_text(value: &str) -> bool { + value.len() == 64 && value.bytes().all(|byte| byte.is_ascii_hexdigit()) +} + +fn text(value: &str, max: usize) -> bool { + !value.is_empty() && value.len() <= max && !value.chars().any(char::is_control) +} + +fn canonical_origin(value: &str) -> Result { + url::Url::parse(value) + .map(|origin| origin.to_string()) + .map_err(|_| G2pError::Unavailable) +} + +fn canonical_registry_origin(value: &str) -> Result { + url::Url::parse(value) + .map(|url| url.origin().ascii_serialization()) + .map_err(|_| G2pError::Unavailable) +} + +fn currency_scale<'de, D: serde::Deserializer<'de>>(deserializer: D) -> Result { + registry_platform_yaml::BoundedU32::<0, 6>::deserialize(deserializer) + .map(|value| u8::try_from(value.get()).expect("the bounded scale fits in u8")) +} diff --git a/crates/registry-adapter/src/payments/g2p_registry.rs b/crates/registry-adapter/src/payments/g2p_registry.rs new file mode 100644 index 0000000000..682ee7ad7d --- /dev/null +++ b/crates/registry-adapter/src/payments/g2p_registry.rs @@ -0,0 +1,400 @@ +// SPDX-License-Identifier: Apache-2.0 +//! Restricted BReg bridge for authoritative G2P instructions. + +use super::g2p_model::{ + DisbursementInstruction, G2pAttempt, G2pError, G2pRegistryBinding, PreparedG2pRegistryAction, +}; +use async_trait::async_trait; +use registry_breg_client::{ + BRegActionInvocationRequest, BRegActionTargetConditionsRequest, BRegIdempotencyKey, + BRegPreparedAction, BRegRecordOptions, BaseRegistryClient, BaseRegistryClientConfig, + StaticToken, +}; +use registry_platform_config::SecretResolver; +use serde_json::{json, Map, Value}; +use std::{collections::BTreeMap, sync::Arc, time::Duration}; +use uuid::Uuid; + +const MAX_MINOR_UNITS: u64 = 9_007_199_254_740_991; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum G2pInstructionState { + InstructionReady, + AttemptBound, + ProviderConfirmed, +} + +#[derive(Clone)] +pub struct G2pInstructionView { + pub instruction: DisbursementInstruction, + pub state: G2pInstructionState, + pub payout_attempt_id: Option, + pub provider_binding_revision: Option, + pub provider_status: Option, + pub provider_reference: Option, + pub provider_result_digest: Option, +} + +impl G2pInstructionView { + pub fn decode(record_id: Uuid, data: BTreeMap) -> Result { + let string = |key: &str| { + data.get(key) + .and_then(Value::as_str) + .map(str::to_owned) + .ok_or(G2pError::Unavailable) + }; + let integer = |key: &str| { + data.get(key) + .and_then(Value::as_u64) + .filter(|value| *value <= MAX_MINOR_UNITS) + .ok_or(G2pError::Unavailable) + }; + let optional = |key: &str| match data.get(key) { + None | Some(Value::Null) => Ok(None), + Some(Value::String(value)) if !value.is_empty() => Ok(Some(value.clone())), + _ => Err(G2pError::Unavailable), + }; + let instruction = DisbursementInstruction { + record_id, + instruction_id: Uuid::parse_str(&string("instructionId")?) + .map_err(|_| G2pError::Unavailable)?, + instruction_version: integer("instructionVersion")?, + instruction_digest: string("instructionDigest")?, + institution_id: string("institutionId")?, + service_id: string("serviceId")?, + programme_id: string("programmeId")?, + cycle_id: string("cycleId")?, + beneficiary_id: string("beneficiaryId")?, + beneficiary_destination: string("beneficiaryDestination")?, + funding_account_id: string("fundingAccountId")?, + amount_minor: integer("amountMinor")?, + currency: string("currency")?, + currency_scale: u8::try_from(integer("currencyScale")?) + .map_err(|_| G2pError::Unavailable)?, + }; + instruction.validate()?; + let state = match string("disbursementState")?.as_str() { + "instruction-ready" => G2pInstructionState::InstructionReady, + "attempt-bound" => G2pInstructionState::AttemptBound, + "provider-confirmed" => G2pInstructionState::ProviderConfirmed, + _ => return Err(G2pError::Unavailable), + }; + let payout_attempt_id = optional("payoutAttemptId")? + .map(|value| Uuid::parse_str(&value).map_err(|_| G2pError::Unavailable)) + .transpose()?; + Ok(Self { + instruction, + state, + payout_attempt_id, + provider_binding_revision: optional("providerBindingRevision")?, + provider_status: optional("providerStatus")?, + provider_reference: optional("providerReference")?, + provider_result_digest: optional("providerResultDigest")?, + }) + } + + pub fn matches_bound(&self, attempt: &G2pAttempt) -> bool { + self.instruction == attempt.instruction + && self.payout_attempt_id == Some(attempt.id) + && self.provider_binding_revision.as_deref() == Some(&attempt.binding_revision) + && matches!( + self.state, + G2pInstructionState::AttemptBound | G2pInstructionState::ProviderConfirmed + ) + } + + pub fn matches_confirmation(&self, attempt: &G2pAttempt) -> bool { + let Some(observation) = &attempt.provider_observation else { + return false; + }; + let Some(reference) = observation.provider_reference.as_deref() else { + return false; + }; + self.matches_bound(attempt) + && self.state == G2pInstructionState::ProviderConfirmed + && self.provider_status.as_deref() == Some("COMPLETED") + && self.provider_reference.as_deref() == Some(reference) + && self.provider_result_digest.as_deref() == attempt.provider_result_digest.as_deref() + } +} + +pub fn bind_inputs(attempt: &G2pAttempt) -> Result, G2pError> { + bind_inputs_for(&attempt.instruction, attempt.id, &attempt.binding_revision) +} + +pub fn bind_inputs_for( + instruction: &DisbursementInstruction, + attempt_id: Uuid, + binding_revision: &str, +) -> Result, G2pError> { + instruction.validate()?; + if attempt_id.is_nil() || binding_revision.is_empty() { + return Err(G2pError::InvalidRequest); + } + object(json!({ + "instructionRecordId": instruction.record_id, + "instructionId": instruction.instruction_id, + "instructionVersion": instruction.instruction_version, + "instructionDigest": instruction.instruction_digest, + "institutionId": instruction.institution_id, + "serviceId": instruction.service_id, + "programmeId": instruction.programme_id, + "cycleId": instruction.cycle_id, + "beneficiaryId": instruction.beneficiary_id, + "beneficiaryDestination": instruction.beneficiary_destination, + "fundingAccountId": instruction.funding_account_id, + "amountMinor": instruction.amount_minor, + "currency": instruction.currency, + "currencyScale": instruction.currency_scale, + "payoutAttemptId": attempt_id, + "providerBindingRevision": binding_revision, + })) +} + +pub fn confirmation_inputs(attempt: &G2pAttempt) -> Result, G2pError> { + if attempt.state != super::g2p_model::G2pAttemptState::ProviderConfirmed { + return Err(G2pError::Conflict); + } + let observation = attempt + .provider_observation + .as_ref() + .ok_or(G2pError::Conflict)?; + let reference = observation + .provider_reference + .as_deref() + .ok_or(G2pError::Conflict)?; + let mut inputs = bind_inputs(attempt)?; + inputs.insert("providerStatus".to_owned(), json!("COMPLETED")); + inputs.insert("providerReference".to_owned(), json!(reference)); + inputs.insert( + "providerResultDigest".to_owned(), + json!(attempt + .provider_result_digest + .as_ref() + .ok_or(G2pError::Conflict)?), + ); + Ok(inputs) +} + +#[async_trait] +pub trait G2pRegistryPort: Send + Sync { + async fn read_instruction( + &self, + binding: &G2pRegistryBinding, + record_id: Uuid, + ) -> Result; + + async fn prepare_bind( + &self, + binding: &G2pRegistryBinding, + key: &str, + inputs: Map, + ) -> Result; + + async fn invoke_bind( + &self, + binding: &G2pRegistryBinding, + prepared: &PreparedG2pRegistryAction, + ) -> Result<(), G2pError>; + + async fn prepare_confirmation( + &self, + binding: &G2pRegistryBinding, + key: &str, + inputs: Map, + ) -> Result; + + async fn invoke_confirmation( + &self, + binding: &G2pRegistryBinding, + prepared: &PreparedG2pRegistryAction, + ) -> Result<(), G2pError>; +} + +pub struct BregG2pBridge { + resolver: Arc, +} + +impl BregG2pBridge { + pub fn new(resolver: Arc) -> Self { + Self { resolver } + } + + fn client(&self, binding: &G2pRegistryBinding) -> Result { + binding.validate()?; + let secret = self + .resolver + .resolve(binding.credential_ref.as_str()) + .map_err(|_| G2pError::Unavailable)?; + let token = + std::str::from_utf8(secret.expose_secret()).map_err(|_| G2pError::Unavailable)?; + let provider = StaticToken::new(token.to_owned()).map_err(|_| G2pError::Unavailable)?; + let url = url::Url::parse(&binding.base_url).map_err(|_| G2pError::Unavailable)?; + BaseRegistryClient::new( + BaseRegistryClientConfig::new(url) + .with_token_provider(Arc::new(provider)) + .with_attempt_timeout(Duration::from_secs(15)) + .with_connect_timeout(Duration::from_secs(5)) + .with_maximum_response_bytes(65_536) + .with_maximum_mutation_retries(0), + ) + .map_err(|_| G2pError::Unavailable) + } + + async fn prepare( + &self, + binding: &G2pRegistryBinding, + report: bool, + key: &str, + inputs: Map, + ) -> Result { + let client = self.client(binding)?; + let (action, profile) = selected(binding, report); + let metadata = client + .registry_contract(Some(profile)) + .await + .map_err(|_| G2pError::Unavailable)? + .value; + let selected = metadata + .select_action(action, profile) + .map_err(|_| G2pError::Unavailable)?; + let key = BRegIdempotencyKey::parse(key).map_err(|_| G2pError::Unavailable)?; + let conditions = if selected.required_condition_keys().is_empty() { + None + } else { + let references = selected + .required_condition_keys() + .iter() + .map(|name| inputs.get(name).cloned().map(|value| (name.clone(), value))) + .collect::>>() + .ok_or(G2pError::Unavailable)?; + let request = BRegActionTargetConditionsRequest::new(&selected, references) + .map_err(|_| G2pError::Unavailable)?; + Some( + client + .action_target_conditions(&selected, &request) + .await + .map_err(|_| G2pError::Unavailable)? + .value, + ) + }; + let request = + BRegActionInvocationRequest::new(&selected, inputs.clone(), conditions.as_ref()) + .map_err(|_| G2pError::Unavailable)?; + let evidence = client + .prepare_action(&selected, &request, &key) + .map_err(|_| G2pError::Unavailable)?; + let evidence = std::str::from_utf8(evidence.as_bytes()) + .map_err(|_| G2pError::Unavailable)? + .to_owned(); + Ok(PreparedG2pRegistryAction { + action: action.to_owned(), + key: key.as_str().to_owned(), + inputs, + evidence, + }) + } + + async fn invoke( + &self, + binding: &G2pRegistryBinding, + report: bool, + prepared: &PreparedG2pRegistryAction, + ) -> Result<(), G2pError> { + let client = self.client(binding)?; + let (action, profile) = selected(binding, report); + if prepared.action != action { + return Err(G2pError::RecoveryHeld); + } + let metadata = client + .registry_contract(Some(profile)) + .await + .map_err(|_| G2pError::Unavailable)? + .value; + let selected = metadata + .select_action(action, profile) + .map_err(|_| G2pError::RecoveryHeld)?; + let key = BRegIdempotencyKey::parse(&prepared.key).map_err(|_| G2pError::RecoveryHeld)?; + let saved = BRegPreparedAction::from_slice(prepared.evidence.as_bytes()) + .map_err(|_| G2pError::RecoveryHeld)?; + let request = client + .recover_action(&selected, &saved, &prepared.inputs, &key) + .map_err(|_| G2pError::RecoveryHeld)?; + client + .invoke_action(&selected, &request, &key) + .await + .map_err(|_| G2pError::OutcomeUnknown)?; + Ok(()) + } +} + +#[async_trait] +impl G2pRegistryPort for BregG2pBridge { + async fn read_instruction( + &self, + binding: &G2pRegistryBinding, + record_id: Uuid, + ) -> Result { + let client = self.client(binding)?; + let options = BRegRecordOptions::default() + .access_profile(&binding.read_profile) + .map_err(|_| G2pError::Unavailable)?; + let response = client + .get_record(&binding.record_route, &record_id.to_string(), &options) + .await + .map_err(|_| G2pError::Unavailable)? + .value; + if response.meta.record_type_identifier != binding.record_type + || response.data.record_identifier != record_id.to_string() + { + return Err(G2pError::Unavailable); + } + G2pInstructionView::decode(record_id, response.data.domain_data) + } + + async fn prepare_bind( + &self, + binding: &G2pRegistryBinding, + key: &str, + inputs: Map, + ) -> Result { + self.prepare(binding, false, key, inputs).await + } + + async fn invoke_bind( + &self, + binding: &G2pRegistryBinding, + prepared: &PreparedG2pRegistryAction, + ) -> Result<(), G2pError> { + self.invoke(binding, false, prepared).await + } + + async fn prepare_confirmation( + &self, + binding: &G2pRegistryBinding, + key: &str, + inputs: Map, + ) -> Result { + self.prepare(binding, true, key, inputs).await + } + + async fn invoke_confirmation( + &self, + binding: &G2pRegistryBinding, + prepared: &PreparedG2pRegistryAction, + ) -> Result<(), G2pError> { + self.invoke(binding, true, prepared).await + } +} + +fn selected(binding: &G2pRegistryBinding, report: bool) -> (&str, &str) { + if report { + (&binding.report_action, &binding.report_profile) + } else { + (&binding.bind_action, &binding.bind_profile) + } +} + +fn object(value: Value) -> Result, G2pError> { + value.as_object().cloned().ok_or(G2pError::Unavailable) +} diff --git a/crates/registry-adapter/src/payments/g2p_service.rs b/crates/registry-adapter/src/payments/g2p_service.rs new file mode 100644 index 0000000000..3d56fb5388 --- /dev/null +++ b/crates/registry-adapter/src/payments/g2p_service.rs @@ -0,0 +1,786 @@ +// SPDX-License-Identifier: Apache-2.0 +//! G2P custody orchestration for the HTTP and Coordinator-facing operations. + +use super::{ + g2p_model::{ + canonical_digest, G2pAttempt, G2pAttemptState, G2pConnectionSnapshot, G2pError, + G2pHttpAuth, G2pProviderBinding, + }, + g2p_registry::{bind_inputs_for, confirmation_inputs, G2pInstructionState, G2pRegistryPort}, + g2p_store::{DispatchAuthorization, G2pStore}, + pack::ProviderPackPin, + provider_mapping::{ + MappedProviderResponse, PaymentEndpointRole, PaymentMappingError, PaymentMappingRegistry, + PreparedProviderRequest, ProviderAcceptance, ProviderHttpResponse, + }, +}; +use async_trait::async_trait; +use registry_platform_config::SecretResolver; +use registry_platform_httputil::client::BearerToken; +use registry_platform_httputil::{read_bounded, validate_response_headers, ServiceBaseUrl}; +use serde::Serialize; +use serde_json::Value; +use std::{future::Future, pin::Pin, sync::Arc, time::Duration}; +use uuid::Uuid; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum G2pProviderError { + /// The provider definitely refused this exact mutation. Custody still + /// holds the first-send mark and never creates a replacement attempt. + Rejected, + /// The mutation may have reached the provider. + OutcomeUnknown, + /// A read-only provider operation could not complete. + Unavailable, +} + +/// Fully built mutation held in memory between local preflight and the one +/// durable dispatch grant. Polling this future performs the first network I/O; +/// no credential, URL, header or request construction remains afterward. +pub struct PreparedG2pSend { + send: Pin> + Send>>, +} + +impl PreparedG2pSend { + pub fn new( + send: impl Future> + Send + 'static, + ) -> Self { + Self { + send: Box::pin(send), + } + } + + pub async fn send(self) -> Result { + self.send.await + } +} + +/// Provider seam used by custody. Recovery is read-only and keyed by the +/// retained correlation; it must never submit or replay the batch command. +#[async_trait] +pub trait G2pProviderPort: Send + Sync { + async fn preflight_submit( + &self, + binding: &G2pProviderBinding, + request: &PreparedProviderRequest, + ) -> Result; + + async fn recover_acceptance( + &self, + binding: &G2pProviderBinding, + request: &PreparedProviderRequest, + ) -> Result, G2pProviderError>; + + async fn observe( + &self, + binding: &G2pProviderBinding, + request: &PreparedProviderRequest, + ) -> Result; +} + +pub trait G2pMappingPort: Send + Sync { + fn ensure_available(&self, pin: &ProviderPackPin) -> Result<(), PaymentMappingError>; + fn prepare( + &self, + pin: &ProviderPackPin, + role: PaymentEndpointRole, + intent: &Value, + settings: &Value, + acceptance: Option<&ProviderAcceptance>, + ) -> Result; + fn interpret( + &self, + pin: &ProviderPackPin, + role: PaymentEndpointRole, + intent: &Value, + settings: &Value, + acceptance: Option<&ProviderAcceptance>, + response: &ProviderHttpResponse, + ) -> Result; +} + +impl G2pMappingPort for PaymentMappingRegistry { + fn ensure_available(&self, pin: &ProviderPackPin) -> Result<(), PaymentMappingError> { + self.select(pin).map(|_| ()) + } + + fn prepare( + &self, + pin: &ProviderPackPin, + role: PaymentEndpointRole, + intent: &Value, + settings: &Value, + acceptance: Option<&ProviderAcceptance>, + ) -> Result { + self.select(pin)? + .prepare(role, intent, settings, acceptance) + } + + fn interpret( + &self, + pin: &ProviderPackPin, + role: PaymentEndpointRole, + intent: &Value, + settings: &Value, + acceptance: Option<&ProviderAcceptance>, + response: &ProviderHttpResponse, + ) -> Result { + self.select(pin)? + .interpret(role, intent, settings, acceptance, response) + } +} + +/// Provider-neutral HTTP host. Bearer requests send only the exact retained +/// request plan. The Mifos legacy signature remains fail closed until its +/// signer and response verifier are integrated into this boundary. +pub struct HttpG2pProvider { + resolver: Arc, +} + +impl HttpG2pProvider { + pub fn new(resolver: Arc) -> Self { + Self { resolver } + } + + fn bearer_token(&self, binding: &G2pProviderBinding) -> Result { + let secret = self + .resolver + .resolve(binding.credential_ref().as_str()) + .map_err(|_| G2pProviderError::Unavailable)?; + let token = std::str::from_utf8(secret.expose_secret()) + .map_err(|_| G2pProviderError::Unavailable)?; + match binding.auth() { + G2pHttpAuth::Bearer => { + BearerToken::new(token.to_owned()).map_err(|_| G2pProviderError::Unavailable) + } + G2pHttpAuth::MifosLegacySignature { .. } => Err(G2pProviderError::Unavailable), + } + } + + fn prepare_url( + binding: &G2pProviderBinding, + request: &PreparedProviderRequest, + ) -> Result { + request + .validate_restored(request.role, &request.provider_pack) + .map_err(|_| G2pProviderError::Unavailable)?; + let base = ServiceBaseUrl::new( + url::Url::parse( + binding + .base_url(request.role) + .map_err(|_| G2pProviderError::Unavailable)?, + ) + .map_err(|_| G2pProviderError::Unavailable)?, + ) + .map_err(|_| G2pProviderError::Unavailable)?; + let path = request + .path + .strip_prefix('/') + .ok_or(G2pProviderError::Unavailable)?; + let mut url = base.join(path).map_err(|_| G2pProviderError::Unavailable)?; + url.query_pairs_mut().extend_pairs(&request.query); + Ok(url) + } + + async fn send_prepared( + &self, + binding: &G2pProviderBinding, + prepared: &PreparedProviderRequest, + ) -> Result { + binding + .validate() + .map_err(|_| G2pProviderError::Unavailable)?; + let url = Self::prepare_url(binding, prepared)?; + let token = self.bearer_token(binding)?; + let client = registry_platform_httputil::client::build_client( + registry_platform_httputil::client::OutboundOptions { + request_timeout: Duration::from_secs(15), + connect_timeout: Duration::from_secs(5), + user_agent: Some("registry-adapter-payment-http/v1"), + trusted_root_certificates: None, + }, + ) + .map_err(|_| G2pProviderError::Unavailable)?; + let mut request = match prepared.method { + super::provider_mapping::PaymentHttpMethod::Post => client.post(url), + super::provider_mapping::PaymentHttpMethod::Get => client.get(url), + }; + for (name, value) in &prepared.headers { + request = request.header(name, value); + } + request = request.header( + http::header::AUTHORIZATION, + token.authorization_header_value(), + ); + if let Some(body) = &prepared.body { + request = request + .header(http::header::CONTENT_TYPE, "application/json") + .body(body.clone()); + } + let mutation = prepared.role.is_submit(); + let response = request.send().await.map_err(|_| { + if mutation { + G2pProviderError::OutcomeUnknown + } else { + G2pProviderError::Unavailable + } + })?; + validate_response_headers(response.headers()).map_err(|_| { + if mutation { + G2pProviderError::OutcomeUnknown + } else { + G2pProviderError::Unavailable + } + })?; + let status = response.status().as_u16(); + let body = read_bounded(response, 131_072).await.map_err(|_| { + if mutation { + G2pProviderError::OutcomeUnknown + } else { + G2pProviderError::Unavailable + } + })?; + Ok(ProviderHttpResponse { status, body }) + } +} + +#[async_trait] +impl G2pProviderPort for HttpG2pProvider { + async fn preflight_submit( + &self, + binding: &G2pProviderBinding, + request: &PreparedProviderRequest, + ) -> Result { + binding + .validate() + .map_err(|_| G2pProviderError::Unavailable)?; + if request.role != PaymentEndpointRole::DisbursementSubmit { + return Err(G2pProviderError::Unavailable); + } + let url = Self::prepare_url(binding, request)?; + let token = self.bearer_token(binding)?; + let client = registry_platform_httputil::client::build_client( + registry_platform_httputil::client::OutboundOptions { + request_timeout: Duration::from_secs(15), + connect_timeout: Duration::from_secs(5), + user_agent: Some("registry-adapter-payment-http/v1"), + trusted_root_certificates: None, + }, + ) + .map_err(|_| G2pProviderError::Unavailable)?; + let mut builder = client.post(url); + for (name, value) in &request.headers { + builder = builder.header(name, value); + } + builder = builder.header( + http::header::AUTHORIZATION, + token.authorization_header_value(), + ); + let body = request.body.as_ref().ok_or(G2pProviderError::Unavailable)?; + let prepared = builder + .header(http::header::CONTENT_TYPE, "application/json") + .body(body.clone()) + .build() + .map_err(|_| G2pProviderError::Unavailable)?; + Ok(PreparedG2pSend::new(async move { + let response = client + .execute(prepared) + .await + .map_err(|_| G2pProviderError::OutcomeUnknown)?; + validate_response_headers(response.headers()) + .map_err(|_| G2pProviderError::OutcomeUnknown)?; + let status = response.status().as_u16(); + let body = read_bounded(response, 131_072) + .await + .map_err(|_| G2pProviderError::OutcomeUnknown)?; + Ok(ProviderHttpResponse { status, body }) + })) + } + + async fn recover_acceptance( + &self, + _binding: &G2pProviderBinding, + _request: &PreparedProviderRequest, + ) -> Result, G2pProviderError> { + Ok(None) + } + + async fn observe( + &self, + binding: &G2pProviderBinding, + request: &PreparedProviderRequest, + ) -> Result { + if request.role != PaymentEndpointRole::DisbursementStatus { + return Err(G2pProviderError::Unavailable); + } + self.send_prepared(binding, request).await + } +} + +pub struct G2pService { + store: G2pStore, + registry: Arc, + provider: Arc, + mapping: Option>, +} + +impl G2pService { + pub fn new( + store: G2pStore, + registry: Arc, + provider: Arc, + ) -> Self { + Self { + store, + registry, + provider, + mapping: None, + } + } + + pub fn with_mapping(mut self, mapping: Arc) -> Self { + self.mapping = Some(mapping); + self + } + + /// Strictly local read of a previous request's acceptance. An unresolved + /// first send has no receipt and cannot be sent again by this endpoint. + pub async fn request_receipt( + &self, + connection: &str, + principal: &str, + command_key: &str, + instruction_record_id: Uuid, + instruction_version: u64, + ) -> Result { + let digest = request_digest(instruction_record_id, instruction_version)?; + let saved = self + .store + .lookup_command(connection, principal, command_key, &digest) + .await? + .ok_or(G2pError::NotFound)?; + if saved.provider_acceptance.is_none() { + return Err(G2pError::RecoveryHeld); + } + Ok(saved) + } + + /// Implements `RequestDisbursement`. The caller supplies only the BReg + /// record identity/version and its workflow command key. All payment facts + /// come from the exact authoritative record. + #[allow(clippy::too_many_arguments)] + pub async fn request_disbursement( + &self, + connection: &str, + principal: &str, + command_key: &str, + instruction_record_id: Uuid, + instruction_version: u64, + binding: G2pConnectionSnapshot, + now_unix_seconds: i64, + ) -> Result { + if connection.is_empty() + || principal.is_empty() + || command_key.is_empty() + || instruction_record_id.is_nil() + || instruction_version == 0 + { + return Err(G2pError::InvalidRequest); + } + binding.validate()?; + let source_namespace = binding.registry.source_namespace()?; + let request_digest = request_digest(instruction_record_id, instruction_version)?; + if let Some(saved) = self + .store + .find_instruction( + principal, + &source_namespace, + instruction_record_id, + instruction_version, + ) + .await? + { + if saved.connection != connection { + return Err(G2pError::Conflict); + } + self.store + .claim_existing_command(&saved, command_key, &request_digest) + .await?; + return self + .resume_request(saved, connection, principal, now_unix_seconds) + .await; + } + + let view = self + .registry + .read_instruction(&binding.registry, instruction_record_id) + .await?; + if view.instruction.instruction_version != instruction_version + || view.state != G2pInstructionState::InstructionReady + { + return Err(G2pError::Conflict); + } + binding.validate_instruction(&view.instruction)?; + + let mapping = self.mapping.as_ref().ok_or(G2pError::Unavailable)?; + mapping + .ensure_available(&binding.provider_pack) + .map_err(mapping_read_error)?; + let provider_intent = binding.provider_intent(&view.instruction)?; + let intent = serde_json::to_value(&provider_intent).map_err(|_| G2pError::Unavailable)?; + let prepared_submit = mapping + .prepare( + &binding.provider_pack, + PaymentEndpointRole::DisbursementSubmit, + &intent, + binding.provider.settings(), + None, + ) + .map_err(mapping_read_error)?; + let id = Uuid::new_v4(); + let binding_revision = binding.attempt_revision(&prepared_submit)?; + let bind_key = format!("g2p-bind-{id}"); + let inputs = bind_inputs_for(&view.instruction, id, &binding_revision)?; + let prepared = self + .registry + .prepare_bind(&binding.registry, &bind_key, inputs) + .await?; + let candidate = G2pAttempt::new( + id, + connection.to_owned(), + principal.to_owned(), + view.instruction, + binding, + prepared_submit, + prepared, + )?; + let saved = self + .store + .reserve(&candidate, command_key, &request_digest) + .await?; + self.resume_request(saved, connection, principal, now_unix_seconds) + .await + } + + /// Implements `DisbursementStatus`. It may perform provider reads and + /// retain their exact result, but never binds or dispatches. + pub async fn disbursement_status( + &self, + connection: &str, + principal: &str, + id: Uuid, + ) -> Result { + let mut attempt = self.store.get_scoped(connection, principal, id).await?; + if attempt.state == G2pAttemptState::DispatchStarted { + let recovered = self + .provider + .recover_acceptance(&attempt.binding.provider, &attempt.prepared_submit) + .await + .map_err(provider_read_error)?; + let Some(accepted) = recovered else { + return Ok(attempt); + }; + attempt = self + .store + .record_acceptance(connection, principal, id, accepted) + .await?; + } + if matches!( + attempt.state, + G2pAttemptState::ProviderAccepted + | G2pAttemptState::ProviderPending + | G2pAttemptState::ProviderUnknown + ) { + let accepted = attempt + .provider_acceptance + .as_ref() + .ok_or(G2pError::RecoveryHeld)?; + let mapping = self.mapping.as_ref().ok_or(G2pError::Unavailable)?; + mapping + .ensure_available(&attempt.binding.provider_pack) + .map_err(mapping_read_error)?; + let intent = serde_json::to_value(&attempt.provider_intent) + .map_err(|_| G2pError::Unavailable)?; + let status_request = mapping + .prepare( + &attempt.binding.provider_pack, + PaymentEndpointRole::DisbursementStatus, + &intent, + attempt.binding.provider.settings(), + Some(accepted), + ) + .map_err(mapping_read_error)?; + let response = self + .provider + .observe(&attempt.binding.provider, &status_request) + .await + .map_err(provider_read_error)?; + let mapped = mapping + .interpret( + &attempt.binding.provider_pack, + PaymentEndpointRole::DisbursementStatus, + &intent, + attempt.binding.provider.settings(), + Some(accepted), + &response, + ) + .map_err(mapping_read_error)?; + let MappedProviderResponse::Observation(observation) = mapped else { + return Err(G2pError::Unavailable); + }; + let observation = attempt.validate_mapped_observation(accepted, &observation)?; + attempt = self + .store + .record_observation(connection, principal, id, observation) + .await?; + } + Ok(attempt) + } + + /// Implements `RecordProviderConfirmation`. Only an exact correlated + /// `COMPLETED` observation can reach the BReg reporting Action. + pub async fn record_provider_confirmation( + &self, + connection: &str, + principal: &str, + command_key: &str, + id: Uuid, + ) -> Result { + if command_key.is_empty() { + return Err(G2pError::InvalidRequest); + } + let request_digest = confirmation_request_digest(connection, principal, id)?; + self.store + .claim_confirmation_command(connection, principal, id, command_key, &request_digest) + .await?; + let mut attempt = self.disbursement_status(connection, principal, id).await?; + if attempt.state == G2pAttemptState::ConfirmationRecorded { + return Ok(attempt); + } + if attempt.state == G2pAttemptState::ProviderConfirmed { + let key = format!("g2p-confirm-{id}"); + let inputs = confirmation_inputs(&attempt)?; + let prepared = self + .registry + .prepare_confirmation(&attempt.binding.registry, &key, inputs) + .await?; + attempt = self + .store + .prepare_confirmation(connection, principal, id, prepared) + .await?; + } + if attempt.state != G2pAttemptState::ConfirmationPrepared { + return Err(G2pError::RecoveryHeld); + } + let prepared = attempt + .confirmation_action + .as_ref() + .ok_or(G2pError::RecoveryHeld)?; + let invocation = self + .registry + .invoke_confirmation(&attempt.binding.registry, prepared) + .await; + let view = self + .registry + .read_instruction(&attempt.binding.registry, attempt.instruction.record_id) + .await?; + if !view.matches_confirmation(&attempt) { + return match invocation { + Err(error) => Err(error), + Ok(()) => Err(G2pError::Conflict), + }; + } + self.store + .record_confirmation(connection, principal, id) + .await + } + + async fn resume_request( + &self, + mut attempt: G2pAttempt, + connection: &str, + principal: &str, + now_unix_seconds: i64, + ) -> Result { + if attempt.state == G2pAttemptState::BindPrepared { + let invocation = self + .registry + .invoke_bind(&attempt.binding.registry, &attempt.bind_action) + .await; + let view = self + .registry + .read_instruction(&attempt.binding.registry, attempt.instruction.record_id) + .await?; + if !view.matches_bound(&attempt) { + return match invocation { + Err(error) => Err(error), + Ok(()) => Err(G2pError::Conflict), + }; + } + attempt = self + .store + .record_bound(connection, principal, attempt.id) + .await?; + } + let prepared_send = if attempt.state == G2pAttemptState::Bound { + self.mapping + .as_ref() + .ok_or(G2pError::Unavailable)? + .ensure_available(&attempt.binding.provider_pack) + .map_err(mapping_read_error)?; + Some( + self.provider + .preflight_submit(&attempt.binding.provider, &attempt.prepared_submit) + .await + .map_err(provider_read_error)?, + ) + } else { + None + }; + match self + .store + .begin_dispatch(connection, principal, attempt.id, now_unix_seconds) + .await? + { + DispatchAuthorization::Send(started) => { + let response = prepared_send + .ok_or(G2pError::OutcomeUnknown)? + .send() + .await + .map_err(provider_mutation_error)?; + let mapping = self.mapping.as_ref().ok_or(G2pError::OutcomeUnknown)?; + let intent = serde_json::to_value(&started.provider_intent) + .map_err(|_| G2pError::OutcomeUnknown)?; + let mapped = mapping + .interpret( + &started.binding.provider_pack, + PaymentEndpointRole::DisbursementSubmit, + &intent, + started.binding.provider.settings(), + None, + &response, + ) + .map_err(|_| G2pError::OutcomeUnknown)?; + let MappedProviderResponse::Acceptance(accepted) = mapped else { + return Err(G2pError::OutcomeUnknown); + }; + started + .validate_acceptance(&accepted) + .map_err(|_| G2pError::OutcomeUnknown)?; + self.store + .record_acceptance(connection, principal, started.id, accepted) + .await + } + DispatchAuthorization::Hold(held) => { + if held.state != G2pAttemptState::DispatchStarted { + return Ok(held); + } + let recovered = self + .provider + .recover_acceptance(&held.binding.provider, &held.prepared_submit) + .await + .map_err(provider_read_error)?; + match recovered { + Some(accepted) => { + self.store + .record_acceptance(connection, principal, held.id, accepted) + .await + } + None => Ok(held), + } + } + } + } +} + +#[derive(Serialize)] +#[serde(rename_all = "camelCase")] +struct RequestIdentity { + domain: &'static str, + instruction_record_id: Uuid, + instruction_version: u64, +} + +#[derive(Serialize)] +#[serde(rename_all = "camelCase")] +struct ConfirmationRequestIdentity<'a> { + domain: &'static str, + operation: &'static str, + connection: &'a str, + principal: &'a str, + disbursement_id: Uuid, +} + +fn request_digest(record_id: Uuid, version: u64) -> Result { + canonical_digest(&RequestIdentity { + domain: "registry-adapter/g2p-request/v1", + instruction_record_id: record_id, + instruction_version: version, + }) +} + +fn confirmation_request_digest( + connection: &str, + principal: &str, + disbursement_id: Uuid, +) -> Result { + if connection.is_empty() || principal.is_empty() || disbursement_id.is_nil() { + return Err(G2pError::InvalidRequest); + } + canonical_digest(&ConfirmationRequestIdentity { + domain: "registry-adapter/g2p-command/v1", + operation: "record-provider-confirmation", + connection, + principal, + disbursement_id, + }) +} + +fn provider_mutation_error(error: G2pProviderError) -> G2pError { + match error { + G2pProviderError::Rejected => G2pError::Conflict, + G2pProviderError::OutcomeUnknown | G2pProviderError::Unavailable => { + G2pError::OutcomeUnknown + } + } +} + +fn provider_read_error(error: G2pProviderError) -> G2pError { + match error { + G2pProviderError::Rejected => G2pError::Conflict, + G2pProviderError::OutcomeUnknown | G2pProviderError::Unavailable => G2pError::Unavailable, + } +} + +fn mapping_read_error(_error: PaymentMappingError) -> G2pError { + G2pError::Unavailable +} + +#[cfg(test)] +mod tests { + use super::confirmation_request_digest; + use uuid::Uuid; + + #[test] + fn confirmation_request_digest_binds_scope_and_disbursement() { + let first = Uuid::parse_str("00000000-0000-4000-8000-000000000201").unwrap(); + let second = Uuid::parse_str("00000000-0000-4000-8000-000000000202").unwrap(); + let digest = confirmation_request_digest("g2p", "coordinator", first).unwrap(); + assert_eq!( + digest, + confirmation_request_digest("g2p", "coordinator", first).unwrap() + ); + assert_ne!( + digest, + confirmation_request_digest("g2p-renamed", "coordinator", first).unwrap() + ); + assert_ne!( + digest, + confirmation_request_digest("g2p", "another-principal", first).unwrap() + ); + assert_ne!( + digest, + confirmation_request_digest("g2p", "coordinator", second).unwrap() + ); + } +} diff --git a/crates/registry-adapter/src/payments/g2p_store.rs b/crates/registry-adapter/src/payments/g2p_store.rs new file mode 100644 index 0000000000..96726c214d --- /dev/null +++ b/crates/registry-adapter/src/payments/g2p_store.rs @@ -0,0 +1,652 @@ +// SPDX-License-Identifier: Apache-2.0 +//! PostgreSQL custody for one-send G2P attempts. + +use super::g2p_model::{ + canonical_digest, G2pAttempt, G2pAttemptState, G2pError, G2pObservationState, + G2pProviderObservation, PreparedG2pRegistryAction, +}; +use super::provider_mapping::ProviderAcceptance; +use deadpool_postgres::{GenericClient, Pool, Transaction}; +use uuid::Uuid; + +const SCHEMA: &str = r#" +CREATE TABLE IF NOT EXISTS adapter_g2p_attempts ( + id uuid PRIMARY KEY, + deployment text NOT NULL, + connection text NOT NULL, + principal text NOT NULL, + source_namespace text NOT NULL, + instruction_record_id uuid NOT NULL, + instruction_id uuid NOT NULL, + instruction_version bigint NOT NULL CHECK (instruction_version > 0), + state text NOT NULL, + document jsonb NOT NULL CHECK (jsonb_typeof(document) = 'object'), + updated_at timestamptz NOT NULL DEFAULT clock_timestamp(), + UNIQUE (deployment, source_namespace, instruction_record_id, instruction_version), + UNIQUE (deployment, source_namespace, instruction_id, instruction_version) +); +CREATE TABLE IF NOT EXISTS adapter_g2p_commands ( + deployment text NOT NULL, + connection text NOT NULL, + principal text NOT NULL, + command_key text NOT NULL, + request_digest text NOT NULL, + attempt_id uuid NOT NULL, + PRIMARY KEY (deployment, connection, principal, command_key) +); +CREATE TABLE IF NOT EXISTS adapter_g2p_events ( + sequence bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, + deployment text NOT NULL, + attempt_id uuid NOT NULL, + principal text NOT NULL, + kind text NOT NULL, + created_at timestamptz NOT NULL DEFAULT clock_timestamp() +); +"#; + +pub async fn migrate_g2p(client: &mut tokio_postgres::Client) -> Result<(), G2pError> { + let tx = client + .transaction() + .await + .map_err(|_| G2pError::Unavailable)?; + tx.execute("SELECT pg_advisory_xact_lock(1879751387, 2)", &[]) + .await + .map_err(|_| G2pError::Unavailable)?; + tx.batch_execute(SCHEMA) + .await + .map_err(|_| G2pError::Unavailable)?; + tx.commit().await.map_err(|_| G2pError::Unavailable) +} + +#[derive(Clone)] +pub struct G2pStore { + pool: Pool, + deployment: String, +} + +#[derive(Clone)] +pub enum DispatchAuthorization { + /// This transaction durably recorded the first-send intent. The caller may + /// perform exactly one provider mutation with the returned command. + Send(G2pAttempt), + /// A send was already attempted or the attempt advanced. Only provider + /// reads and exact retained-state recovery are permitted. + Hold(G2pAttempt), +} + +impl G2pStore { + pub fn new(pool: Pool, deployment: String) -> Self { + Self { pool, deployment } + } + + /// Resolve only the exact previously admitted workflow command. This read + /// never creates an attempt or authorizes another provider submission. + pub async fn lookup_command( + &self, + connection: &str, + principal: &str, + command_key: &str, + request_digest: &str, + ) -> Result, G2pError> { + let client = self.pool.get().await.map_err(|_| G2pError::Unavailable)?; + let row = client + .query_opt( + "SELECT a.document,c.request_digest FROM adapter_g2p_commands c JOIN adapter_g2p_attempts a ON a.id=c.attempt_id AND a.deployment=c.deployment WHERE c.deployment=$1 AND c.connection=$2 AND c.principal=$3 AND c.command_key=$4", + &[&self.deployment, &connection, &principal, &command_key], + ) + .await + .map_err(|_| G2pError::Unavailable)?; + let Some(row) = row else { return Ok(None) }; + if row.get::<_, String>(1) != request_digest { + return Err(G2pError::Conflict); + } + decode(row.get(0)).map(Some) + } + + pub async fn check_privileges(&self) -> Result<(), G2pError> { + let client = self.pool.get().await.map_err(|_| G2pError::Unavailable)?; + for (table, privileges) in [ + ("adapter_g2p_attempts", &["SELECT", "INSERT", "UPDATE"][..]), + ("adapter_g2p_commands", &["SELECT", "INSERT"][..]), + ("adapter_g2p_events", &["SELECT", "INSERT"][..]), + ] { + if !crate::journal::missing_table_privileges(&client, table, privileges) + .await + .map_err(|_| G2pError::Unavailable)? + .is_empty() + { + return Err(G2pError::Unavailable); + } + } + let row = client + .query_one( + "SELECT has_sequence_privilege(current_user, $1, 'USAGE')", + &[&"adapter_g2p_events_sequence_seq"], + ) + .await + .map_err(|_| G2pError::Unavailable)?; + if !row.get::<_, bool>(0) { + return Err(G2pError::Unavailable); + } + Ok(()) + } + + /// Reserve one attempt and its workflow command atomically. Both the BReg + /// record identity and the immutable source instruction identity are + /// unique across all command keys for the same authoritative source. + pub async fn reserve( + &self, + candidate: &G2pAttempt, + command_key: &str, + request_digest: &str, + ) -> Result { + candidate.validate_integrity()?; + if candidate.state != G2pAttemptState::BindPrepared { + return Err(G2pError::InvalidRequest); + } + let version = i64::try_from(candidate.instruction.instruction_version) + .map_err(|_| G2pError::InvalidRequest)?; + let document = serde_json::to_value(candidate).map_err(|_| G2pError::Unavailable)?; + let mut client = self.pool.get().await.map_err(|_| G2pError::Unavailable)?; + let tx = client + .transaction() + .await + .map_err(|_| G2pError::Unavailable)?; + let inserted = tx + .execute( + "INSERT INTO adapter_g2p_attempts (id,deployment,connection,principal,source_namespace,instruction_record_id,instruction_id,instruction_version,state,document) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10) ON CONFLICT DO NOTHING", + &[ + &candidate.id, + &self.deployment, + &candidate.connection, + &candidate.principal, + &candidate.source_namespace, + &candidate.instruction.record_id, + &candidate.instruction.instruction_id, + &version, + &state_name(candidate.state), + &document, + ], + ) + .await + .map_err(|_| G2pError::Unavailable)?; + let row = tx + .query_opt( + "SELECT document,source_namespace FROM adapter_g2p_attempts WHERE deployment=$1 AND source_namespace=$2 AND instruction_version=$3 AND (instruction_record_id=$4 OR instruction_id=$5) FOR UPDATE", + &[ + &self.deployment, + &candidate.source_namespace, + &version, + &candidate.instruction.record_id, + &candidate.instruction.instruction_id, + ], + ) + .await + .map_err(|_| G2pError::Unavailable)? + .ok_or(G2pError::Conflict)?; + let saved = decode(row.get(0))?; + if row.get::<_, String>(1) != saved.source_namespace + || saved.connection != candidate.connection + || saved.principal != candidate.principal + || saved.source_namespace != candidate.source_namespace + || saved.instruction.record_id != candidate.instruction.record_id + || saved.instruction.instruction_id != candidate.instruction.instruction_id + { + return Err(G2pError::Conflict); + } + claim_command( + &tx, + &self.deployment, + &saved.connection, + &saved.principal, + command_key, + request_digest, + saved.id, + ) + .await?; + if inserted == 1 { + event(&tx, &self.deployment, &saved, "g2p.attempt-reserved").await?; + } + tx.commit().await.map_err(|_| G2pError::Unavailable)?; + Ok(saved) + } + + pub async fn find_instruction( + &self, + principal: &str, + source_namespace: &str, + record_id: Uuid, + version: u64, + ) -> Result, G2pError> { + let version = i64::try_from(version).map_err(|_| G2pError::InvalidRequest)?; + let client = self.pool.get().await.map_err(|_| G2pError::Unavailable)?; + let row = client + .query_opt( + "SELECT document,source_namespace FROM adapter_g2p_attempts WHERE deployment=$1 AND principal=$2 AND source_namespace=$3 AND instruction_record_id=$4 AND instruction_version=$5", + &[&self.deployment, &principal, &source_namespace, &record_id, &version], + ) + .await + .map_err(|_| G2pError::Unavailable)?; + row.map(|row| { + let attempt = decode(row.get(0))?; + if row.get::<_, String>(1) != attempt.source_namespace { + return Err(G2pError::Unavailable); + } + Ok(attempt) + }) + .transpose() + } + + /// Bind an additional workflow command key to an already retained + /// instruction attempt. A reused key with a different request remains a + /// conflict; this method never creates or advances an attempt. + pub async fn claim_existing_command( + &self, + attempt: &G2pAttempt, + command_key: &str, + request_digest: &str, + ) -> Result<(), G2pError> { + attempt.validate_integrity()?; + let mut client = self.pool.get().await.map_err(|_| G2pError::Unavailable)?; + let tx = client + .transaction() + .await + .map_err(|_| G2pError::Unavailable)?; + let retained = locked( + &tx, + &self.deployment, + &attempt.connection, + &attempt.principal, + attempt.id, + ) + .await?; + if retained.instruction != attempt.instruction { + return Err(G2pError::Conflict); + } + claim_command( + &tx, + &self.deployment, + &attempt.connection, + &attempt.principal, + command_key, + request_digest, + attempt.id, + ) + .await?; + tx.commit().await.map_err(|_| G2pError::Unavailable) + } + + /// Bind the caller's confirmation command before any BReg reporting + /// effect. The command table's scope and digest comparison make an exact + /// retry resumable while refusing reuse for another operation or attempt. + pub async fn claim_confirmation_command( + &self, + connection: &str, + principal: &str, + id: Uuid, + command_key: &str, + request_digest: &str, + ) -> Result { + if command_key.is_empty() || request_digest.is_empty() { + return Err(G2pError::InvalidRequest); + } + let mut client = self.pool.get().await.map_err(|_| G2pError::Unavailable)?; + let tx = client + .transaction() + .await + .map_err(|_| G2pError::Unavailable)?; + let attempt = locked(&tx, &self.deployment, connection, principal, id).await?; + claim_command( + &tx, + &self.deployment, + connection, + principal, + command_key, + request_digest, + id, + ) + .await?; + tx.commit().await.map_err(|_| G2pError::Unavailable)?; + Ok(attempt) + } + + pub async fn get_scoped( + &self, + connection: &str, + principal: &str, + id: Uuid, + ) -> Result { + let client = self.pool.get().await.map_err(|_| G2pError::Unavailable)?; + let row = client + .query_opt( + "SELECT document FROM adapter_g2p_attempts WHERE deployment=$1 AND connection=$2 AND principal=$3 AND id=$4", + &[&self.deployment, &connection, &principal, &id], + ) + .await + .map_err(|_| G2pError::Unavailable)? + .ok_or(G2pError::NotFound)?; + decode(row.get(0)) + } + + pub async fn record_bound( + &self, + connection: &str, + principal: &str, + id: Uuid, + ) -> Result { + self.transition( + connection, + principal, + id, + "g2p.instruction-bound", + |attempt| { + if attempt.state != G2pAttemptState::BindPrepared { + return Err(G2pError::Conflict); + } + attempt.state = G2pAttemptState::Bound; + Ok(()) + }, + ) + .await + } + + /// Atomically grants the only provider mutation authorization this + /// attempt can ever produce. All later calls return `Hold`. + pub async fn begin_dispatch( + &self, + connection: &str, + principal: &str, + id: Uuid, + now_unix_seconds: i64, + ) -> Result { + if now_unix_seconds <= 0 { + return Err(G2pError::InvalidRequest); + } + let mut client = self.pool.get().await.map_err(|_| G2pError::Unavailable)?; + let tx = client + .transaction() + .await + .map_err(|_| G2pError::Unavailable)?; + let mut attempt = locked(&tx, &self.deployment, connection, principal, id).await?; + if attempt.state != G2pAttemptState::Bound { + tx.commit().await.map_err(|_| G2pError::Unavailable)?; + return Ok(DispatchAuthorization::Hold(attempt)); + } + attempt.first_send_at_unix_seconds = Some(now_unix_seconds); + attempt.state = G2pAttemptState::DispatchStarted; + persist(&tx, &self.deployment, &attempt, "g2p.dispatch-started").await?; + tx.commit().await.map_err(|_| G2pError::Unavailable)?; + Ok(DispatchAuthorization::Send(attempt)) + } + + pub async fn record_acceptance( + &self, + connection: &str, + principal: &str, + id: Uuid, + accepted: ProviderAcceptance, + ) -> Result { + self.transition( + connection, + principal, + id, + "g2p.provider-accepted", + |attempt| { + attempt.validate_acceptance(&accepted)?; + if attempt.state == G2pAttemptState::ProviderAccepted + && attempt.provider_acceptance.as_ref() == Some(&accepted) + { + return Ok(()); + } + if attempt.state != G2pAttemptState::DispatchStarted { + return Err(G2pError::Conflict); + } + attempt.provider_acceptance = Some(accepted); + attempt.state = G2pAttemptState::ProviderAccepted; + Ok(()) + }, + ) + .await + } + + /// Retain an exact, correlated provider read. `Unknown` is represented as + /// its own held state and is never converted into `Failed` by custody. + pub async fn record_observation( + &self, + connection: &str, + principal: &str, + id: Uuid, + observation: G2pProviderObservation, + ) -> Result { + self.transition( + connection, + principal, + id, + "g2p.provider-observed", + |attempt| { + let accepted = attempt + .provider_acceptance + .as_ref() + .ok_or(G2pError::RecoveryHeld)?; + attempt.validate_observation(accepted, &observation)?; + if matches!( + attempt.state, + G2pAttemptState::ProviderConfirmed + | G2pAttemptState::ProviderFailed + | G2pAttemptState::ConfirmationPrepared + | G2pAttemptState::ConfirmationRecorded + ) { + if attempt.provider_observation.as_ref() == Some(&observation) { + return Ok(()); + } + return Err(G2pError::Conflict); + } + if !matches!( + attempt.state, + G2pAttemptState::ProviderAccepted + | G2pAttemptState::ProviderPending + | G2pAttemptState::ProviderUnknown + ) { + return Err(G2pError::RecoveryHeld); + } + let digest = canonical_digest(&observation)?; + attempt.state = match observation.state { + G2pObservationState::Pending => G2pAttemptState::ProviderPending, + G2pObservationState::ProviderConfirmed => G2pAttemptState::ProviderConfirmed, + G2pObservationState::ProviderRejected => G2pAttemptState::ProviderFailed, + }; + attempt.provider_observation = Some(observation); + attempt.provider_result_digest = Some(digest); + Ok(()) + }, + ) + .await + } + + pub async fn prepare_confirmation( + &self, + connection: &str, + principal: &str, + id: Uuid, + action: PreparedG2pRegistryAction, + ) -> Result { + self.transition( + connection, + principal, + id, + "g2p.confirmation-prepared", + |attempt| { + if attempt.state == G2pAttemptState::ConfirmationPrepared + && attempt.confirmation_action.as_ref() == Some(&action) + { + return Ok(()); + } + if attempt.state != G2pAttemptState::ProviderConfirmed + || action.action != attempt.binding.registry.report_action + { + return Err(G2pError::Conflict); + } + attempt.confirmation_action = Some(action); + attempt.state = G2pAttemptState::ConfirmationPrepared; + Ok(()) + }, + ) + .await + } + + pub async fn record_confirmation( + &self, + connection: &str, + principal: &str, + id: Uuid, + ) -> Result { + self.transition( + connection, + principal, + id, + "g2p.confirmation-recorded", + |attempt| { + if attempt.state == G2pAttemptState::ConfirmationRecorded { + return Ok(()); + } + if attempt.state != G2pAttemptState::ConfirmationPrepared { + return Err(G2pError::Conflict); + } + attempt.state = G2pAttemptState::ConfirmationRecorded; + Ok(()) + }, + ) + .await + } + + async fn transition( + &self, + connection: &str, + principal: &str, + id: Uuid, + event_kind: &str, + update: impl FnOnce(&mut G2pAttempt) -> Result<(), G2pError>, + ) -> Result { + let mut client = self.pool.get().await.map_err(|_| G2pError::Unavailable)?; + let tx = client + .transaction() + .await + .map_err(|_| G2pError::Unavailable)?; + let mut attempt = locked(&tx, &self.deployment, connection, principal, id).await?; + let before = serde_json::to_value(&attempt).map_err(|_| G2pError::Unavailable)?; + update(&mut attempt)?; + attempt.validate_integrity()?; + let after = serde_json::to_value(&attempt).map_err(|_| G2pError::Unavailable)?; + if before != after { + persist(&tx, &self.deployment, &attempt, event_kind).await?; + } + tx.commit().await.map_err(|_| G2pError::Unavailable)?; + Ok(attempt) + } +} + +async fn locked( + tx: &Transaction<'_>, + deployment: &str, + connection: &str, + principal: &str, + id: Uuid, +) -> Result { + let row = tx + .query_opt( + "SELECT document FROM adapter_g2p_attempts WHERE deployment=$1 AND connection=$2 AND principal=$3 AND id=$4 FOR UPDATE", + &[&deployment, &connection, &principal, &id], + ) + .await + .map_err(|_| G2pError::Unavailable)? + .ok_or(G2pError::NotFound)?; + decode(row.get(0)) +} + +async fn persist( + tx: &Transaction<'_>, + deployment: &str, + attempt: &G2pAttempt, + event_kind: &str, +) -> Result<(), G2pError> { + attempt.validate_integrity()?; + let document = serde_json::to_value(attempt).map_err(|_| G2pError::Unavailable)?; + let count = tx + .execute( + "UPDATE adapter_g2p_attempts SET state=$3,document=$4,updated_at=clock_timestamp() WHERE deployment=$1 AND id=$2", + &[&deployment, &attempt.id, &state_name(attempt.state), &document], + ) + .await + .map_err(|_| G2pError::Unavailable)?; + if count != 1 { + return Err(G2pError::Unavailable); + } + event(tx, deployment, attempt, event_kind).await +} + +async fn event( + client: &impl GenericClient, + deployment: &str, + attempt: &G2pAttempt, + kind: &str, +) -> Result<(), G2pError> { + client + .execute( + "INSERT INTO adapter_g2p_events (deployment,attempt_id,principal,kind) VALUES ($1,$2,$3,$4)", + &[&deployment, &attempt.id, &attempt.principal, &kind], + ) + .await + .map_err(|_| G2pError::Unavailable)?; + Ok(()) +} + +#[allow(clippy::too_many_arguments)] +async fn claim_command( + client: &impl GenericClient, + deployment: &str, + connection: &str, + principal: &str, + command_key: &str, + request_digest: &str, + id: Uuid, +) -> Result<(), G2pError> { + client + .execute( + "INSERT INTO adapter_g2p_commands (deployment,connection,principal,command_key,request_digest,attempt_id) VALUES ($1,$2,$3,$4,$5,$6) ON CONFLICT DO NOTHING", + &[&deployment, &connection, &principal, &command_key, &request_digest, &id], + ) + .await + .map_err(|_| G2pError::Unavailable)?; + let row = client + .query_one( + "SELECT request_digest,attempt_id FROM adapter_g2p_commands WHERE deployment=$1 AND connection=$2 AND principal=$3 AND command_key=$4", + &[&deployment, &connection, &principal, &command_key], + ) + .await + .map_err(|_| G2pError::Unavailable)?; + if row.get::<_, String>(0) != request_digest || row.get::<_, Uuid>(1) != id { + return Err(G2pError::Conflict); + } + Ok(()) +} + +fn decode(value: serde_json::Value) -> Result { + let attempt: G2pAttempt = serde_json::from_value(value).map_err(|_| G2pError::Unavailable)?; + attempt.validate_integrity()?; + Ok(attempt) +} + +fn state_name(state: G2pAttemptState) -> &'static str { + match state { + G2pAttemptState::BindPrepared => "bind-prepared", + G2pAttemptState::Bound => "bound", + G2pAttemptState::DispatchStarted => "dispatch-started", + G2pAttemptState::ProviderAccepted => "provider-accepted", + G2pAttemptState::ProviderPending => "provider-pending", + G2pAttemptState::ProviderUnknown => "provider-unknown", + G2pAttemptState::ProviderConfirmed => "provider-confirmed", + G2pAttemptState::ProviderFailed => "provider-failed", + G2pAttemptState::ConfirmationPrepared => "confirmation-prepared", + G2pAttemptState::ConfirmationRecorded => "confirmation-recorded", + } +} diff --git a/crates/registry-adapter/src/payments/http.rs b/crates/registry-adapter/src/payments/http.rs index 96d70c8bf1..9a3d4a2746 100644 --- a/crates/registry-adapter/src/payments/http.rs +++ b/crates/registry-adapter/src/payments/http.rs @@ -3,6 +3,16 @@ use super::{ config::{PaymentsConfig, API_VERSION, KIND}, + g2p_config::G2pConnection, + g2p_model::{G2pAttempt, G2pAttemptState, G2pError}, + g2p_registry::BregG2pBridge, + g2p_service::{G2pService, HttpG2pProvider}, + g2p_store::{migrate_g2p, G2pStore}, + pack::{ + ConnectorKind, PaymentCapability, PaymentOperationMapping, PaymentProviderAuth, + PaymentProviderPack, ProviderPackPin, + }, + provider_mapping::{PaymentMappingProgram, PaymentMappingRegistry}, registry::BregBridge, service::{PaymentService, SyntheticProvider}, store::{migrate, PaymentStore}, @@ -18,28 +28,37 @@ use axum::{ }; use registry_adapter_core::AdapterRuntimeConfig; use registry_payment_protocol::{ - PaymentProblem, PaymentProblemCode as Error, RecordReceipt, RequestCollection, + DisbursementAccepted, DisbursementState, DisbursementStatus, Money, PaymentProblem, + PaymentProblemCode as Error, ProviderConfirmation, RecordProviderConfirmation, RecordReceipt, + RequestCollection, RequestDisbursement, }; use registry_platform_config::{ RuntimeConfigLoader, RuntimeEnvelope, SecretProvider, SecretResolver, }; use serde::{de::DeserializeOwned, Serialize}; -use std::{path::Path, sync::Arc}; +use std::{ + collections::BTreeMap, + path::{Path, PathBuf}, + sync::Arc, +}; use uuid::Uuid; struct HttpState { authenticator: Authenticator, service: PaymentService, + g2p: G2pService, + disbursements: Vec, } /// Fixed payment routes and wire schemas, without origins or credential references. #[cfg(feature = "schema")] pub fn contract(config: &PaymentsConfig) -> serde_json::Value { + use registry_payment_protocol::ReadDisbursement; use registry_payment_protocol::{CollectionAccepted, CollectionStatus, RegistryReceipt}; serde_json::json!({ "protocol":"payments/v1", "authentication":"OIDC access tokens under the Adapter runtime issuer and client policy", - "simulation":true, + "simulation":config.disbursements.is_empty() && config.connections.iter().all(|connection| connection.binding.simulation), "connections":config.connections.iter().map(|connection| { let base=format!("/v1/payments/{}/collections",connection.id); serde_json::json!({ @@ -53,13 +72,32 @@ pub fn contract(config: &PaymentsConfig) -> serde_json::Value { {"operation":"payments.record-receipt/v1","method":"POST","path":format!("{base}/{{collectionId}}/record-receipt"),"successStatus":200,"effect":"mutation"} ] }) - }).collect::>(), + }).chain(config.disbursements.iter().map(|connection| { + let base=format!("/v1/payments/{}/disbursements",connection.id); + serde_json::json!({ + "connection":connection.id, + "allowedClients":connection.allowed_clients, + "requiredScope":connection.required_scope, + "operations":[ + {"operation":"payments.request-disbursement/v1","method":"POST","path":base,"successStatus":202,"effect":"mutation"}, + {"operation":"payments.request-disbursement-receipt/v1","method":"POST","path":format!("{base}/receipt"),"successStatus":200,"effect":"read","recoveryOnly":true}, + {"operation":"payments.read-disbursement/v1","method":"GET","path":format!("{base}/{{disbursementId}}"),"successStatus":200,"effect":"read"}, + {"operation":"payments.record-provider-confirmation/v1","method":"POST","path":format!("{base}/{{disbursementId}}/record-provider-confirmation"),"successStatus":200,"effect":"mutation"} + ] + }) + })).collect::>(), "schemas":{ "RequestCollection":schemars::schema_for!(RequestCollection), "CollectionAccepted":schemars::schema_for!(CollectionAccepted), "CollectionStatus":schemars::schema_for!(CollectionStatus), "RecordReceipt":schemars::schema_for!(RecordReceipt), "RegistryReceipt":schemars::schema_for!(RegistryReceipt), + "RequestDisbursement":schemars::schema_for!(RequestDisbursement), + "ReadDisbursement":schemars::schema_for!(ReadDisbursement), + "DisbursementAccepted":schemars::schema_for!(DisbursementAccepted), + "DisbursementStatus":schemars::schema_for!(DisbursementStatus), + "RecordProviderConfirmation":schemars::schema_for!(RecordProviderConfirmation), + "ProviderConfirmation":schemars::schema_for!(ProviderConfirmation), "PaymentProblem":schemars::schema_for!(PaymentProblem) } }) @@ -89,12 +127,157 @@ fn resolver(runtime: &AdapterRuntimeConfig) -> Result, + expected: PaymentProviderAuth, +) -> bool { + operation.is_some_and(|operation| operation.auth == expected) +} + +fn live_disbursement_auth_supported(auth: PaymentProviderAuth) -> bool { + matches!(auth, PaymentProviderAuth::Bearer) +} + +const MAX_PAYMENT_PROVIDER_PACKS: usize = 32; + +struct LoadedPaymentPacks { + by_digest: BTreeMap)>, + mapping: Option>, +} + +impl LoadedPaymentPacks { + fn for_pin(&self, pin: &ProviderPackPin) -> Result<&PaymentProviderPack, ServeError> { + let (pack, bytes) = self + .by_digest + .get(&pin.digest) + .ok_or_else(|| refused("pinned payment provider pack was not supplied"))?; + pack.check_pin(pin, bytes) + .map_err(|_| refused("payment provider pack pin differs"))?; + Ok(pack) + } +} + +fn load_provider_packs(paths: &[PathBuf]) -> Result { + if paths.len() > MAX_PAYMENT_PROVIDER_PACKS { + return Err(refused("too many payment provider packs were supplied")); + } + let mut by_digest = BTreeMap::new(); + let mut mapping = PaymentMappingRegistry::new(); + let mut mapped_count = 0; + for path in paths { + let absolute = std::fs::canonicalize(path) + .map_err(|_| refused("payment provider pack could not be read"))?; + let bytes = std::fs::read(&absolute) + .map_err(|_| refused("payment provider pack could not be read"))?; + let pack = PaymentProviderPack::from_yaml(&bytes) + .map_err(|_| refused("payment provider pack was refused"))?; + pack.validate() + .map_err(|_| refused("payment provider pack was refused"))?; + let digest = registry_platform_config::sha256_uri(&bytes); + if by_digest.contains_key(&digest) { + return Err(refused("payment provider pack was supplied more than once")); + } + if pack.connector == ConnectorKind::AdapterPaymentHttpV1 { + let root = absolute + .parent() + .ok_or_else(|| refused("payment provider pack path was refused"))?; + let scripts = pack + .mapping + .as_ref() + .ok_or_else(|| refused("payment provider pack mapping was refused"))? + .scripts + .iter() + .map(|script| { + let script_path = + std::fs::canonicalize(root.join(&script.path)).map_err(|_| { + refused("payment provider mapping artifact could not be read") + })?; + if !script_path.starts_with(root) || !script_path.is_file() { + return Err(refused("payment provider mapping artifact was refused")); + } + let bytes = std::fs::read(script_path).map_err(|_| { + refused("payment provider mapping artifact could not be read") + })?; + Ok((script.path.clone(), bytes)) + }) + .collect::, ServeError>>()?; + let program = PaymentMappingProgram::compile(&pack, &bytes, &scripts) + .map_err(|_| refused("payment provider mapping was refused"))?; + mapping + .insert(program) + .map_err(|_| refused("payment provider mapping registry was refused"))?; + mapped_count += 1; + } + by_digest.insert(digest, (pack, bytes)); + } + Ok(LoadedPaymentPacks { + by_digest, + mapping: (mapped_count > 0).then(|| Arc::new(mapping)), + }) +} + pub async fn load_router( runtime: &AdapterRuntimeConfig, path: &Path, + provider_pack_paths: &[PathBuf], pool: deadpool_postgres::Pool, ) -> Result { let config = load_config(path)?; + let packs = load_provider_packs(provider_pack_paths)?; + for connection in &config.connections { + let Some(pin) = connection.binding.provider_pack.as_ref() else { + if connection.binding.simulation { + continue; + } + return Err(refused("payment connection must pin the provider pack")); + }; + let pack = packs.for_pin(pin)?; + if pack.connector != connection.binding.connector_kind() + || !pack.capabilities.contains(&PaymentCapability::Collection) + { + return Err(refused( + "payment provider pack lacks collection capability or connector", + )); + } + if matches!( + &connection.binding.provider, + super::config::CollectionProvider::Http { .. } + ) && !mapping_auth_matches( + pack.mapping + .as_ref() + .and_then(|mapping| mapping.collection.as_ref()), + PaymentProviderAuth::Bearer, + ) { + return Err(refused( + "payment provider collection mapping requires unsupported authentication", + )); + } + } + for connection in &config.disbursements { + let pack = packs.for_pin(&connection.binding.provider_pack)?; + if pack.connector != ConnectorKind::AdapterPaymentHttpV1 + || !pack.capabilities.contains(&PaymentCapability::Disbursement) + { + return Err(refused( + "payment provider pack lacks generic HTTP disbursement capability", + )); + } + if !mapping_auth_matches( + pack.mapping + .as_ref() + .and_then(|mapping| mapping.disbursement.as_ref()), + connection.binding.provider.auth_profile(), + ) { + return Err(refused( + "payment provider disbursement mapping authentication differs from the connection", + )); + } + if !live_disbursement_auth_supported(connection.binding.provider.auth_profile()) { + return Err(refused( + "payment provider disbursement authentication is not implemented by the live host", + )); + } + } let resolver = Arc::new(resolver(runtime)?); for connection in &config.connections { for reference in [ @@ -110,6 +293,20 @@ pub async fn load_router( .map_err(|_| refused("a payment credential was refused"))?; } } + for connection in &config.disbursements { + for reference in [ + connection.binding.provider.credential_ref(), + &connection.binding.registry.credential_ref, + ] { + let value = resolver + .resolve(reference.as_str()) + .map_err(|_| refused("a payment credential could not be resolved"))?; + let value = std::str::from_utf8(value.expose_secret()) + .map_err(|_| refused("a payment credential was refused"))?; + registry_platform_httputil::client::BearerToken::new(value.to_owned()) + .map_err(|_| refused("a payment credential was refused"))?; + } + } let authenticator = crate::serve::authenticator(runtime, &resolver).await?; let migration = crate::serve::pool(&runtime.database, &resolver, true)?; { @@ -120,22 +317,45 @@ pub async fn load_router( migrate(&mut client) .await .map_err(|_| refused("payment database migration failed"))?; + migrate_g2p(&mut client) + .await + .map_err(|_| refused("G2P database migration failed"))?; } - let store = PaymentStore::new(pool, runtime.id.as_str().to_owned()); + let store = PaymentStore::new(pool.clone(), runtime.id.as_str().to_owned()); store .check_privileges() .await .map_err(|_| refused("payment runtime role lacks required table or sequence privileges"))?; + let g2p_store = G2pStore::new(pool.clone(), runtime.id.as_str().to_owned()); + if !config.disbursements.is_empty() { + g2p_store + .check_privileges() + .await + .map_err(|_| refused("G2P runtime role lacks required table or sequence privileges"))?; + } + let g2p = G2pService::new( + g2p_store, + Arc::new(BregG2pBridge::new(resolver.clone())), + Arc::new(HttpG2pProvider::new(resolver.clone())), + ); + let g2p = if let Some(mapping) = packs.mapping.clone() { + g2p.with_mapping(mapping) + } else { + g2p + }; + let disbursements = config.disbursements.clone(); let service = PaymentService::new( config, store, Arc::new(BregBridge::new(resolver.clone())), - Arc::new(SyntheticProvider::new(resolver)), + Arc::new(SyntheticProvider::new(resolver, packs.mapping)), ) .map_err(|_| refused("payment service was refused"))?; let state = Arc::new(HttpState { authenticator, service, + g2p, + disbursements, }); Ok(Router::new() .route("/v1/payments/{connection}/collections", post(request)) @@ -151,11 +371,31 @@ pub async fn load_router( "/v1/payments/{connection}/collections/{collection}/record-receipt", post(record_receipt), ) + .route( + "/v1/payments/{connection}/disbursements", + post(request_disbursement), + ) + .route( + "/v1/payments/{connection}/disbursements/receipt", + post(disbursement_receipt), + ) + .route( + "/v1/payments/{connection}/disbursements/{disbursement}", + get(read_disbursement), + ) + .route( + "/v1/payments/{connection}/disbursements/{disbursement}/record-provider-confirmation", + post(record_provider_confirmation), + ) .layer(DefaultBodyLimit::max(4096)) .with_state(state)) } -pub async fn run_only(runtime_path: &Path, payments_path: &Path) -> Result<(), ServeError> { +pub async fn run_only( + runtime_path: &Path, + payments_path: &Path, + provider_pack_paths: &[PathBuf], +) -> Result<(), ServeError> { let absolute = std::fs::canonicalize(runtime_path) .map_err(|_| refused("runtime configuration could not be read"))?; let runtime = RuntimeConfigLoader::new(RuntimeEnvelope { @@ -168,7 +408,7 @@ pub async fn run_only(runtime_path: &Path, payments_path: &Path) -> Result<(), S .config; let resolver = resolver(&runtime)?; let pool = crate::serve::pool(&runtime.database, &resolver, false)?; - let router = load_router(&runtime, payments_path, pool).await?; + let router = load_router(&runtime, payments_path, provider_pack_paths, pool).await?; let shutdown = crate::serve::shutdown_signal()?; let listener = tokio::net::TcpListener::bind(runtime.listener.bind.0) .await @@ -322,6 +562,282 @@ async fn record_receipt( .await } +async fn g2p_connection<'a>( + state: &'a HttpState, + id: &str, + caller: &Caller, + operation: &str, +) -> Result<&'a G2pConnection, HttpError> { + let selected = state + .disbursements + .iter() + .find(|entry| entry.id == id) + .ok_or(Error::NotFound) + .and_then(|connection| { + if !connection.allowed_clients.contains(&caller.client_id) + || !caller.scopes.contains(&connection.required_scope) + { + Err(Error::Forbidden) + } else { + Ok(connection) + } + }); + if let Err(error) = selected { + state + .service + .audit_access(caller, operation, None, Some(error)) + .await + .map_err(|_| HttpError(Error::Unavailable))?; + } + selected.map_err(HttpError) +} + +fn g2p_principal(caller: &Caller) -> Result { + super::model::digest(&[&caller.issuer, &caller.client_id, &caller.reference]) +} + +fn g2p_error(error: G2pError) -> Error { + match error { + G2pError::InvalidRequest => Error::InvalidRequest, + G2pError::Conflict => Error::Conflict, + G2pError::NotFound => Error::NotFound, + G2pError::Unavailable => Error::Unavailable, + G2pError::OutcomeUnknown => Error::OutcomeUnknown, + G2pError::RecoveryHeld => Error::RecoveryHeld, + } +} + +fn disbursement_accepted(attempt: &G2pAttempt) -> Result { + if attempt.provider_acceptance.is_none() { + return Err(Error::OutcomeUnknown); + } + let accepted = DisbursementAccepted { + disbursement_id: attempt.id, + instruction_record_id: attempt.instruction.record_id, + instruction_id: attempt.instruction.instruction_id, + instruction_version: attempt.instruction.instruction_version, + binding_revision: attempt.binding_revision.clone(), + simulation: false, + }; + accepted.validate().map_err(|_| Error::Unavailable)?; + Ok(accepted) +} + +fn disbursement_status(attempt: &G2pAttempt) -> Result { + let state = match attempt.state { + G2pAttemptState::ProviderAccepted => DisbursementState::Accepted, + G2pAttemptState::ProviderPending => DisbursementState::Pending, + G2pAttemptState::ProviderConfirmed + | G2pAttemptState::ConfirmationPrepared + | G2pAttemptState::ConfirmationRecorded => DisbursementState::ProviderConfirmed, + G2pAttemptState::ProviderFailed => DisbursementState::Failed, + G2pAttemptState::BindPrepared + | G2pAttemptState::Bound + | G2pAttemptState::DispatchStarted + | G2pAttemptState::ProviderUnknown => DisbursementState::Unknown, + }; + let value = DisbursementStatus { + disbursement_id: attempt.id, + instruction_record_id: attempt.instruction.record_id, + instruction_id: attempt.instruction.instruction_id, + instruction_version: attempt.instruction.instruction_version, + binding_revision: attempt.binding_revision.clone(), + simulation: false, + state, + money: Money { + value: attempt.instruction.amount(), + currency: attempt.instruction.currency.clone(), + scale: attempt.instruction.currency_scale, + }, + provider_reference: if state == DisbursementState::ProviderConfirmed { + attempt + .provider_observation + .as_ref() + .and_then(|observation| observation.provider_reference.clone()) + } else { + None + }, + failure_reason: (state == DisbursementState::Failed) + .then(|| "provider-reported-failure".to_owned()), + }; + value.validate().map_err(|_| Error::Unavailable)?; + Ok(value) +} + +async fn request_disbursement( + State(state): State>, + RoutePath(connection): RoutePath, + uri: Uri, + headers: HeaderMap, + bytes: Bytes, +) -> Result { + let caller = caller(&state, &headers).await?; + let request: RequestDisbursement = body(&headers, &uri, &bytes)?; + request + .validate() + .map_err(|_| HttpError(Error::InvalidRequest))?; + let key = single_header(&headers, "idempotency-key")?; + if !super::config::text(key, 128) { + return Err(HttpError(Error::InvalidRequest)); + } + let selected = g2p_connection(&state, &connection, &caller, "request-disbursement").await?; + let result = state + .g2p + .request_disbursement( + &connection, + &g2p_principal(&caller).map_err(HttpError)?, + key, + request.instruction_record_id, + request.instruction_version, + selected.binding.clone(), + time::OffsetDateTime::now_utc().unix_timestamp(), + ) + .await + .map_err(g2p_error) + .and_then(|attempt| disbursement_accepted(&attempt)); + finish( + &state, + &caller, + "request-disbursement", + None, + true, + StatusCode::ACCEPTED, + result, + ) + .await +} + +async fn disbursement_receipt( + State(state): State>, + RoutePath(connection): RoutePath, + uri: Uri, + headers: HeaderMap, + bytes: Bytes, +) -> Result { + let caller = caller(&state, &headers).await?; + let request: RequestDisbursement = body(&headers, &uri, &bytes)?; + request + .validate() + .map_err(|_| HttpError(Error::InvalidRequest))?; + let key = single_header(&headers, "idempotency-key")?; + if !super::config::text(key, 128) { + return Err(HttpError(Error::InvalidRequest)); + } + g2p_connection(&state, &connection, &caller, "request-disbursement-receipt").await?; + let result = state + .g2p + .request_receipt( + &connection, + &g2p_principal(&caller).map_err(HttpError)?, + key, + request.instruction_record_id, + request.instruction_version, + ) + .await + .map_err(g2p_error) + .and_then(|attempt| disbursement_accepted(&attempt)); + finish( + &state, + &caller, + "request-disbursement-receipt", + None, + false, + StatusCode::OK, + result, + ) + .await +} + +async fn read_disbursement( + State(state): State>, + RoutePath((connection, id)): RoutePath<(String, String)>, + uri: Uri, + headers: HeaderMap, + bytes: Bytes, +) -> Result { + let caller = caller(&state, &headers).await?; + if uri.query().is_some() || !bytes.is_empty() { + return Err(HttpError(Error::InvalidRequest)); + } + g2p_connection(&state, &connection, &caller, "read-disbursement").await?; + let id = collection(&id)?; + let result = state + .g2p + .disbursement_status(&connection, &g2p_principal(&caller).map_err(HttpError)?, id) + .await + .map_err(g2p_error) + .and_then(|attempt| disbursement_status(&attempt)); + finish( + &state, + &caller, + "read-disbursement", + Some(id), + false, + StatusCode::OK, + result, + ) + .await +} + +async fn record_provider_confirmation( + State(state): State>, + RoutePath((connection, id)): RoutePath<(String, String)>, + uri: Uri, + headers: HeaderMap, + bytes: Bytes, +) -> Result { + let caller = caller(&state, &headers).await?; + let id = collection(&id)?; + let request: RecordProviderConfirmation = body(&headers, &uri, &bytes)?; + if request.disbursement_id != id { + return Err(HttpError(Error::InvalidRequest)); + } + let key = single_header(&headers, "idempotency-key")?; + if !super::config::text(key, 128) { + return Err(HttpError(Error::InvalidRequest)); + } + g2p_connection(&state, &connection, &caller, "record-provider-confirmation").await?; + let result = state + .g2p + .record_provider_confirmation( + &connection, + &g2p_principal(&caller).map_err(HttpError)?, + key, + id, + ) + .await + .map_err(g2p_error) + .and_then(|attempt| { + if attempt.state != G2pAttemptState::ConfirmationRecorded { + return Err(Error::RecoveryHeld); + } + let status = disbursement_status(&attempt)?; + let confirmation = ProviderConfirmation { + disbursement_id: id, + instruction_record_id: attempt.instruction.record_id, + instruction_id: attempt.instruction.instruction_id, + instruction_version: attempt.instruction.instruction_version, + binding_revision: attempt.binding_revision, + simulation: false, + money: status.money, + provider_reference: status.provider_reference.ok_or(Error::Unavailable)?, + provider_result_digest: attempt.provider_result_digest.ok_or(Error::Unavailable)?, + }; + confirmation.validate().map_err(|_| Error::Unavailable)?; + Ok(confirmation) + }); + finish( + &state, + &caller, + "record-provider-confirmation", + Some(id), + true, + StatusCode::OK, + result, + ) + .await +} + #[allow(clippy::too_many_arguments)] async fn finish( state: &HttpState, @@ -380,10 +896,110 @@ fn headers(mut response: Response) -> Response { HeaderValue::from_static("nosniff"), ); response - .headers_mut() - .insert("x-payment-simulator", HeaderValue::from_static("synthetic")); - response } fn refused(message: &str) -> ServeError { ServeError::Configuration(format!("adapter.payment.configuration: {message}")) } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn startup_auth_match_is_exact_for_each_generic_payment_direction() { + let pack = PaymentProviderPack::from_yaml( + format!( + r#"apiVersion: id.registrystack.org/formats/adapter/payment-provider-pack/v1alpha1 +kind: AdapterPaymentProviderPack +id: auth-contract +version: '1' +connector: adapter-payment-http/v1 +capabilities: [collection, disbursement] +mapping: + collection: + auth: bearer + submit: + path: /collect + request: {{file: scripts/provider.rhai, entrypoint: collection_request}} + response: {{file: scripts/provider.rhai, entrypoint: collection_response}} + disbursement: + auth: mifos-legacy-signature + submit: + path: /disburse + request: {{file: scripts/provider.rhai, entrypoint: disbursement_request}} + response: {{file: scripts/provider.rhai, entrypoint: disbursement_response}} + scripts: + - path: scripts/provider.rhai + digest: sha256:{} +"#, + "0".repeat(64) + ) + .as_bytes(), + ) + .unwrap(); + let mapping = pack.mapping.as_ref().unwrap(); + assert!(mapping_auth_matches( + mapping.collection.as_ref(), + PaymentProviderAuth::Bearer, + )); + assert!(!mapping_auth_matches( + mapping.collection.as_ref(), + PaymentProviderAuth::MifosLegacySignature, + )); + assert!(mapping_auth_matches( + mapping.disbursement.as_ref(), + PaymentProviderAuth::MifosLegacySignature, + )); + assert!(!mapping_auth_matches( + mapping.disbursement.as_ref(), + PaymentProviderAuth::Bearer, + )); + assert!(!mapping_auth_matches(None, PaymentProviderAuth::Bearer)); + } + + #[test] + fn startup_refuses_disbursement_auth_without_a_runtime_signer_and_verifier() { + assert!(live_disbursement_auth_supported( + PaymentProviderAuth::Bearer + )); + assert!(!live_disbursement_auth_supported( + PaymentProviderAuth::MifosLegacySignature + )); + } + + #[test] + fn startup_keeps_multiple_exact_pack_pins_for_recovery() { + let directory = tempfile::tempdir().unwrap(); + let pack_bytes = |version: &str| { + format!( + "apiVersion: {}\nkind: {}\nid: sample-payments\nversion: '{version}'\nconnector: simulator-p2g/v1\ncapabilities: [collection]\n", + super::super::pack::API_VERSION, + super::super::pack::KIND, + ) + .into_bytes() + }; + let first = directory.path().join("first.yaml"); + let second = directory.path().join("second.yaml"); + let first_bytes = pack_bytes("1"); + let second_bytes = pack_bytes("2"); + std::fs::write(&first, &first_bytes).unwrap(); + std::fs::write(&second, &second_bytes).unwrap(); + let loaded = load_provider_packs(&[first.clone(), second.clone()]).unwrap(); + let pin = |version: &str, bytes: &[u8]| super::super::pack::ProviderPackPin { + id: "sample-payments".to_owned(), + version: version.to_owned(), + digest: registry_platform_config::sha256_uri(bytes), + }; + assert_eq!( + loaded.for_pin(&pin("1", &first_bytes)).unwrap().version, + "1" + ); + assert_eq!( + loaded.for_pin(&pin("2", &second_bytes)).unwrap().version, + "2" + ); + assert!(loaded.for_pin(&pin("3", &first_bytes)).is_err()); + assert!(load_provider_packs(&[first.clone(), first]).is_err()); + assert!(load_provider_packs(&vec![second; MAX_PAYMENT_PROVIDER_PACKS + 1]).is_err()); + } +} diff --git a/crates/registry-adapter/src/payments/mod.rs b/crates/registry-adapter/src/payments/mod.rs index 80304c56f3..22aa3bdf16 100644 --- a/crates/registry-adapter/src/payments/mod.rs +++ b/crates/registry-adapter/src/payments/mod.rs @@ -2,8 +2,15 @@ //! Payment-specific attempt custody at the Adapter host boundary. The generic //! route engine has no payment state, provider semantics, or receipt authority. pub mod config; +pub mod g2p_config; +pub mod g2p_model; +pub mod g2p_registry; +pub mod g2p_service; +pub mod g2p_store; pub mod http; pub mod model; +pub mod pack; +pub mod provider_mapping; pub mod registry; pub mod service; pub mod store; diff --git a/crates/registry-adapter/src/payments/model.rs b/crates/registry-adapter/src/payments/model.rs index c6566a95a4..10a95b4972 100644 --- a/crates/registry-adapter/src/payments/model.rs +++ b/crates/registry-adapter/src/payments/model.rs @@ -1,13 +1,17 @@ // SPDX-License-Identifier: Apache-2.0 //! Immutable bill and provider facts retained for exact recovery. -use super::config::{PaymentBinding, PaymentConnection}; +use super::config::{CollectionProvider, PaymentBinding, PaymentConnection}; +use super::provider_mapping::{PreparedProviderRequest, ProviderAcceptance}; use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine}; +use registry_payment_mifos_connector::{ + CollectionCommand, ExactMoney, PartyIdentifier, TransactionType, +}; use registry_payment_protocol::{ CollectionAccepted, CollectionState, CollectionStatus, Money, PaymentProblemCode, RegistryReceipt, MAX_MINOR_UNITS, }; -use registry_payment_simulator_connector::{Observation, ProviderCommand}; +use registry_payment_simulator_connector::{Observation, ProviderCommand as SimulatorCommand}; use serde::{Deserialize, Serialize}; use serde_json::{Map, Value}; use sha2::{Digest, Sha256}; @@ -38,8 +42,7 @@ impl BillSnapshot { || self.bill_version > MAX_MINOR_UNITS || self.institution_id != connection.institution_id || self.service_id != connection.service_id - || !self.simulation - || !connection.binding.simulation + || self.simulation != connection.binding.simulation || self.money.currency != connection.binding.currency || self.money.scale != connection.binding.currency_scale || !super::config::text(&self.bill_digest, 64) @@ -70,37 +73,212 @@ impl BillSnapshot { pub fn provider_command( &self, binding: &PaymentBinding, - ) -> Result { - let origin = url::Url::parse(&binding.provider.base_url) - .map_err(|_| PaymentProblemCode::Unavailable)?; + ) -> Result { + match &binding.provider { + CollectionProvider::Simulator { connection } => { + let origin = url::Url::parse(&connection.base_url) + .map_err(|_| PaymentProblemCode::Unavailable)?; + let identity = serde_json::json!({ + "domain": "registry-adapter/payment-provider-command/v1", + "provider": { + "origin": origin.as_str(), + "producer": binding.provider_credential_identity, + "tenant": connection.tenant, + "biller": connection.biller, + }, + "bill": self, + }); + let canonical = registry_platform_canonical_json::canonicalize_json(&identity) + .map_err(|_| PaymentProblemCode::Unavailable)?; + let digest = Sha256::digest(canonical); + // Disjoint digest portions retain 180 bits across the bounded wire tuple. + // A requestId collision with a different body must remain a provider conflict. + let mut number = [0_u8; 8]; + number[1..].copy_from_slice(&digest[16..23]); + let command = SimulatorCommand { + request_id: URL_SAFE_NO_PAD.encode(&digest[..9]), + bill_id: URL_SAFE_NO_PAD.encode(&digest[9..16]), + rtp_id: (u64::from_be_bytes(number) & ((1_u64 << 52) - 1)) + 1, + payer_address: self.payer_financial_address.clone(), + money: self.money.clone(), + }; + command + .validate() + .map_err(|_| PaymentProblemCode::Unavailable)?; + Ok(CollectionProviderCommand::Simulator(command)) + } + CollectionProvider::Mifos { + connection, + payer, + transaction_type, + } => { + let channel = url::Url::parse(&connection.channel_base_url) + .map_err(|_| PaymentProblemCode::Unavailable)?; + let operations = url::Url::parse(&connection.operations_base_url) + .map_err(|_| PaymentProblemCode::Unavailable)?; + let identity = serde_json::json!({ + "domain": "registry-adapter/mifos-collection-command/v1", + "provider": { + "connector": registry_payment_mifos_connector::CONNECTOR_PROFILE, + "providerPack": binding.provider_pack, + "channelOrigin": channel.as_str(), + "operationsOrigin": operations.as_str(), + "producer": binding.provider_credential_identity, + "tenant": connection.tenant, + "paymentScheme": connection.payment_scheme, + "payer": payer, + "transactionType": transaction_type, + }, + "bill": self, + }); + let canonical = registry_platform_canonical_json::canonicalize_json(&identity) + .map_err(|_| PaymentProblemCode::Unavailable)?; + let digest = Sha256::digest(canonical); + let money = self + .money + .canonical() + .map_err(|_| PaymentProblemCode::Unavailable)?; + let command = CollectionCommand { + correlation_id: URL_SAFE_NO_PAD.encode(&digest[..18]), + payer: [ + PartyIdentifier { + key: payer.financial_address_key.clone(), + value: self.payer_financial_address.clone(), + }, + PartyIdentifier { + key: payer.payer_id_key.clone(), + value: self.payer_id.clone(), + }, + ], + money: ExactMoney { + amount: money.value, + currency: money.currency, + }, + transaction_type: TransactionType { + scenario: transaction_type.scenario.clone(), + sub_scenario: transaction_type.sub_scenario.clone(), + initiator: transaction_type.initiator.clone(), + initiator_type: transaction_type.initiator_type.clone(), + }, + }; + command + .validate() + .map_err(|_| PaymentProblemCode::Unavailable)?; + Ok(CollectionProviderCommand::Mifos(command)) + } + CollectionProvider::Http { .. } => Err(PaymentProblemCode::Unavailable), + } + } + + /// Host-owned collection intent supplied to a reviewed pure mapping. The + /// correlation binds the complete authoritative bill, fixed provider + /// origins, operator settings, producer identity and provider pack. The + /// mapping never receives credentials or chooses transport authority. + pub fn http_intent(&self, binding: &PaymentBinding) -> Result { + let CollectionProvider::Http { + submit_base_url, + status_base_url, + settings, + } = &binding.provider + else { + return Err(PaymentProblemCode::Unavailable); + }; + let provider_pack = binding + .provider_pack + .as_ref() + .ok_or(PaymentProblemCode::Unavailable)?; + let submit = + url::Url::parse(submit_base_url).map_err(|_| PaymentProblemCode::Unavailable)?; + let status = + url::Url::parse(status_base_url).map_err(|_| PaymentProblemCode::Unavailable)?; let identity = serde_json::json!({ - "domain": "registry-adapter/payment-provider-command/v1", + "domain": "registry-adapter/http-collection-command/v1", "provider": { - "origin": origin.as_str(), + "providerPack": provider_pack, + "submitOrigin": submit.as_str(), + "statusOrigin": status.as_str(), "producer": binding.provider_credential_identity, - "tenant": binding.provider.tenant, - "biller": binding.provider.biller, + "settings": settings, }, "bill": self, }); let canonical = registry_platform_canonical_json::canonicalize_json(&identity) .map_err(|_| PaymentProblemCode::Unavailable)?; - let digest = Sha256::digest(canonical); - // Disjoint digest portions retain 180 bits across the bounded wire tuple. - // A requestId collision with a different body must remain a provider conflict. - let mut number = [0_u8; 8]; - number[1..].copy_from_slice(&digest[16..23]); - let command = ProviderCommand { - request_id: URL_SAFE_NO_PAD.encode(&digest[..9]), - bill_id: URL_SAFE_NO_PAD.encode(&digest[9..16]), - rtp_id: (u64::from_be_bytes(number) & ((1_u64 << 52) - 1)) + 1, - payer_address: self.payer_financial_address.clone(), - money: self.money.clone(), - }; - command - .validate() + let correlation_id = URL_SAFE_NO_PAD.encode(&Sha256::digest(canonical)[..18]); + let minor_units = self + .money + .minor_units() .map_err(|_| PaymentProblemCode::Unavailable)?; - Ok(command) + Ok(serde_json::json!({ + "correlationId": correlation_id, + "payerFinancialAddress": self.payer_financial_address, + "payerId": self.payer_id, + "money": { + "minorUnits": minor_units, + "currency": self.money.currency, + "scale": self.money.scale, + }, + })) + } +} + +/// Exact retained input and POST request for the generic fixed-role HTTP +/// connector. `preparedSubmit` is mapped and canonicalized before the attempt +/// is reserved, then sent without evaluating the mapping again. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct HttpCollectionCommand { + pub intent: Value, + pub prepared_submit: PreparedProviderRequest, +} + +/// Exact durable command for the selected provider. Untagged serialization +/// leaves all retained simulator attempts in their original wire shape. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(untagged)] +pub enum CollectionProviderCommand { + Simulator(SimulatorCommand), + Mifos(CollectionCommand), + Http(HttpCollectionCommand), +} + +impl CollectionProviderCommand { + pub fn validate(&self) -> Result<(), PaymentProblemCode> { + match self { + Self::Simulator(command) => command + .validate() + .map_err(|_| PaymentProblemCode::Unavailable), + Self::Mifos(command) => command + .validate() + .map_err(|_| PaymentProblemCode::Unavailable), + Self::Http(command) => { + if command.prepared_submit.role + != super::provider_mapping::PaymentEndpointRole::CollectionSubmit + || command.prepared_submit.method + != super::provider_mapping::PaymentHttpMethod::Post + || command.prepared_submit.body.is_none() + || !command.intent.is_object() + { + return Err(PaymentProblemCode::Unavailable); + } + Ok(()) + } + } + } + + #[must_use] + pub const fn simulator(&self) -> Option<&SimulatorCommand> { + match self { + Self::Simulator(command) => Some(command), + Self::Mifos(_) | Self::Http(_) => None, + } + } + + pub fn simulator_mut(&mut self) -> Option<&mut SimulatorCommand> { + match self { + Self::Simulator(command) => Some(command), + Self::Mifos(_) | Self::Http(_) => None, + } } } @@ -123,11 +301,19 @@ pub struct Attempt { pub bill_snapshot_digest: String, pub binding: PaymentBinding, pub binding_revision: String, - pub provider_command: ProviderCommand, + pub provider_command: CollectionProviderCommand, + /// Digest of the exact generic prepared request, including canonical body + /// bytes. Compiled connectors can still rederive their command directly. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub provider_command_digest: Option, pub bind_action: Option, pub bound: bool, pub first_send_at: Option, pub transfer_id: Option, + /// Full mapped acknowledgement for a generic provider. Compiled + /// connectors need only their historical `transferId`. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub provider_acceptance: Option, pub observation: Option, pub report_action: Option, pub receipt_digest: Option, @@ -182,6 +368,12 @@ impl Attempt { return Err(PaymentProblemCode::Conflict); } if let Some(first) = self.first_send_at { + if matches!( + &self.binding.provider, + CollectionProvider::Mifos { .. } | CollectionProvider::Http { .. } + ) { + return Err(PaymentProblemCode::RecoveryHeld); + } if now < first || u64::try_from(now - first).map_err(|_| PaymentProblemCode::RecoveryHeld)? >= self.binding.replay_window_seconds @@ -193,15 +385,43 @@ impl Attempt { } pub fn validate_integrity(&self) -> Result<(), PaymentProblemCode> { + let command_matches = match (&self.binding.provider, &self.provider_command) { + (CollectionProvider::Http { .. }, CollectionProviderCommand::Http(command)) => { + command.intent == self.bill.http_intent(&self.binding)? + && self.binding.provider_pack.as_ref() + == Some(&command.prepared_submit.provider_pack) + && command + .prepared_submit + .validate_restored( + super::provider_mapping::PaymentEndpointRole::CollectionSubmit, + self.binding + .provider_pack + .as_ref() + .ok_or(PaymentProblemCode::Unavailable)?, + ) + .is_ok() + && self.provider_command_digest.as_ref() + == Some(&digest(&self.provider_command)?) + } + (CollectionProvider::Http { .. }, _) | (_, CollectionProviderCommand::Http(_)) => false, + _ => { + self.provider_command_digest.is_none() + && self.provider_command == self.bill.provider_command(&self.binding)? + } + }; if self .binding .revision() .map_err(|_| PaymentProblemCode::Unavailable)? != self.binding_revision || self.bill.digest()? != self.bill_snapshot_digest - || !self.bill.simulation - || !self.binding.simulation - || self.provider_command != self.bill.provider_command(&self.binding)? + || self.bill.simulation != self.binding.simulation + || !command_matches + || self.provider_acceptance.as_ref().is_some_and(|acceptance| { + self.transfer_id.is_none() + || acceptance.correlation_id + != self.provider_command.correlation_id().unwrap_or_default() + }) { return Err(PaymentProblemCode::Unavailable); } @@ -215,6 +435,17 @@ impl Attempt { } } +impl CollectionProviderCommand { + #[must_use] + pub fn correlation_id(&self) -> Option<&str> { + match self { + Self::Simulator(_) => None, + Self::Mifos(command) => Some(&command.correlation_id), + Self::Http(command) => command.intent.get("correlationId")?.as_str(), + } + } +} + pub fn digest(value: &impl Serialize) -> Result { let value = serde_json::to_value(value).map_err(|_| PaymentProblemCode::Unavailable)?; let bytes = registry_platform_canonical_json::canonicalize_json(&value) diff --git a/crates/registry-adapter/src/payments/pack.rs b/crates/registry-adapter/src/payments/pack.rs new file mode 100644 index 0000000000..f31b61cd2f --- /dev/null +++ b/crates/registry-adapter/src/payments/pack.rs @@ -0,0 +1,311 @@ +// SPDX-License-Identifier: Apache-2.0 +//! Reviewed provider selection for the typed payment host. + +use registry_adapter_core::{RhaiExpression, ScriptReference}; +use registry_platform_yaml::{ApiVersion, EnvelopeRule, Expect, FormatSpec, Reader, Report}; +use serde::{Deserialize, Serialize}; +use std::collections::{BTreeMap, BTreeSet}; +use std::path::{Component, Path}; + +pub const API_VERSION: &str = "id.registrystack.org/formats/adapter/payment-provider-pack/v1alpha1"; +pub const KIND: &str = "AdapterPaymentProviderPack"; +pub const SCHEMA_ID: &str = + "https://id.registrystack.org/schemas/adapter/payment-provider-pack/payment-provider-pack.v1alpha1.schema.json"; + +const FORMAT: FormatSpec<'static> = FormatSpec { + kind: KIND, + envelope: EnvelopeRule::ApiVersionKind { + api_versions: &[ApiVersion::current(API_VERSION)], + retired_api_versions: &[], + }, + removed_keys: &[], +}; + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct PaymentProviderPack { + #[cfg_attr(feature = "schema", schemars(with = "registry_platform_yaml::LocalId"))] + pub id: String, + pub version: String, + pub connector: ConnectorKind, + #[cfg_attr(feature = "schema", schemars(length(min = 1), extend("uniqueItems" = true)))] + pub capabilities: Vec, + #[serde(default)] + pub tested_versions: Vec, + /// Pure, digest-pinned provider wire mappings. Compiled connectors omit + /// this member; the generic HTTP connector requires it. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub mapping: Option, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +pub enum ConnectorKind { + #[serde(rename = "simulator-p2g/v1")] + SimulatorP2gV1, + #[serde(rename = "mifos-ph-ee-legacy/v1")] + MifosPhEeLegacyV1, + /// One fixed-role HTTP transport whose provider-specific behavior is + /// limited to the pack's pure request and response mappings. + #[serde(rename = "adapter-payment-http/v1")] + AdapterPaymentHttpV1, +} + +#[derive(Clone, Copy, Debug, Ord, PartialOrd, Eq, PartialEq, Serialize, Deserialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[serde(rename_all = "kebab-case")] +pub enum PaymentCapability { + Collection, + Disbursement, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct ProviderPackPin { + #[cfg_attr(feature = "schema", schemars(with = "registry_platform_yaml::LocalId"))] + pub id: String, + pub version: String, + #[cfg_attr(feature = "schema", schemars(with = "registry_platform_yaml::Digest"))] + pub digest: String, +} + +/// The complete executable mapping closure of one data-driven provider. +/// Scripts are reviewed pack files, never deployment values. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct PaymentProviderMapping { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub collection: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub disbursement: Option, + /// Every Rhai file reachable from the operation mappings, exactly once. + pub scripts: Vec, +} + +/// Submit and optional read-only status mappings for one typed payment +/// direction. The host fixes POST for submit and GET for status. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct PaymentOperationMapping { + /// Host-enforced credential mechanism for every endpoint in this payment + /// direction. Scripts never receive or select credentials. + pub auth: PaymentProviderAuth, + pub submit: PaymentMappingCall, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub status: Option, +} + +/// Closed credential mechanisms implemented by the fixed-role payment host. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[serde(rename_all = "kebab-case")] +pub enum PaymentProviderAuth { + Bearer, + MifosLegacySignature, +} + +/// One pure mapping pair at a reviewed, origin-relative provider path. +/// Neither script can select an origin, endpoint role, method, credential, or +/// retry behavior. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct PaymentMappingCall { + pub path: String, + pub request: RhaiExpression, + pub response: RhaiExpression, +} + +#[derive(Debug, thiserror::Error)] +#[error("adapter.payment.provider-pack-refused")] +pub struct PackError; + +impl PaymentProviderPack { + /// Decode one authored pack using the common strict YAML and envelope reader. + pub fn from_yaml(bytes: &[u8]) -> Result { + let decoded = Reader::new("pack.yaml").decode::(bytes, &Expect::one(&FORMAT))?; + Ok(decoded.value) + } + + pub fn validate(&self) -> Result<(), PackError> { + let capabilities = self.capabilities.iter().copied().collect::>(); + if !local_id(&self.id) + || self.version.is_empty() + || self.version.len() > 64 + || self.capabilities.is_empty() + || capabilities.len() != self.capabilities.len() + || self.tested_versions.len() > 16 + || self + .tested_versions + .iter() + .any(|version| version.is_empty() || version.len() > 128) + { + return Err(PackError); + } + if self.connector == ConnectorKind::SimulatorP2gV1 + && capabilities != BTreeSet::from([PaymentCapability::Collection]) + { + return Err(PackError); + } + match (self.connector, &self.mapping) { + (ConnectorKind::AdapterPaymentHttpV1, Some(mapping)) => { + mapping.validate(&capabilities)?; + } + (ConnectorKind::AdapterPaymentHttpV1, None) + | (ConnectorKind::SimulatorP2gV1 | ConnectorKind::MifosPhEeLegacyV1, Some(_)) => { + return Err(PackError); + } + (ConnectorKind::SimulatorP2gV1 | ConnectorKind::MifosPhEeLegacyV1, None) => {} + } + Ok(()) + } + + pub fn check_pin(&self, pin: &ProviderPackPin, bytes: &[u8]) -> Result<(), PackError> { + self.validate()?; + if pin.id != self.id + || pin.version != self.version + || pin.digest != registry_platform_config::sha256_uri(bytes) + { + return Err(PackError); + } + Ok(()) + } +} + +impl PaymentProviderMapping { + fn validate(&self, capabilities: &BTreeSet) -> Result<(), PackError> { + if self.scripts.is_empty() + || capabilities.contains(&PaymentCapability::Collection) != self.collection.is_some() + || capabilities.contains(&PaymentCapability::Disbursement) + != self.disbursement.is_some() + { + return Err(PackError); + } + + let mut inventory = BTreeMap::new(); + for script in &self.scripts { + if !relative_pack_path(&script.path) + || inventory + .insert(script.path.as_str(), script.digest.as_str()) + .is_some() + { + return Err(PackError); + } + } + let mut referenced = BTreeSet::new(); + for operation in self.collection.iter().chain(self.disbursement.iter()) { + for call in std::iter::once(&operation.submit).chain(operation.status.iter()) { + provider_path_parameters(&call.path)?; + for expression in [&call.request, &call.response] { + if !function_name(&expression.entrypoint) + || !inventory.contains_key(expression.file.as_str()) + { + return Err(PackError); + } + referenced.insert(expression.file.as_str()); + } + } + } + if referenced != inventory.keys().copied().collect() { + return Err(PackError); + } + Ok(()) + } +} + +pub(crate) fn provider_path_parameters(path: &str) -> Result, PackError> { + validate_provider_path(path)?; + let mut parameters = BTreeSet::new(); + let mut rest = path; + while let Some(start) = rest.find("{{") { + if rest[..start].contains('{') || rest[..start].contains('}') { + return Err(PackError); + } + let after = &rest[start + 2..]; + let Some(end) = after.find("}}") else { + return Err(PackError); + }; + let name = &after[..end]; + if !path_parameter_name(name) || !parameters.insert(name.to_owned()) { + return Err(PackError); + } + rest = &after[end + 2..]; + } + if rest.contains("}}") || rest.contains('{') || rest.contains('}') { + return Err(PackError); + } + Ok(parameters) +} + +fn validate_provider_path(path: &str) -> Result<(), PackError> { + if path.is_empty() + || path.len() > 2_048 + || !path.starts_with('/') + || path.starts_with("//") + || path.contains('?') + || path.contains('#') + || path.contains("\\") + || path.bytes().any(|byte| byte.is_ascii_control()) + || path.split('/').any(|segment| matches!(segment, "." | "..")) + { + return Err(PackError); + } + // Also validates the complete placeholder grammar. + let mut rest = path; + while let Some(start) = rest.find("{{") { + if rest[..start].contains('{') || rest[..start].contains('}') { + return Err(PackError); + } + let after = &rest[start + 2..]; + let Some(end) = after.find("}}") else { + return Err(PackError); + }; + if !path_parameter_name(&after[..end]) { + return Err(PackError); + } + rest = &after[end + 2..]; + } + if rest.contains("}}") || rest.contains('{') || rest.contains('}') { + return Err(PackError); + } + Ok(()) +} + +fn relative_pack_path(value: &str) -> bool { + !value.is_empty() + && value.len() <= 512 + && !value.contains('\\') + && Path::new(value) + .components() + .all(|component| matches!(component, Component::Normal(_))) +} + +fn function_name(value: &str) -> bool { + let mut bytes = value.bytes(); + bytes + .next() + .is_some_and(|byte| byte.is_ascii_alphabetic() || byte == b'_') + && value.len() <= 128 + && bytes.all(|byte| byte.is_ascii_alphanumeric() || byte == b'_') +} + +fn path_parameter_name(value: &str) -> bool { + let mut bytes = value.bytes(); + bytes.next().is_some_and(|byte| byte.is_ascii_lowercase()) + && value.len() <= 64 + && bytes.all(|byte| byte.is_ascii_alphanumeric()) +} + +fn local_id(value: &str) -> bool { + !value.is_empty() + && value.len() <= 128 + && value + .bytes() + .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'-') + && !value.starts_with('-') + && !value.ends_with('-') +} diff --git a/crates/registry-adapter/src/payments/provider_mapping.rs b/crates/registry-adapter/src/payments/provider_mapping.rs new file mode 100644 index 0000000000..eaed3d6f1c --- /dev/null +++ b/crates/registry-adapter/src/payments/provider_mapping.rs @@ -0,0 +1,1010 @@ +// SPDX-License-Identifier: Apache-2.0 +//! Pure provider-wire mappings for the fixed-role payment HTTP connector. +//! +//! Pack scripts are reviewed, digest-pinned implementation code. They receive +//! plain payment intent, non-secret settings and retained acceptance data, and +//! return closed data shapes. They never receive an origin or credential and +//! cannot select a method, endpoint role, retry policy, or additional effect. + +use std::collections::{BTreeMap, BTreeSet}; +use std::time::{Duration, Instant}; + +use http::{HeaderName, HeaderValue}; +use registry_adapter_core::RhaiExpression; +use registry_platform_script::rhai::{ + build_engine, call_with_fresh_scope, classify_failure, compile_entrypoint, + entrypoint_parameters, RhaiBaseEngine, RhaiCompileError, RhaiFailureCategory, RhaiLimits, + RhaiProfile, +}; +use rhai::{Dynamic, EvalAltResult, AST}; +use serde::{Deserialize, Serialize}; +use serde_json::Value; + +use super::pack::{ + provider_path_parameters, ConnectorKind, PaymentMappingCall, PaymentOperationMapping, + PaymentProviderPack, ProviderPackPin, +}; + +const MAXIMUM_SCRIPT_SOURCE_BYTES: usize = 65_536; +const MAXIMUM_INPUT_BYTES: usize = 65_536; +const MAXIMUM_REQUEST_BODY_BYTES: usize = 65_536; +const MAXIMUM_SCRIPT_OUTPUT_BYTES: usize = 131_072; +const MAXIMUM_REFERENCES: usize = 16; +const MAXIMUM_PARTIES: usize = 16; +const MAXIMUM_REQUEST_MEMBERS: usize = 32; +const MAXIMUM_TEXT_BYTES: usize = 512; +const MAXIMUM_MAPPING_PROGRAMS: usize = 32; +const CALL_DEADLINE: Duration = Duration::from_secs(2); + +const SCRIPT_PROFILE: RhaiProfile = RhaiProfile { + limits: RhaiLimits { + operations: 100_000, + call_levels: 32, + expression_depth: 64, + modules: 0, + string_bytes: 262_144, + array_items: 1_024, + map_entries: 1_024, + }, + base: RhaiBaseEngine::Deterministic, + disabled_symbols: &["import", "export", "eval", "print", "debug"], + allow_anonymous_fn: false, + maximum_source_bytes: MAXIMUM_SCRIPT_SOURCE_BYTES, +}; + +/// The four endpoint roles the host may bind. A script cannot create another +/// role or change its HTTP method. +#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize, Deserialize)] +#[serde(rename_all = "kebab-case")] +pub enum PaymentEndpointRole { + CollectionSubmit, + CollectionStatus, + DisbursementSubmit, + DisbursementStatus, +} + +impl PaymentEndpointRole { + #[must_use] + pub const fn method(self) -> PaymentHttpMethod { + match self { + Self::CollectionSubmit | Self::DisbursementSubmit => PaymentHttpMethod::Post, + Self::CollectionStatus | Self::DisbursementStatus => PaymentHttpMethod::Get, + } + } + + #[must_use] + pub const fn is_submit(self) -> bool { + matches!(self, Self::CollectionSubmit | Self::DisbursementSubmit) + } +} + +#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "UPPERCASE")] +pub enum PaymentHttpMethod { + Get, + Post, +} + +/// The exact non-secret request plan produced before transport credential +/// injection. Its role fixes the endpoint and its method fixes mutation +/// behavior. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct PreparedProviderRequest { + /// Exact pack identity. Its digest covers the script inventory and every + /// operation entrypoint used to produce this request. + pub provider_pack: ProviderPackPin, + pub role: PaymentEndpointRole, + pub method: PaymentHttpMethod, + pub path: String, + pub query: BTreeMap, + pub headers: BTreeMap, + /// Exact RFC 8785 JSON bytes to persist before dispatch and send without + /// evaluating the mapping again. Credentials are injected later. + pub body: Option>, +} + +impl PreparedProviderRequest { + /// Revalidate a retained request before dispatch. The expected role and + /// pack come from the enclosing attempt, not from the serialized request. + /// Failures never include retained values. This checks the closed request + /// shape; the caller remains responsible for authenticating the enclosing + /// attempt and binding its intent to these retained bytes. + pub fn validate_restored( + &self, + expected_role: PaymentEndpointRole, + expected_pack: &ProviderPackPin, + ) -> Result<(), PaymentMappingError> { + self.validate_integrity(expected_role, expected_pack) + .map_err(|_| PaymentMappingError::RestoredRequestInvalid) + } + + fn validate_integrity( + &self, + expected_role: PaymentEndpointRole, + expected_pack: &ProviderPackPin, + ) -> Result<(), PaymentMappingError> { + if self.role != expected_role + || self.method != expected_role.method() + || &self.provider_pack != expected_pack + || self.query.len() > MAXIMUM_REQUEST_MEMBERS + || self.headers.len() > MAXIMUM_REQUEST_MEMBERS + || !valid_final_path(&self.path) + { + return Err(PaymentMappingError::OutputInvalid); + } + validate_pairs(&self.query, 128, 2_048)?; + if validate_headers(self.headers.clone())? != self.headers { + return Err(PaymentMappingError::OutputInvalid); + } + match (self.method, self.body.as_deref()) { + (PaymentHttpMethod::Post, Some(body)) => validate_canonical_body(body), + (PaymentHttpMethod::Get, None) => Ok(()), + _ => Err(PaymentMappingError::OutputInvalid), + } + } +} + +/// The only provider response material exposed to a response mapping. The raw +/// body is retained until the mapping boundary so JSON number spellings are +/// not rounded through a host floating-point representation. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ProviderHttpResponse { + pub status: u16, + pub body: Vec, +} + +/// Provider acknowledgement retained for a later status request. Reference +/// names are provider-profile data, while correlation remains host-owned. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct ProviderAcceptance { + pub correlation_id: String, + pub references: BTreeMap, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "kebab-case")] +pub enum ProviderObservationState { + Pending, + ProviderRejected, + ProviderConfirmed, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct ProviderObservedMoney { + /// Canonical decimal digits. A response script must normalize the + /// provider's exact amount representation into minor units without using + /// floating-point arithmetic. + pub minor_units: String, + pub currency: String, + pub scale: u8, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct ProviderObservedParty { + pub role: ProviderPartyRole, + pub key: String, + pub value: String, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "kebab-case")] +pub enum ProviderPartyRole { + Payer, + Funding, + Recipient, +} + +/// A provider observation, deliberately not a paid, settled, or credited +/// result. The payment host decides whether the exact retained intent matches. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct ProviderObservation { + pub correlation_id: String, + pub provider_reference: String, + pub state: ProviderObservationState, + pub money: ProviderObservedMoney, + pub parties: Vec, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum MappedProviderResponse { + Acceptance(ProviderAcceptance), + Observation(ProviderObservation), +} + +/// Value-free failures. Script text, input, provider content and credentials +/// never enter an error or log boundary through this API. +#[derive(Clone, Copy, Debug, Eq, PartialEq, thiserror::Error)] +pub enum PaymentMappingError { + #[error("the payment provider pack does not carry a valid pure mapping")] + Pack, + #[error("a pinned payment provider script is unavailable")] + ArtifactUnavailable, + #[error("a pinned payment provider script digest does not match")] + ArtifactDigest, + #[error("a payment provider mapping does not compile under its ABI")] + ScriptCompile, + #[error("payment provider mapping input exceeds its bound")] + InputBound, + #[error("the payment provider mapping exhausted its resource bound")] + ResourceExhausted, + #[error("the payment provider mapping exceeded its deadline")] + Deadline, + #[error("the payment provider mapping failed")] + ScriptFailed, + #[error("the payment provider mapping returned an invalid closed output")] + OutputInvalid, + #[error("the retained payment provider request is invalid")] + RestoredRequestInvalid, +} + +struct CompiledCall { + path: String, + request_file: String, + request_entrypoint: String, + request: AST, + response_file: String, + response_entrypoint: String, + response: AST, +} + +/// Bounded in-memory authority for exact compiled provider packs. Retained +/// attempts select by the full immutable pin; a digest key is only the index, +/// never sufficient authority by itself. +#[derive(Clone, Default)] +pub struct PaymentMappingRegistry { + programs: BTreeMap>, +} + +impl PaymentMappingRegistry { + #[must_use] + pub fn new() -> Self { + Self::default() + } + + pub fn insert(&mut self, program: PaymentMappingProgram) -> Result<(), PaymentMappingError> { + let digest = program.provider_pack.digest.clone(); + if self.programs.contains_key(&digest) { + return Err(PaymentMappingError::Pack); + } + if self.programs.len() >= MAXIMUM_MAPPING_PROGRAMS { + return Err(PaymentMappingError::InputBound); + } + self.programs.insert(digest, std::sync::Arc::new(program)); + Ok(()) + } + + pub fn select( + &self, + pin: &ProviderPackPin, + ) -> Result, PaymentMappingError> { + self.programs + .get(&pin.digest) + .filter(|program| program.provider_pack() == pin) + .cloned() + .ok_or(PaymentMappingError::ArtifactUnavailable) + } +} + +/// One immutable program compiled from the complete digest-pinned mapping +/// closure. It contains no transport client, endpoint origin, or credential. +pub struct PaymentMappingProgram { + provider_pack: ProviderPackPin, + calls: BTreeMap, +} + +impl PaymentMappingProgram { + /// Compile all and only the scripts inventoried by `pack`. `artifacts` is + /// an in-memory authority supplied by the host, keyed by exact pack path. + pub fn compile( + pack: &PaymentProviderPack, + pack_bytes: &[u8], + artifacts: &BTreeMap>, + ) -> Result { + let decoded = + PaymentProviderPack::from_yaml(pack_bytes).map_err(|_| PaymentMappingError::Pack)?; + if &decoded != pack { + return Err(PaymentMappingError::Pack); + } + pack.validate().map_err(|_| PaymentMappingError::Pack)?; + if pack.connector != ConnectorKind::AdapterPaymentHttpV1 { + return Err(PaymentMappingError::Pack); + } + let mapping = pack.mapping.as_ref().ok_or(PaymentMappingError::Pack)?; + let inventory = mapping + .scripts + .iter() + .map(|script| (script.path.as_str(), script.digest.as_str())) + .collect::>(); + if artifacts.len() != inventory.len() + || artifacts + .keys() + .any(|path| !inventory.contains_key(path.as_str())) + { + return Err(PaymentMappingError::ArtifactUnavailable); + } + let mut sources = BTreeMap::new(); + for (path, digest) in inventory { + let bytes = artifacts + .get(path) + .ok_or(PaymentMappingError::ArtifactUnavailable)?; + if bytes.len() > MAXIMUM_SCRIPT_SOURCE_BYTES { + return Err(PaymentMappingError::ScriptCompile); + } + if registry_platform_config::sha256_uri(bytes) != digest { + return Err(PaymentMappingError::ArtifactDigest); + } + let source = + std::str::from_utf8(bytes).map_err(|_| PaymentMappingError::ScriptCompile)?; + sources.insert(path, source); + } + + let mut calls = BTreeMap::new(); + if let Some(operation) = &mapping.collection { + compile_operation( + &mut calls, + PaymentEndpointRole::CollectionSubmit, + PaymentEndpointRole::CollectionStatus, + operation, + &sources, + )?; + } + if let Some(operation) = &mapping.disbursement { + compile_operation( + &mut calls, + PaymentEndpointRole::DisbursementSubmit, + PaymentEndpointRole::DisbursementStatus, + operation, + &sources, + )?; + } + Ok(Self { + provider_pack: ProviderPackPin { + id: pack.id.clone(), + version: pack.version.clone(), + digest: registry_platform_config::sha256_uri(pack_bytes), + }, + calls, + }) + } + + /// Run the request mapping for one fixed endpoint role. + pub fn prepare( + &self, + role: PaymentEndpointRole, + intent: &Value, + settings: &Value, + acceptance: Option<&ProviderAcceptance>, + ) -> Result { + validate_context(role, intent, settings, acceptance)?; + let call = self.calls.get(&role).ok_or(PaymentMappingError::Pack)?; + let acceptance = acceptance + .map(serde_json::to_value) + .transpose() + .map_err(|_| PaymentMappingError::InputBound)? + .unwrap_or(Value::Null); + let output = run( + &call.request, + &call.request_entrypoint, + &[intent.clone(), settings.clone(), acceptance], + )?; + let mapped: MappedRequest = + serde_json::from_value(output).map_err(|_| PaymentMappingError::OutputInvalid)?; + mapped.finish(role, &call.path, &self.provider_pack) + } + + /// Run the response mapping and decode its result by endpoint role. + pub fn interpret( + &self, + role: PaymentEndpointRole, + intent: &Value, + settings: &Value, + acceptance: Option<&ProviderAcceptance>, + response: &ProviderHttpResponse, + ) -> Result { + validate_context(role, intent, settings, acceptance)?; + if !(100..=599).contains(&response.status) { + return Err(PaymentMappingError::InputBound); + } + let body = exact_provider_json(&response.body)?; + let call = self.calls.get(&role).ok_or(PaymentMappingError::Pack)?; + let acceptance = acceptance + .map(serde_json::to_value) + .transpose() + .map_err(|_| PaymentMappingError::InputBound)? + .unwrap_or(Value::Null); + let response = serde_json::json!({"status": response.status, "body": body}); + let output = run_bounded( + &call.response, + &call.response_entrypoint, + &[intent.clone(), settings.clone(), acceptance, response], + MAXIMUM_SCRIPT_OUTPUT_BYTES, + )?; + if role.is_submit() { + let acceptance: ProviderAcceptance = + serde_json::from_value(output).map_err(|_| PaymentMappingError::OutputInvalid)?; + acceptance.validate()?; + Ok(MappedProviderResponse::Acceptance(acceptance)) + } else { + let observation: ProviderObservation = + serde_json::from_value(output).map_err(|_| PaymentMappingError::OutputInvalid)?; + observation.validate(role)?; + Ok(MappedProviderResponse::Observation(observation)) + } + } + + /// The exact script identity used for one role, for attempt and audit + /// correlation without exposing the script source. + #[must_use] + pub fn script_identity(&self, role: PaymentEndpointRole) -> Option<(&str, &str)> { + self.calls.get(&role).map(|call| { + // The pair names request and response compilation units. A caller + // already retains the pack digest as the authority over both. + (call.request_file.as_str(), call.response_file.as_str()) + }) + } + + #[must_use] + pub fn provider_pack(&self) -> &ProviderPackPin { + &self.provider_pack + } +} + +fn compile_operation( + calls: &mut BTreeMap, + submit_role: PaymentEndpointRole, + status_role: PaymentEndpointRole, + operation: &PaymentOperationMapping, + sources: &BTreeMap<&str, &str>, +) -> Result<(), PaymentMappingError> { + calls.insert(submit_role, compile_call(&operation.submit, sources)?); + if let Some(status) = &operation.status { + calls.insert(status_role, compile_call(status, sources)?); + } + Ok(()) +} + +fn compile_call( + call: &PaymentMappingCall, + sources: &BTreeMap<&str, &str>, +) -> Result { + let request = compile_expression( + &call.request, + sources, + &["intent", "settings", "acceptance"], + )?; + let response = compile_expression( + &call.response, + sources, + &["intent", "settings", "acceptance", "response"], + )?; + Ok(CompiledCall { + path: call.path.clone(), + request_file: call.request.file.clone(), + request_entrypoint: call.request.entrypoint.clone(), + request, + response_file: call.response.file.clone(), + response_entrypoint: call.response.entrypoint.clone(), + response, + }) +} + +fn compile_expression( + expression: &RhaiExpression, + sources: &BTreeMap<&str, &str>, + parameters: &[&str], +) -> Result { + let source = sources + .get(expression.file.as_str()) + .ok_or(PaymentMappingError::ArtifactUnavailable)?; + let ast = compile_entrypoint( + &SCRIPT_PROFILE, + source, + &expression.entrypoint, + &[parameters.len()], + ) + .map_err(|error| match error { + RhaiCompileError::SourceBound + | RhaiCompileError::Parse(_) + | RhaiCompileError::Entrypoint => PaymentMappingError::ScriptCompile, + })?; + if entrypoint_parameters(&ast, &expression.entrypoint) != parameters { + return Err(PaymentMappingError::ScriptCompile); + } + Ok(ast) +} + +fn validate_context( + role: PaymentEndpointRole, + intent: &Value, + settings: &Value, + acceptance: Option<&ProviderAcceptance>, +) -> Result<(), PaymentMappingError> { + bounded_json(intent, MAXIMUM_INPUT_BYTES)?; + bounded_json(settings, MAXIMUM_INPUT_BYTES)?; + match (role.is_submit(), acceptance) { + (true, None) => Ok(()), + (false, Some(acceptance)) => acceptance.validate(), + _ => Err(PaymentMappingError::InputBound), + } +} + +fn run(ast: &AST, entrypoint: &str, arguments: &[Value]) -> Result { + run_bounded(ast, entrypoint, arguments, MAXIMUM_INPUT_BYTES) +} + +fn run_bounded( + ast: &AST, + entrypoint: &str, + arguments: &[Value], + maximum_argument_bytes: usize, +) -> Result { + for argument in arguments { + bounded_json(argument, maximum_argument_bytes)?; + } + let dynamic = arguments + .iter() + .map(rhai::serde::to_dynamic) + .collect::, _>>() + .map_err(|_| PaymentMappingError::InputBound)?; + let deadline = Instant::now() + CALL_DEADLINE; + let engine = build_engine(&SCRIPT_PROFILE, Some(deadline), |_| {}); + let result = match dynamic.as_slice() { + [one, two, three] => call_with_fresh_scope( + &engine, + ast, + entrypoint, + (one.clone(), two.clone(), three.clone()), + ), + [one, two, three, four] => call_with_fresh_scope( + &engine, + ast, + entrypoint, + (one.clone(), two.clone(), three.clone(), four.clone()), + ), + _ => return Err(PaymentMappingError::ScriptFailed), + } + .map_err(|error| script_failure(&error, deadline))?; + let output = rhai::serde::from_dynamic::(&result) + .map_err(|_| PaymentMappingError::OutputInvalid)?; + bounded_json(&output, MAXIMUM_SCRIPT_OUTPUT_BYTES)?; + Ok(output) +} + +/// Validate one bounded JSON document, then expose its body numbers to Rhai as +/// strings containing their exact source lexemes. The validation remains with +/// the shared duplicate-rejecting parser. This scanner only finds already +/// validated number tokens, and does not implement or relax JSON syntax. +fn exact_provider_json(bytes: &[u8]) -> Result { + if bytes.len() > MAXIMUM_INPUT_BYTES { + return Err(PaymentMappingError::InputBound); + } + registry_platform_canonical_json::parse_json_preserving_integers(bytes) + .map_err(|_| PaymentMappingError::InputBound)?; + + let mut quoted = Vec::with_capacity(bytes.len()); + let mut index = 0; + let mut in_string = false; + let mut escaped = false; + while index < bytes.len() { + let byte = bytes[index]; + if in_string { + quoted.push(byte); + if escaped { + escaped = false; + } else if byte == b'\\' { + escaped = true; + } else if byte == b'"' { + in_string = false; + } + index += 1; + continue; + } + if byte == b'"' { + quoted.push(byte); + in_string = true; + index += 1; + continue; + } + if byte.is_ascii_digit() + || (byte == b'-' && bytes.get(index + 1).is_some_and(u8::is_ascii_digit)) + { + quoted.push(b'"'); + while index < bytes.len() + && matches!(bytes[index], b'0'..=b'9' | b'-' | b'+' | b'.' | b'e' | b'E') + { + quoted.push(bytes[index]); + index += 1; + } + quoted.push(b'"'); + continue; + } + quoted.push(byte); + index += 1; + } + if quoted.len() > MAXIMUM_SCRIPT_OUTPUT_BYTES { + return Err(PaymentMappingError::InputBound); + } + registry_platform_canonical_json::parse_json_preserving_integers("ed) + .map_err(|_| PaymentMappingError::InputBound) +} + +fn script_failure(error: &EvalAltResult, deadline: Instant) -> PaymentMappingError { + if matches!(error, EvalAltResult::ErrorTerminated(..)) && Instant::now() >= deadline { + return PaymentMappingError::Deadline; + } + match classify_failure(error) { + RhaiFailureCategory::ResourceExhausted => PaymentMappingError::ResourceExhausted, + RhaiFailureCategory::Other => PaymentMappingError::ScriptFailed, + } +} + +fn bounded_json(value: &Value, maximum: usize) -> Result<(), PaymentMappingError> { + let encoded = serde_json::to_vec(value).map_err(|_| PaymentMappingError::InputBound)?; + if encoded.len() > maximum { + Err(PaymentMappingError::InputBound) + } else { + Ok(()) + } +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct MappedRequest { + #[serde(default)] + path_parameters: BTreeMap, + #[serde(default)] + query: BTreeMap, + #[serde(default)] + headers: BTreeMap, + #[serde(default)] + body: Option, +} + +impl MappedRequest { + fn finish( + self, + role: PaymentEndpointRole, + template: &str, + provider_pack: &ProviderPackPin, + ) -> Result { + if self.path_parameters.len() > MAXIMUM_REQUEST_MEMBERS + || self.query.len() > MAXIMUM_REQUEST_MEMBERS + || self.headers.len() > MAXIMUM_REQUEST_MEMBERS + { + return Err(PaymentMappingError::OutputInvalid); + } + let expected = provider_path_parameters(template).map_err(|_| PaymentMappingError::Pack)?; + if expected + != self + .path_parameters + .keys() + .cloned() + .collect::>() + { + return Err(PaymentMappingError::OutputInvalid); + } + let mut path = template.to_owned(); + for (name, value) in self.path_parameters { + if value.is_empty() || value.len() > MAXIMUM_TEXT_BYTES { + return Err(PaymentMappingError::OutputInvalid); + } + path = path.replace(&format!("{{{{{name}}}}}"), &encode_path_segment(&value)); + } + if !valid_final_path(&path) { + return Err(PaymentMappingError::OutputInvalid); + } + validate_pairs(&self.query, 128, 2_048)?; + let headers = validate_headers(self.headers)?; + let body = match (role.method(), self.body) { + (PaymentHttpMethod::Post, Some(body)) => { + bounded_json(&body, MAXIMUM_REQUEST_BODY_BYTES)?; + let canonical = registry_platform_canonical_json::canonicalize_json(&body) + .map_err(|_| PaymentMappingError::OutputInvalid)?; + if canonical.len() > MAXIMUM_REQUEST_BODY_BYTES { + return Err(PaymentMappingError::OutputInvalid); + } + Some(canonical) + } + (PaymentHttpMethod::Get, None) => None, + _ => return Err(PaymentMappingError::OutputInvalid), + }; + let request = PreparedProviderRequest { + provider_pack: provider_pack.clone(), + role, + method: role.method(), + path, + query: self.query, + headers, + body, + }; + request.validate_integrity(role, provider_pack)?; + Ok(request) + } +} + +fn valid_final_path(path: &str) -> bool { + path.len() <= 4_096 + && provider_path_parameters(path).is_ok_and(|parameters| parameters.is_empty()) +} + +fn validate_canonical_body(body: &[u8]) -> Result<(), PaymentMappingError> { + if body.len() > MAXIMUM_REQUEST_BODY_BYTES { + return Err(PaymentMappingError::OutputInvalid); + } + let value = registry_platform_canonical_json::parse_json_strict(body) + .map_err(|_| PaymentMappingError::OutputInvalid)?; + let canonical = registry_platform_canonical_json::canonicalize_json(&value) + .map_err(|_| PaymentMappingError::OutputInvalid)?; + if canonical.as_slice() == body { + Ok(()) + } else { + Err(PaymentMappingError::OutputInvalid) + } +} + +fn validate_pairs( + pairs: &BTreeMap, + maximum_name: usize, + maximum_value: usize, +) -> Result<(), PaymentMappingError> { + if pairs.iter().any(|(name, value)| { + name.is_empty() + || name.len() > maximum_name + || value.len() > maximum_value + || name.bytes().any(|byte| byte.is_ascii_control()) + || value.bytes().any(|byte| byte.is_ascii_control()) + }) { + Err(PaymentMappingError::OutputInvalid) + } else { + Ok(()) + } +} + +fn validate_headers( + headers: BTreeMap, +) -> Result, PaymentMappingError> { + let mut admitted = BTreeMap::new(); + for (name, value) in headers { + let name = HeaderName::from_bytes(name.as_bytes()) + .map_err(|_| PaymentMappingError::OutputInvalid)?; + let lowered = name.as_str(); + if forbidden_header(lowered) + || HeaderValue::from_str(&value).is_err() + || value.len() > 4_096 + || admitted.insert(lowered.to_owned(), value).is_some() + { + return Err(PaymentMappingError::OutputInvalid); + } + } + Ok(admitted) +} + +fn forbidden_header(name: &str) -> bool { + matches!( + name, + "authorization" + | "proxy-authorization" + | "cookie" + | "set-cookie" + | "host" + | "content-length" + | "transfer-encoding" + | "connection" + | "keep-alive" + | "proxy-connection" + | "te" + | "trailer" + | "upgrade" + | "x-api-key" + | "api-key" + | "x-auth-token" + | "x-access-token" + | "traceparent" + | "tracestate" + | "forwarded" + | "x-forwarded-for" + | "x-forwarded-host" + | "x-forwarded-proto" + | "x-http-method-override" + | "x-method-override" + | "x-original-url" + | "x-rewrite-url" + ) +} + +fn encode_path_segment(value: &str) -> String { + const HEX: &[u8; 16] = b"0123456789ABCDEF"; + let mut encoded = String::with_capacity(value.len()); + for byte in value.bytes() { + if byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'.' | b'_' | b'~') { + encoded.push(char::from(byte)); + } else { + encoded.push('%'); + encoded.push(char::from(HEX[usize::from(byte >> 4)])); + encoded.push(char::from(HEX[usize::from(byte & 0x0f)])); + } + } + encoded +} + +impl ProviderAcceptance { + fn validate(&self) -> Result<(), PaymentMappingError> { + if !bounded_text(&self.correlation_id, MAXIMUM_TEXT_BYTES) + || self.references.is_empty() + || self.references.len() > MAXIMUM_REFERENCES + || self.references.iter().any(|(key, value)| { + !bounded_identifier(key, 64) || !bounded_text(value, MAXIMUM_TEXT_BYTES) + }) + { + Err(PaymentMappingError::OutputInvalid) + } else { + Ok(()) + } + } +} + +impl ProviderObservation { + fn validate(&self, role: PaymentEndpointRole) -> Result<(), PaymentMappingError> { + let payer_count = self + .parties + .iter() + .filter(|party| party.role == ProviderPartyRole::Payer) + .count(); + let funding_count = self + .parties + .iter() + .filter(|party| party.role == ProviderPartyRole::Funding) + .count(); + let recipient_count = self + .parties + .iter() + .filter(|party| party.role == ProviderPartyRole::Recipient) + .count(); + let distinct_party_keys = self + .parties + .iter() + .map(|party| party.key.as_str()) + .collect::>() + .len() + == self.parties.len(); + let roles_match = match role { + PaymentEndpointRole::CollectionStatus => { + payer_count == 2 && funding_count == 0 && recipient_count == 0 + } + PaymentEndpointRole::DisbursementStatus => { + payer_count == 0 && funding_count == 1 && recipient_count == 1 + } + PaymentEndpointRole::CollectionSubmit | PaymentEndpointRole::DisbursementSubmit => { + false + } + }; + if !bounded_text(&self.correlation_id, MAXIMUM_TEXT_BYTES) + || !bounded_text(&self.provider_reference, MAXIMUM_TEXT_BYTES) + || !valid_minor_units(&self.money.minor_units) + || self.money.currency.len() != 3 + || !self + .money + .currency + .bytes() + .all(|byte| byte.is_ascii_uppercase()) + || self.money.scale > 6 + || !roles_match + || !distinct_party_keys + || self.parties.len() > MAXIMUM_PARTIES + || self.parties.iter().any(|party| { + !bounded_text(&party.key, 128) || !bounded_text(&party.value, MAXIMUM_TEXT_BYTES) + }) + { + Err(PaymentMappingError::OutputInvalid) + } else { + Ok(()) + } + } +} + +fn valid_minor_units(value: &str) -> bool { + !value.is_empty() + && value.len() <= 20 + && value.bytes().all(|byte| byte.is_ascii_digit()) + && (value.len() == 1 || !value.starts_with('0')) + && value + .parse::() + .is_ok_and(|minor_units| minor_units > 0) +} + +fn bounded_text(value: &str, maximum: usize) -> bool { + !value.is_empty() + && value.len() <= maximum + && !value.bytes().any(|byte| byte.is_ascii_control()) +} + +fn bounded_identifier(value: &str, maximum: usize) -> bool { + bounded_text(value, maximum) + && value + .bytes() + .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.')) +} + +#[cfg(test)] +mod registry_tests { + use super::*; + + #[test] + fn registry_holds_missing_old_pack_and_selects_each_exact_retained_pin() { + let pin_a = pin("provider-a", 'a'); + let pin_b = pin("provider-b", 'b'); + let mut registry = PaymentMappingRegistry::default(); + + assert!(matches!( + registry.select(&pin_a), + Err(PaymentMappingError::ArtifactUnavailable) + )); + registry.insert(program(pin_b.clone())).unwrap(); + assert_eq!(registry.select(&pin_b).unwrap().provider_pack(), &pin_b); + assert!(matches!( + registry.select(&pin_a), + Err(PaymentMappingError::ArtifactUnavailable) + )); + + registry.insert(program(pin_a.clone())).unwrap(); + assert_eq!(registry.select(&pin_a).unwrap().provider_pack(), &pin_a); + assert_eq!(registry.select(&pin_b).unwrap().provider_pack(), &pin_b); + + let forged = ProviderPackPin { + id: "forged-provider".to_owned(), + version: pin_a.version.clone(), + digest: pin_a.digest.clone(), + }; + assert!(matches!( + registry.select(&forged), + Err(PaymentMappingError::ArtifactUnavailable) + )); + assert!(matches!( + registry.insert(program(pin_a)), + Err(PaymentMappingError::Pack) + )); + } + + #[test] + fn registry_refuses_more_than_the_bounded_pack_set() { + let mut registry = PaymentMappingRegistry::new(); + for index in 0..MAXIMUM_MAPPING_PROGRAMS { + let digest = format!("sha256:{index:064x}"); + registry + .insert(program(ProviderPackPin { + id: format!("provider-{index}"), + version: "1".to_owned(), + digest, + })) + .unwrap(); + } + assert!(matches!( + registry.insert(program(ProviderPackPin { + id: "one-too-many".to_owned(), + version: "1".to_owned(), + digest: format!("sha256:{}", "f".repeat(64)), + })), + Err(PaymentMappingError::InputBound) + )); + } + + fn program(provider_pack: ProviderPackPin) -> PaymentMappingProgram { + PaymentMappingProgram { + provider_pack, + calls: BTreeMap::new(), + } + } + + fn pin(id: &str, digest: char) -> ProviderPackPin { + ProviderPackPin { + id: id.to_owned(), + version: "1".to_owned(), + digest: format!("sha256:{}", digest.to_string().repeat(64)), + } + } +} diff --git a/crates/registry-adapter/src/payments/service.rs b/crates/registry-adapter/src/payments/service.rs index f2f0a6cdf3..25a5348bc8 100644 --- a/crates/registry-adapter/src/payments/service.rs +++ b/crates/registry-adapter/src/payments/service.rs @@ -1,48 +1,112 @@ // SPDX-License-Identifier: Apache-2.0 //! Explicitly initiated collection, observation, and receipt operations. +//! Mifos PH-EE supports collection request and status only: its provider +//! completion observation cannot authorize the BReg paid receipt Action. use super::{ - config::{PaymentBinding, PaymentConnection, PaymentsConfig}, - model::{digest, Attempt}, + config::{CollectionProvider, PaymentBinding, PaymentConnection, PaymentsConfig}, + model::{digest, Attempt, BillSnapshot, CollectionProviderCommand, HttpCollectionCommand}, + provider_mapping::{ + MappedProviderResponse, PaymentEndpointRole, PaymentHttpMethod, PaymentMappingProgram, + PaymentMappingRegistry, PreparedProviderRequest, ProviderAcceptance, ProviderHttpResponse, + ProviderObservationState, ProviderPartyRole, + }, registry::{binding_inputs, BillState, RegistryPort}, store::PaymentStore, }; use crate::serve::Caller; use async_trait::async_trait; +use registry_payment_mifos_connector::{ + CollectionAccepted as MifosAccepted, ConnectorError as MifosError, MifosClient, + PaymentState as MifosState, RequestAuth, SubmissionState, +}; use registry_payment_protocol::{ CollectionAccepted, CollectionState, CollectionStatus, PaymentProblemCode as Error, RegistryReceipt, RequestCollection, }; -use registry_payment_simulator_connector::{ - ConnectorError, Observation, ProviderCommand, SimulatorClient, -}; +use registry_payment_simulator_connector::{ConnectorError, Observation, SimulatorClient}; use registry_platform_config::SecretResolver; use registry_platform_httputil::client::BearerToken; -use std::sync::Arc; +use registry_platform_httputil::{read_bounded, validate_response_headers, ServiceBaseUrl}; +use std::{future::Future, pin::Pin, sync::Arc, time::Duration}; use tokio::sync::Semaphore; use uuid::Uuid; #[async_trait] pub trait ProviderPort: Send + Sync { + fn prepare( + &self, + binding: &PaymentBinding, + bill: &BillSnapshot, + ) -> Result { + bill.provider_command(binding) + .map_err(|_| ConnectorError::Configuration) + } + + /// Complete every local step needed for a mutation before custody records + /// its one-send grant. Compiled connectors retain the existing direct seam; + /// generic live HTTP returns a fully built request whose first poll is the + /// first network I/O. + async fn preflight_submit( + &self, + _binding: &PaymentBinding, + _command: &CollectionProviderCommand, + ) -> Result { + Ok(ProviderPreflight::Direct) + } + async fn submit( &self, binding: &PaymentBinding, - command: &ProviderCommand, - ) -> Result; + command: &CollectionProviderCommand, + ) -> Result; async fn observe( &self, binding: &PaymentBinding, - command: &ProviderCommand, + command: &CollectionProviderCommand, transfer: &str, + acceptance: Option<&ProviderAcceptance>, ) -> Result; } +pub enum ProviderPreflight { + Direct, + Prepared(PreparedProviderSend), +} + +pub struct PreparedProviderSend { + send: Pin> + Send>>, +} + +impl PreparedProviderSend { + pub fn new( + send: impl Future> + Send + 'static, + ) -> Self { + Self { + send: Box::pin(send), + } + } + + pub async fn send(self) -> Result { + self.send.await + } +} + +pub struct ProviderSubmission { + pub transfer_id: String, + pub acceptance: Option, +} + pub struct SyntheticProvider { resolver: Arc, + mappings: Option>, } impl SyntheticProvider { - pub fn new(resolver: Arc) -> Self { - Self { resolver } + pub fn new( + resolver: Arc, + mappings: Option>, + ) -> Self { + Self { resolver, mappings } } fn token(&self, binding: &PaymentBinding) -> Result { let secret = self @@ -53,27 +117,468 @@ impl SyntheticProvider { std::str::from_utf8(secret.expose_secret()).map_err(|_| ConnectorError::Unavailable)?; BearerToken::new(token.to_owned()).map_err(|_| ConnectorError::Unavailable) } + + fn mapping( + &self, + binding: &PaymentBinding, + ) -> Result, ConnectorError> { + let pin = binding + .provider_pack + .as_ref() + .ok_or(ConnectorError::Configuration)?; + self.mappings + .as_ref() + .ok_or(ConnectorError::Configuration)? + .select(pin) + .map_err(|_| ConnectorError::Configuration) + } } #[async_trait] impl ProviderPort for SyntheticProvider { + fn prepare( + &self, + binding: &PaymentBinding, + bill: &BillSnapshot, + ) -> Result { + let CollectionProvider::Http { settings, .. } = &binding.provider else { + return bill + .provider_command(binding) + .map_err(|_| ConnectorError::Configuration); + }; + let mapping = self.mapping(binding)?; + let intent = bill + .http_intent(binding) + .map_err(|_| ConnectorError::Configuration)?; + let prepared_submit = mapping + .prepare( + PaymentEndpointRole::CollectionSubmit, + &intent, + settings, + None, + ) + .map_err(|_| ConnectorError::Configuration)?; + Ok(CollectionProviderCommand::Http(HttpCollectionCommand { + intent, + prepared_submit, + })) + } + + async fn preflight_submit( + &self, + binding: &PaymentBinding, + command: &CollectionProviderCommand, + ) -> Result { + let ( + CollectionProvider::Http { + submit_base_url, + settings, + .. + }, + CollectionProviderCommand::Http(command), + ) = (&binding.provider, command) + else { + return Ok(ProviderPreflight::Direct); + }; + let provider_pack = binding + .provider_pack + .as_ref() + .ok_or(ConnectorError::Configuration)?; + command + .prepared_submit + .validate_restored(PaymentEndpointRole::CollectionSubmit, provider_pack) + .map_err(|_| ConnectorError::Configuration)?; + let base = ServiceBaseUrl::new( + url::Url::parse(submit_base_url).map_err(|_| ConnectorError::Configuration)?, + ) + .map_err(|_| ConnectorError::Configuration)?; + let path = command + .prepared_submit + .path + .strip_prefix('/') + .ok_or(ConnectorError::Configuration)?; + let mut url = base.join(path).map_err(|_| ConnectorError::Configuration)?; + url.query_pairs_mut() + .extend_pairs(&command.prepared_submit.query); + let token = self.token(binding)?; + let client = registry_platform_httputil::client::build_client( + registry_platform_httputil::client::OutboundOptions { + request_timeout: Duration::from_secs(15), + connect_timeout: Duration::from_secs(5), + user_agent: Some("registry-adapter-payment-http/v1"), + trusted_root_certificates: None, + }, + ) + .map_err(|_| ConnectorError::Configuration)?; + let mut builder = client.post(url); + for (name, value) in &command.prepared_submit.headers { + builder = builder.header(name, value); + } + let body = command + .prepared_submit + .body + .as_ref() + .ok_or(ConnectorError::Configuration)?; + let request = builder + .header( + http::header::AUTHORIZATION, + token.authorization_header_value(), + ) + .header(http::header::CONTENT_TYPE, "application/json") + .body(body.clone()) + .build() + .map_err(|_| ConnectorError::Configuration)?; + let mapping = self.mapping(binding)?; + let intent = command.intent.clone(); + let settings = settings.clone(); + Ok(ProviderPreflight::Prepared(PreparedProviderSend::new( + async move { + let response = client + .execute(request) + .await + .map_err(|_| ConnectorError::Unknown)?; + validate_response_headers(response.headers()) + .map_err(|_| ConnectorError::Unknown)?; + let status = response.status().as_u16(); + let body = read_bounded(response, 131_072) + .await + .map_err(|_| ConnectorError::Unknown)?; + let mapped = mapping + .interpret( + PaymentEndpointRole::CollectionSubmit, + &intent, + &settings, + None, + &ProviderHttpResponse { status, body }, + ) + .map_err(|_| ConnectorError::Unknown)?; + let MappedProviderResponse::Acceptance(acceptance) = mapped else { + return Err(ConnectorError::Unknown); + }; + if intent + .get("correlationId") + .and_then(serde_json::Value::as_str) + != Some(acceptance.correlation_id.as_str()) + { + return Err(ConnectorError::Unknown); + } + let transfer_id = acceptance + .references + .values() + .next() + .cloned() + .ok_or(ConnectorError::Unknown)?; + Ok(ProviderSubmission { + transfer_id, + acceptance: Some(acceptance), + }) + }, + ))) + } + async fn submit( &self, binding: &PaymentBinding, - command: &ProviderCommand, - ) -> Result { - SimulatorClient::new(binding.provider.clone())? - .submit(command, &self.token(binding)?) - .await + command: &CollectionProviderCommand, + ) -> Result { + match (&binding.provider, command) { + ( + CollectionProvider::Simulator { + connection: provider, + }, + CollectionProviderCommand::Simulator(command), + ) => SimulatorClient::new(provider.clone())? + .submit(command, &self.token(binding)?) + .await + .map(|transfer_id| ProviderSubmission { + transfer_id, + acceptance: None, + }), + ( + CollectionProvider::Mifos { + connection: provider, + .. + }, + CollectionProviderCommand::Mifos(command), + ) => { + let token = self.token(binding)?; + let auth = RequestAuth::bearer(&token); + MifosClient::new(provider.clone()) + .map_err(map_mifos_error)? + .submit_collection(command, &auth) + .await + .map(|accepted| ProviderSubmission { + transfer_id: accepted.transaction_id, + acceptance: None, + }) + .map_err(map_mifos_error) + } + (CollectionProvider::Http { .. }, CollectionProviderCommand::Http(_)) => { + Err(ConnectorError::Configuration) + } + _ => Err(ConnectorError::Configuration), + } } async fn observe( &self, binding: &PaymentBinding, - command: &ProviderCommand, + command: &CollectionProviderCommand, transfer: &str, + acceptance: Option<&ProviderAcceptance>, ) -> Result { - SimulatorClient::new(binding.provider.clone())? - .observe(command, transfer, &self.token(binding)?) - .await + match (&binding.provider, command) { + ( + CollectionProvider::Simulator { + connection: provider, + }, + CollectionProviderCommand::Simulator(command), + ) => { + SimulatorClient::new(provider.clone())? + .observe(command, transfer, &self.token(binding)?) + .await + } + ( + CollectionProvider::Mifos { + connection: provider, + .. + }, + CollectionProviderCommand::Mifos(command), + ) => { + let token = self.token(binding)?; + let auth = RequestAuth::bearer(&token); + let observed = MifosClient::new(provider.clone()) + .map_err(map_mifos_error)? + .collection_status( + command, + &MifosAccepted { + transaction_id: transfer.to_owned(), + state: SubmissionState::Accepted, + }, + &auth, + ) + .await + .map_err(map_mifos_error)?; + let state = match observed.state { + MifosState::Pending => CollectionState::Pending, + MifosState::ProviderConfirmed => CollectionState::Confirmed, + MifosState::Failed => CollectionState::Failed, + MifosState::Unknown => CollectionState::Unknown, + }; + let observed_at = u64::try_from(time::OffsetDateTime::now_utc().unix_timestamp()) + .map_err(|_| ConnectorError::Unavailable)?; + Ok(Observation { + state, + provider_reference: (state == CollectionState::Confirmed) + .then_some(observed.transaction_id), + failure_reason: (state == CollectionState::Failed) + .then(|| "provider-reported-failure".to_owned()), + observed_at, + }) + } + ( + CollectionProvider::Http { + status_base_url, .. + }, + CollectionProviderCommand::Http(command), + ) => { + let acceptance = acceptance.ok_or(ConnectorError::Protocol)?; + if command + .intent + .get("correlationId") + .and_then(serde_json::Value::as_str) + != Some(acceptance.correlation_id.as_str()) + || !acceptance + .references + .values() + .any(|value| value == transfer) + { + return Err(ConnectorError::Protocol); + } + let mapping = self.mapping(binding)?; + let prepared = mapping + .prepare( + PaymentEndpointRole::CollectionStatus, + &command.intent, + http_settings(binding)?, + Some(acceptance), + ) + .map_err(|_| ConnectorError::Protocol)?; + let response = self + .send_prepared(status_base_url, &prepared, &self.token(binding)?) + .await?; + let mapped = mapping + .interpret( + PaymentEndpointRole::CollectionStatus, + &command.intent, + http_settings(binding)?, + Some(acceptance), + &response, + ) + .map_err(|_| ConnectorError::Protocol)?; + let MappedProviderResponse::Observation(observed) = mapped else { + return Err(ConnectorError::Protocol); + }; + validate_http_observation(binding, command, &observed)?; + let state = match observed.state { + ProviderObservationState::Pending => CollectionState::Pending, + ProviderObservationState::ProviderRejected => CollectionState::Failed, + ProviderObservationState::ProviderConfirmed => CollectionState::Confirmed, + }; + let observed_at = u64::try_from(time::OffsetDateTime::now_utc().unix_timestamp()) + .map_err(|_| ConnectorError::Unavailable)?; + Ok(Observation { + state, + provider_reference: (state == CollectionState::Confirmed) + .then_some(observed.provider_reference), + failure_reason: (state == CollectionState::Failed) + .then(|| "provider-reported-failure".to_owned()), + observed_at, + }) + } + _ => Err(ConnectorError::Configuration), + } + } +} + +impl SyntheticProvider { + async fn send_prepared( + &self, + base_url: &str, + prepared: &PreparedProviderRequest, + token: &BearerToken, + ) -> Result { + let base = ServiceBaseUrl::new( + url::Url::parse(base_url).map_err(|_| ConnectorError::Configuration)?, + ) + .map_err(|_| ConnectorError::Configuration)?; + let path = prepared + .path + .strip_prefix('/') + .ok_or(ConnectorError::Configuration)?; + let mut url = base.join(path).map_err(|_| ConnectorError::Configuration)?; + url.query_pairs_mut().extend_pairs(&prepared.query); + let client = registry_platform_httputil::client::build_client( + registry_platform_httputil::client::OutboundOptions { + request_timeout: Duration::from_secs(15), + connect_timeout: Duration::from_secs(5), + user_agent: Some("registry-adapter-payment-http/v1"), + trusted_root_certificates: None, + }, + ) + .map_err(|_| ConnectorError::Configuration)?; + let mut request = match prepared.method { + PaymentHttpMethod::Post => client.post(url), + PaymentHttpMethod::Get => client.get(url), + }; + for (name, value) in &prepared.headers { + request = request.header(name, value); + } + request = request.header( + http::header::AUTHORIZATION, + token.authorization_header_value(), + ); + if let Some(body) = &prepared.body { + request = request + .header(http::header::CONTENT_TYPE, "application/json") + .body(body.clone()); + } + let response = request.send().await.map_err(|_| { + if prepared.method == PaymentHttpMethod::Post { + ConnectorError::Unknown + } else { + ConnectorError::Unavailable + } + })?; + validate_response_headers(response.headers()).map_err(|_| { + if prepared.method == PaymentHttpMethod::Post { + ConnectorError::Unknown + } else { + ConnectorError::Protocol + } + })?; + let status = response.status().as_u16(); + let body = read_bounded(response, 131_072).await.map_err(|_| { + if prepared.method == PaymentHttpMethod::Post { + ConnectorError::Unknown + } else { + ConnectorError::Protocol + } + })?; + Ok(ProviderHttpResponse { status, body }) + } +} + +fn http_settings(binding: &PaymentBinding) -> Result<&serde_json::Value, ConnectorError> { + match &binding.provider { + CollectionProvider::Http { settings, .. } => Ok(settings), + _ => Err(ConnectorError::Configuration), + } +} + +fn validate_http_observation( + binding: &PaymentBinding, + command: &HttpCollectionCommand, + observed: &super::provider_mapping::ProviderObservation, +) -> Result<(), ConnectorError> { + let expected_intent = command.intent.as_object().ok_or(ConnectorError::Protocol)?; + if expected_intent + .get("correlationId") + .and_then(serde_json::Value::as_str) + != Some(observed.correlation_id.as_str()) + { + return Err(ConnectorError::Protocol); + } + let money = expected_intent + .get("money") + .and_then(serde_json::Value::as_object) + .ok_or(ConnectorError::Protocol)?; + if money + .get("minorUnits") + .and_then(serde_json::Value::as_u64) + .map(|value| value.to_string()) + .as_deref() + != Some(observed.money.minor_units.as_str()) + || money.get("currency").and_then(serde_json::Value::as_str) + != Some(observed.money.currency.as_str()) + || money.get("scale").and_then(serde_json::Value::as_u64) + != Some(u64::from(observed.money.scale)) + { + return Err(ConnectorError::Protocol); + } + let payer_values = observed + .parties + .iter() + .filter(|party| party.role == ProviderPartyRole::Payer) + .map(|party| party.value.as_str()) + .collect::>(); + let payer_id = expected_intent + .get("payerId") + .and_then(serde_json::Value::as_str) + .ok_or(ConnectorError::Protocol)?; + let payer_address = expected_intent + .get("payerFinancialAddress") + .and_then(serde_json::Value::as_str) + .ok_or(ConnectorError::Protocol)?; + if observed.parties.len() != 2 + || payer_values.len() != 2 + || !payer_values.contains(payer_id) + || !payer_values.contains(payer_address) + || !matches!(&binding.provider, CollectionProvider::Http { .. }) + { + return Err(ConnectorError::Protocol); + } + Ok(()) +} + +fn map_mifos_error(error: MifosError) -> ConnectorError { + match error { + MifosError::Configuration => ConnectorError::Configuration, + MifosError::Command => ConnectorError::Command, + MifosError::Protocol => ConnectorError::Protocol, + MifosError::OutcomeUnknown => ConnectorError::Unknown, + MifosError::Authentication + | MifosError::Forbidden + | MifosError::Rejected + | MifosError::Unavailable => ConnectorError::Unavailable, } } @@ -198,6 +703,14 @@ impl PaymentService { { return Err(Error::Conflict); } + let provider_command = self + .provider + .prepare(&connection.binding, &view.snapshot) + .map_err(|_| Error::Unavailable)?; + let provider_command_digest = + matches!(&provider_command, CollectionProviderCommand::Http(_)) + .then(|| digest(&provider_command)) + .transpose()?; let candidate = Attempt { id: Uuid::new_v4(), connection: id.to_owned(), @@ -208,12 +721,14 @@ impl PaymentService { .binding .revision() .map_err(|_| Error::Unavailable)?, - provider_command: view.snapshot.provider_command(&connection.binding)?, + provider_command, + provider_command_digest, bill: view.snapshot, bind_action: None, bound: false, first_send_at: None, transfer_id: None, + provider_acceptance: None, observation: None, report_action: None, receipt_digest: None, @@ -248,17 +763,26 @@ impl PaymentService { if !bill.matches_binding(&attempt) || bill.state != BillState::AttemptBound { return Err(Error::Conflict); } + let preflight = self + .provider + .preflight_submit(&attempt.binding, &attempt.provider_command) + .await + .map_err(|_| Error::Unavailable)?; let now = time::OffsetDateTime::now_utc().unix_timestamp(); attempt.may_dispatch(now)?; if attempt.first_send_at.is_none() { attempt.first_send_at = Some(now); } self.store.save(&attempt, "provider.dispatching").await?; - let transfer = match self - .provider - .submit(&attempt.binding, &attempt.provider_command) - .await - { + let result = match preflight { + ProviderPreflight::Direct => { + self.provider + .submit(&attempt.binding, &attempt.provider_command) + .await + } + ProviderPreflight::Prepared(send) => send.send().await, + }; + let submission = match result { Ok(transfer) => transfer, Err(_) => { self.store @@ -268,7 +792,8 @@ impl PaymentService { return Err(Error::OutcomeUnknown); } }; - attempt.transfer_id = Some(transfer); + attempt.transfer_id = Some(submission.transfer_id); + attempt.provider_acceptance = submission.acceptance; self.store .save(&attempt, "provider.accepted") .await @@ -394,7 +919,12 @@ impl PaymentService { }; let observation = self .provider - .observe(&attempt.binding, &attempt.provider_command, transfer) + .observe( + &attempt.binding, + &attempt.provider_command, + transfer, + attempt.provider_acceptance.as_ref(), + ) .await .map_err(|e| { if e == ConnectorError::Protocol { @@ -460,12 +990,27 @@ impl PaymentService { return Ok(receipt.clone()); } let status = attempt.status(); - if status.state != CollectionState::Confirmed || !status.simulation { + if status.state != CollectionState::Confirmed { return Err(Error::Conflict); } let reference = status.provider_reference.ok_or(Error::Conflict)?; - if !reference.starts_with("SIM-") { - return Err(Error::Conflict); + match &attempt.binding.provider { + CollectionProvider::Simulator { .. } + if status.simulation && reference.starts_with("SIM-") => {} + CollectionProvider::Mifos { .. } if !status.simulation => { + // Released PH-EE Operations `SUCCESS` is only a provider + // observation. It cannot satisfy the BReg Action that advances + // this bill to `paid` and authorizes service issuance. + return Err(Error::RecoveryHeld); + } + CollectionProvider::Http { .. } if !status.simulation => { + return Err(Error::RecoveryHeld); + } + CollectionProvider::Simulator { .. } + | CollectionProvider::Mifos { .. } + | CollectionProvider::Http { .. } => { + return Err(Error::Conflict); + } } let receipt = RegistryReceipt { collection_id: attempt.id, @@ -577,3 +1122,105 @@ fn validate_key(key: &str) -> Result<(), Error> { Err(Error::InvalidRequest) } } + +#[cfg(test)] +mod tests { + use super::*; + use crate::payments::{ + config::PaymentsConfig, + provider_mapping::{ + PreparedProviderRequest, ProviderObservation, ProviderObservedMoney, + ProviderObservedParty, + }, + }; + use serde_json::json; + use std::collections::BTreeMap; + + fn http_binding() -> PaymentBinding { + let config: PaymentsConfig = serde_json::from_value(json!({"connections":[{ + "id":"fees","institutionId":"ministry","serviceId":"permit", + "allowedClients":["coordinator"],"requiredScope":"payments:collections", + "binding":{"providerPack":{"id":"provider","version":"1","digest":format!("sha256:{}", "a".repeat(64))}, + "simulation":false,"currency":"KES","currencyScale":2, + "providerCredentialRef":"secret:env/PROVIDER_TOKEN","providerCredentialIdentity":"producer", + "replayWindowSeconds":3600, + "provider":{"type":"http","submitBaseUrl":"https://submit.example.test/","statusBaseUrl":"https://status.example.test/","settings":{}}, + "registry":{"baseUrl":"https://registry.example.test/","recordType":"service-fee-bill","recordRoute":"service-fee-bills","readProfile":"reporter","bindProfile":"binder","receiptProfile":"reporter","bindAction":"bind-payment-attempt","receiptAction":"record-payment-receipt","credentialRef":"secret:env/REGISTRY_TOKEN","credentialIdentity":"adapter"} + }}]})).unwrap(); + config.connections[0].binding.clone() + } + + fn http_command(binding: &PaymentBinding) -> HttpCollectionCommand { + let intent = json!({ + "correlationId":"correlation-1", + "payerFinancialAddress":"254700000001", + "payerId":"payer-1", + "money":{"minorUnits":2500,"currency":"KES","scale":2} + }); + HttpCollectionCommand { + intent, + prepared_submit: PreparedProviderRequest { + provider_pack: binding.provider_pack.clone().unwrap(), + role: PaymentEndpointRole::CollectionSubmit, + method: PaymentHttpMethod::Post, + path: "/collections".into(), + query: BTreeMap::new(), + headers: BTreeMap::new(), + body: Some(br#"{"amount":"25.00"}"#.to_vec()), + }, + } + } + + fn observation() -> ProviderObservation { + ProviderObservation { + correlation_id: "correlation-1".into(), + provider_reference: "provider-1".into(), + state: ProviderObservationState::ProviderConfirmed, + money: ProviderObservedMoney { + minor_units: "2500".into(), + currency: "KES".into(), + scale: 2, + }, + parties: vec![ + ProviderObservedParty { + role: ProviderPartyRole::Payer, + key: "MSISDN".into(), + value: "254700000001".into(), + }, + ProviderObservedParty { + role: ProviderPartyRole::Payer, + key: "ACCOUNTID".into(), + value: "payer-1".into(), + }, + ], + } + } + + #[test] + fn mapped_collection_observation_must_match_authoritative_payer_and_money() { + let binding = http_binding(); + let command = http_command(&binding); + assert!(validate_http_observation(&binding, &command, &observation()).is_ok()); + + let mut wrong_money = observation(); + wrong_money.money.minor_units = "2501".into(); + assert_eq!( + validate_http_observation(&binding, &command, &wrong_money), + Err(ConnectorError::Protocol) + ); + + let mut wrong_payer = observation(); + wrong_payer.parties[1].value = "different-payer".into(); + assert_eq!( + validate_http_observation(&binding, &command, &wrong_payer), + Err(ConnectorError::Protocol) + ); + + let mut wrong_correlation = observation(); + wrong_correlation.correlation_id = "different-correlation".into(); + assert_eq!( + validate_http_observation(&binding, &command, &wrong_correlation), + Err(ConnectorError::Protocol) + ); + } +} diff --git a/crates/registry-adapter/src/serve.rs b/crates/registry-adapter/src/serve.rs index 286e247df2..77f693e66b 100644 --- a/crates/registry-adapter/src/serve.rs +++ b/crates/registry-adapter/src/serve.rs @@ -637,6 +637,7 @@ pub async fn run( pack_path, runtime_path, None, + &[], ) .await } @@ -648,13 +649,22 @@ pub async fn run_configured( pack_path: Option<&std::path::Path>, runtime_path: &std::path::Path, payments_path: Option<&std::path::Path>, + payment_provider_pack: &[std::path::PathBuf], ) -> Result<(), ServeError> { match (project_directory, payments_path) { (Some(project), payments) => { - run_facade(project, profile_path, pack_path, runtime_path, payments).await + run_facade( + project, + profile_path, + pack_path, + runtime_path, + payments, + payment_provider_pack, + ) + .await } (None, Some(payments)) if profile_path.is_none() && pack_path.is_none() => { - crate::payments::http::run_only(runtime_path, payments).await + crate::payments::http::run_only(runtime_path, payments, payment_provider_pack).await } _ => Err(ServeError::Configuration( "a project or payment configuration is required".to_owned(), @@ -668,6 +678,7 @@ async fn run_facade( pack_path: Option<&std::path::Path>, runtime_path: &std::path::Path, payments_path: Option<&std::path::Path>, + payment_provider_pack: &[std::path::PathBuf], ) -> Result<(), ServeError> { let loaded = crate::engine::load::load_with_target( project_directory, @@ -841,9 +852,15 @@ async fn run_facade( let async_retention = idempotency.as_ref().map(|(_, retention)| *retention); let facade_idempotency = idempotency.as_ref().map(|(store, _)| store.clone()); let payments_router = match payments_path { - Some(path) => { - Some(crate::payments::http::load_router(&loaded.runtime, path, journal.clone()).await?) - } + Some(path) => Some( + crate::payments::http::load_router( + &loaded.runtime, + path, + payment_provider_pack, + journal.clone(), + ) + .await?, + ), None => None, }; let address: SocketAddr = loaded.runtime.listener.bind.0; diff --git a/crates/registry-adapter/tests/g2p_model.rs b/crates/registry-adapter/tests/g2p_model.rs new file mode 100644 index 0000000000..a01f3da096 --- /dev/null +++ b/crates/registry-adapter/tests/g2p_model.rs @@ -0,0 +1,497 @@ +// SPDX-License-Identifier: Apache-2.0 + +use registry_adapter::payments::g2p_model::{ + DisbursementInstruction, G2pAttempt, G2pConnectionSnapshot, G2pError, G2pHttpAuth, + G2pProviderBinding, G2pRegistryBinding, PreparedG2pRegistryAction, +}; +use registry_adapter::payments::pack::{PaymentProviderAuth, ProviderPackPin}; +use registry_adapter::payments::provider_mapping::{ + PaymentEndpointRole, PaymentHttpMethod, PreparedProviderRequest, ProviderAcceptance, + ProviderObservation, ProviderObservationState, ProviderObservedMoney, ProviderObservedParty, + ProviderPartyRole, +}; +use registry_platform_yaml::SecretReference; +use serde_json::{json, Map}; +use std::collections::BTreeMap; +use uuid::Uuid; + +#[test] +fn attempt_freezes_the_pack_settings_and_exact_prepared_submit_bytes() { + let binding = binding(); + let intent = binding.provider_intent(&instruction()).unwrap(); + let prepared = PreparedProviderRequest { + provider_pack: binding.provider_pack.clone(), + role: PaymentEndpointRole::DisbursementSubmit, + method: PaymentHttpMethod::Post, + path: "/bulk/transactions".to_owned(), + query: BTreeMap::new(), + headers: BTreeMap::from([("x-tenant".to_owned(), "default".to_owned())]), + body: Some(br#"{"amount":"1000.00","requestId":"exact"}"#.to_vec()), + }; + let attempt = G2pAttempt::new( + Uuid::new_v4(), + "g2p".to_owned(), + "coordinator".to_owned(), + instruction(), + binding, + prepared.clone(), + action(), + ) + .unwrap(); + let recovered: G2pAttempt = + serde_json::from_value(serde_json::to_value(&attempt).unwrap()).unwrap(); + recovered.validate_integrity().unwrap(); + assert_eq!(recovered.provider_intent, intent); + assert_eq!(recovered.prepared_submit, prepared); + assert_eq!(recovered.prepared_submit.body, prepared.body); +} + +#[test] +fn mapped_observation_must_match_the_independent_breg_tuple() { + let binding = binding(); + let intent = binding.provider_intent(&instruction()).unwrap(); + let attempt = G2pAttempt::new( + Uuid::new_v4(), + "g2p".to_owned(), + "coordinator".to_owned(), + instruction(), + binding.clone(), + prepared_submit(&binding, &intent.correlation_id), + action(), + ) + .unwrap(); + let acceptance = ProviderAcceptance { + correlation_id: intent.correlation_id.clone(), + references: BTreeMap::from([("batchId".to_owned(), "batch-001".to_owned())]), + }; + let exact = observation(&intent.correlation_id); + attempt + .validate_mapped_observation(&acceptance, &exact) + .unwrap(); + + let mut wrong_funding = exact.clone(); + wrong_funding.parties[0].value = "other-account".to_owned(); + assert_eq!( + attempt + .validate_mapped_observation(&acceptance, &wrong_funding) + .unwrap_err(), + G2pError::Conflict + ); + let mut wrong_money = exact; + wrong_money.money.minor_units = "99999".to_owned(); + assert_eq!( + attempt + .validate_mapped_observation(&acceptance, &wrong_money) + .unwrap_err(), + G2pError::Conflict + ); +} + +#[test] +fn custody_accepts_two_provider_wire_shapes_without_changing_the_breg_tuple() { + let binding = binding(); + let instruction = instruction(); + let intent = binding.provider_intent(&instruction).unwrap(); + let first_request = prepared_submit(&binding, &intent.correlation_id); + let mut second_request = first_request.clone(); + second_request.path = "/v2/payouts".to_owned(); + second_request.query = BTreeMap::from([("channel".to_owned(), "benefits".to_owned())]); + second_request.headers = BTreeMap::from([("x-provider-profile".to_owned(), "v2".to_owned())]); + second_request.body = Some( + registry_platform_canonical_json::canonicalize_json(&json!({ + "transfer": { + "clientReference": intent.correlation_id, + "debit": intent.funding, + "credit": intent.recipient, + "money": intent.money + } + })) + .unwrap(), + ); + + let first = G2pAttempt::new( + Uuid::new_v4(), + "g2p-first".to_owned(), + "coordinator".to_owned(), + instruction.clone(), + binding.clone(), + first_request, + action(), + ) + .unwrap(); + let second = G2pAttempt::new( + Uuid::new_v4(), + "g2p-second".to_owned(), + "coordinator".to_owned(), + instruction, + binding, + second_request, + action(), + ) + .unwrap(); + assert_eq!(first.provider_intent, second.provider_intent); + assert_ne!(first.prepared_submit, second.prepared_submit); + assert_ne!(first.binding_revision, second.binding_revision); +} + +#[test] +fn provider_correlation_is_stable_and_namespace_bound() { + let instruction = instruction(); + let binding = binding(); + let first = binding.provider_intent(&instruction).unwrap(); + let second = binding.provider_intent(&instruction).unwrap(); + assert_eq!(first, second); + assert!(first.correlation_id.starts_with("g2p_")); + + let mut other = binding.clone(); + let G2pProviderBinding::Http { settings, .. } = &mut other.provider; + *settings = json!({"tenant": "other-tenant"}); + assert_ne!( + first.correlation_id, + other.provider_intent(&instruction).unwrap().correlation_id + ); + let mut other_revision = binding.clone(); + let G2pProviderBinding::Http { revision, .. } = &mut other_revision.provider; + *revision = "mifos-test-v2".to_owned(); + assert_ne!( + first.correlation_id, + other_revision + .provider_intent(&instruction) + .unwrap() + .correlation_id + ); + + let prepared = prepared_submit(&binding, &first.correlation_id); + let attempt = G2pAttempt::new( + Uuid::new_v4(), + "g2p".to_owned(), + "coordinator".to_owned(), + instruction, + binding, + prepared, + action(), + ) + .unwrap(); + let recovered: G2pAttempt = + serde_json::from_value(serde_json::to_value(&attempt).unwrap()).unwrap(); + recovered.validate_integrity().unwrap(); + assert_eq!(attempt.provider_intent, recovered.provider_intent); + assert_eq!(attempt.prepared_submit, recovered.prepared_submit); +} + +#[test] +fn correlation_separates_authoritative_sources_and_full_instruction_revisions() { + let first_instruction = instruction(); + let first_binding = binding(); + let first_intent = first_binding.provider_intent(&first_instruction).unwrap(); + let first = G2pAttempt::new( + Uuid::new_v4(), + "g2p".to_owned(), + "coordinator".to_owned(), + first_instruction, + first_binding.clone(), + prepared_submit(&first_binding, &first_intent.correlation_id), + action(), + ) + .unwrap() + .provider_intent; + + let mut other_source = binding(); + other_source.registry.base_url = "https://other-breg.invalid/".to_owned(); + other_source.registry.credential_identity = "other-g2p-adapter".to_owned(); + other_source.registry.record_route = "other-disbursement-instructions".to_owned(); + let other_intent = other_source.provider_intent(&instruction()).unwrap(); + let from_other_source = G2pAttempt::new( + Uuid::new_v4(), + "g2p".to_owned(), + "coordinator".to_owned(), + instruction(), + other_source.clone(), + prepared_submit(&other_source, &other_intent.correlation_id), + action(), + ) + .unwrap() + .provider_intent; + + let mut revised_instruction = instruction(); + revised_instruction.record_id = + Uuid::parse_str("00000000-0000-4000-8000-000000000199").unwrap(); + revised_instruction.instruction_digest = "b".repeat(64); + revised_instruction.cycle_id = "cycle-2026-12".to_owned(); + revised_instruction.beneficiary_id = "beneficiary-002".to_owned(); + let revised_binding = binding(); + let revised_intent = revised_binding + .provider_intent(&revised_instruction) + .unwrap(); + let from_revised_instruction = G2pAttempt::new( + Uuid::new_v4(), + "g2p".to_owned(), + "coordinator".to_owned(), + revised_instruction, + revised_binding.clone(), + prepared_submit(&revised_binding, &revised_intent.correlation_id), + action(), + ) + .unwrap() + .provider_intent; + + for distinct in [&from_other_source, &from_revised_instruction] { + assert_eq!(first.money, distinct.money); + assert_eq!(first.recipient, distinct.recipient); + assert_eq!(first.funding, distinct.funding); + assert_ne!(first.correlation_id, distinct.correlation_id); + } +} + +#[test] +fn correlation_canonicalizes_equivalent_provider_and_source_origins() { + let mut first_binding = binding(); + first_binding.registry.base_url = "https://BREG.EXAMPLE:443/".to_owned(); + let G2pProviderBinding::Http { + submit_base_url, + status_base_url, + .. + } = &mut first_binding.provider; + *submit_base_url = "https://BULK.EXAMPLE:443/".to_owned(); + *status_base_url = "https://OPERATIONS.EXAMPLE:443/".to_owned(); + let first_intent = first_binding.provider_intent(&instruction()).unwrap(); + let first = G2pAttempt::new( + Uuid::new_v4(), + "g2p".to_owned(), + "coordinator".to_owned(), + instruction(), + first_binding.clone(), + prepared_submit(&first_binding, &first_intent.correlation_id), + action(), + ) + .unwrap() + .provider_intent; + + let mut second_binding = binding(); + second_binding.registry.base_url = "https://breg.example/".to_owned(); + let G2pProviderBinding::Http { + submit_base_url, + status_base_url, + .. + } = &mut second_binding.provider; + *submit_base_url = "https://bulk.example/".to_owned(); + *status_base_url = "https://operations.example/".to_owned(); + let second_intent = second_binding.provider_intent(&instruction()).unwrap(); + let second = G2pAttempt::new( + Uuid::new_v4(), + "g2p".to_owned(), + "coordinator".to_owned(), + instruction(), + second_binding.clone(), + prepared_submit(&second_binding, &second_intent.correlation_id), + action(), + ) + .unwrap() + .provider_intent; + + assert_eq!(first, second); +} + +#[test] +fn connection_refuses_wrong_programme_and_funding_before_attempt_custody() { + let binding = binding(); + let mut wrong_programme = instruction(); + wrong_programme.programme_id = "other-programme".to_owned(); + assert_eq!( + binding.validate_instruction(&wrong_programme).unwrap_err(), + G2pError::Conflict + ); + + let mut wrong_funding = instruction(); + wrong_funding.funding_account_id = "other-funding".to_owned(); + assert_eq!( + binding.validate_instruction(&wrong_funding).unwrap_err(), + G2pError::Conflict + ); + + assert_eq!( + G2pAttempt::new( + Uuid::new_v4(), + "g2p".to_owned(), + "coordinator".to_owned(), + wrong_funding, + binding.clone(), + prepared_submit( + &binding, + &binding + .provider_intent(&instruction()) + .unwrap() + .correlation_id, + ), + action(), + ) + .err(), + Some(G2pError::Conflict) + ); +} + +#[test] +fn provider_binding_exposes_the_exact_pack_auth_profile() { + let mut provider = binding().provider; + assert_eq!(provider.auth_profile(), PaymentProviderAuth::Bearer); + let G2pProviderBinding::Http { auth, .. } = &mut provider; + *auth = G2pHttpAuth::MifosLegacySignature { + signing_key_identity: "mifos-signing-key".to_owned(), + signing_key_ref: SecretReference::new("secret:env/MIFOS_SIGNING_KEY").unwrap(), + response_key_identity: "mifos-response-key".to_owned(), + response_key_ref: SecretReference::new("secret:env/MIFOS_RESPONSE_KEY").unwrap(), + }; + assert_eq!( + provider.auth_profile(), + PaymentProviderAuth::MifosLegacySignature + ); +} + +#[test] +fn provider_auth_and_binding_use_strict_camel_case_authored_fields() { + let signature = json!({ + "type": "mifos-legacy-signature", + "signingKeyIdentity": "mifos-signing-key", + "signingKeyRef": "secret:env/MIFOS_SIGNING_KEY", + "responseKeyIdentity": "mifos-response-key", + "responseKeyRef": "secret:env/MIFOS_RESPONSE_KEY" + }); + let auth: G2pHttpAuth = serde_json::from_value(signature.clone()).unwrap(); + assert_eq!(serde_json::to_value(&auth).unwrap(), signature); + assert!(serde_json::from_value::(json!({ + "type": "mifos-legacy-signature", + "signing_key_identity": "mifos-signing-key", + "signingKeyRef": "secret:env/MIFOS_SIGNING_KEY", + "responseKeyIdentity": "mifos-response-key", + "responseKeyRef": "secret:env/MIFOS_RESPONSE_KEY" + })) + .is_err()); + assert!(serde_json::from_value::(json!({ + "type": "bearer", + "credentialRef": "secret:env/NOT_ALLOWED" + })) + .is_err()); + + let provider = binding().provider; + let encoded = serde_json::to_value(&provider).unwrap(); + assert!(encoded.get("submitBaseUrl").is_some()); + assert!(encoded.get("statusBaseUrl").is_some()); + assert!(encoded.get("credentialIdentity").is_some()); + assert!(encoded.get("credentialRef").is_some()); + assert!(encoded.get("submit_base_url").is_none()); + let decoded: G2pProviderBinding = serde_json::from_value(encoded).unwrap(); + assert_eq!(decoded.auth_profile(), PaymentProviderAuth::Bearer); +} + +fn instruction() -> DisbursementInstruction { + DisbursementInstruction { + record_id: Uuid::parse_str("00000000-0000-4000-8000-000000000100").unwrap(), + instruction_id: Uuid::parse_str("00000000-0000-4000-8000-000000000101").unwrap(), + instruction_version: 1, + instruction_digest: "a".repeat(64), + institution_id: "ministry-social-protection".to_owned(), + service_id: "cash-transfer".to_owned(), + programme_id: "cash-programme".to_owned(), + cycle_id: "cycle-2026-11".to_owned(), + beneficiary_id: "beneficiary-001".to_owned(), + beneficiary_destination: "254700000002".to_owned(), + funding_account_id: "programme-account".to_owned(), + amount_minor: 100_000, + currency: "KES".to_owned(), + currency_scale: 2, + } +} + +fn binding() -> G2pConnectionSnapshot { + G2pConnectionSnapshot { + institution_id: "ministry-social-protection".to_owned(), + service_id: "cash-transfer".to_owned(), + programme_id: "cash-programme".to_owned(), + funding_account_id: "programme-account".to_owned(), + currency: "KES".to_owned(), + currency_scale: 2, + provider_pack: ProviderPackPin { + id: "g2p-test".to_owned(), + version: "1".to_owned(), + digest: format!("sha256:{}", "a".repeat(64)), + }, + funding_party_key: "ACCOUNT_ID".to_owned(), + recipient_party_key: "MSISDN".to_owned(), + provider: G2pProviderBinding::Http { + revision: "mifos-test-v1".to_owned(), + submit_base_url: "http://127.0.0.1:31002/".to_owned(), + status_base_url: "http://127.0.0.1:31003/".to_owned(), + credential_identity: "mifos-test-client".to_owned(), + credential_ref: SecretReference::new("secret:env/MIFOS_TEST_TOKEN").unwrap(), + auth: G2pHttpAuth::Bearer, + settings: json!({"tenant": "default", "purpose": "GOVERNMENT_TRANSFER"}), + }, + registry: G2pRegistryBinding { + base_url: "https://breg.invalid/".to_owned(), + credential_identity: "g2p-adapter".to_owned(), + credential_ref: SecretReference::new("secret:env/BREG_TEST_TOKEN").unwrap(), + record_route: "disbursement-instructions".to_owned(), + record_type: "disbursement-instruction".to_owned(), + read_profile: "g2p-adapter-read".to_owned(), + bind_action: "bind-payout-attempt".to_owned(), + bind_profile: "g2p-adapter-bind".to_owned(), + report_action: "record-provider-confirmation".to_owned(), + report_profile: "g2p-adapter-report".to_owned(), + }, + } +} + +fn prepared_submit( + binding: &G2pConnectionSnapshot, + correlation_id: &str, +) -> PreparedProviderRequest { + PreparedProviderRequest { + provider_pack: binding.provider_pack.clone(), + role: PaymentEndpointRole::DisbursementSubmit, + method: PaymentHttpMethod::Post, + path: "/bulk/transactions".to_owned(), + query: BTreeMap::new(), + headers: BTreeMap::new(), + body: Some( + registry_platform_canonical_json::canonicalize_json(&json!({ + "correlationId": correlation_id, + "amountMinor": "100000" + })) + .unwrap(), + ), + } +} + +fn observation(correlation_id: &str) -> ProviderObservation { + ProviderObservation { + correlation_id: correlation_id.to_owned(), + provider_reference: "provider-001".to_owned(), + state: ProviderObservationState::ProviderConfirmed, + money: ProviderObservedMoney { + minor_units: "100000".to_owned(), + currency: "KES".to_owned(), + scale: 2, + }, + parties: vec![ + ProviderObservedParty { + role: ProviderPartyRole::Funding, + key: "ACCOUNT_ID".to_owned(), + value: "programme-account".to_owned(), + }, + ProviderObservedParty { + role: ProviderPartyRole::Recipient, + key: "MSISDN".to_owned(), + value: "254700000002".to_owned(), + }, + ], + } +} + +fn action() -> PreparedG2pRegistryAction { + PreparedG2pRegistryAction { + action: "bind-payout-attempt".to_owned(), + key: "g2p-bind-test".to_owned(), + inputs: Map::new(), + evidence: "prepared".to_owned(), + } +} diff --git a/crates/registry-adapter/tests/g2p_postgres.rs b/crates/registry-adapter/tests/g2p_postgres.rs new file mode 100644 index 0000000000..6f36e89e39 --- /dev/null +++ b/crates/registry-adapter/tests/g2p_postgres.rs @@ -0,0 +1,614 @@ +// SPDX-License-Identifier: Apache-2.0 +#![cfg(feature = "postgres-test")] + +use async_trait::async_trait; +use registry_adapter::payments::{ + g2p_model::{ + DisbursementInstruction, G2pAttempt, G2pAttemptState, G2pConnectionSnapshot, G2pError, + G2pHttpAuth, G2pProviderBinding, G2pRegistryBinding, PreparedG2pRegistryAction, + }, + g2p_registry::{G2pInstructionView, G2pRegistryPort}, + g2p_service::{G2pMappingPort, G2pProviderError, G2pProviderPort, G2pService, PreparedG2pSend}, + g2p_store::{migrate_g2p, DispatchAuthorization, G2pStore}, + pack::ProviderPackPin, + provider_mapping::{ + MappedProviderResponse, PaymentEndpointRole, PaymentHttpMethod, PaymentMappingError, + PaymentMappingRegistry, PreparedProviderRequest, ProviderAcceptance, ProviderHttpResponse, + }, +}; +use registry_platform_yaml::SecretReference; +use serde_json::{json, Map}; +use std::{ + collections::BTreeMap, + sync::{ + atomic::{AtomicUsize, Ordering}, + Arc, + }, +}; +use uuid::Uuid; + +#[tokio::test] +async fn concurrent_dispatch_authorizes_exactly_one_provider_send() { + let store = store().await; + let candidate = attempt( + Uuid::parse_str("00000000-0000-4000-8000-000000000100").unwrap(), + Uuid::parse_str("00000000-0000-4000-8000-000000000101").unwrap(), + ); + let saved = store + .reserve(&candidate, "workflow-command", "request-digest") + .await + .unwrap(); + store + .record_bound("g2p", "coordinator", saved.id) + .await + .unwrap(); + + let first_store = store.clone(); + let second_store = store.clone(); + let id = saved.id; + let (first, second) = tokio::join!( + first_store.begin_dispatch("g2p", "coordinator", id, 1_800_000_000), + second_store.begin_dispatch("g2p", "coordinator", id, 1_800_000_000), + ); + let decisions = [first.unwrap(), second.unwrap()]; + assert_eq!( + decisions + .iter() + .filter(|decision| matches!(decision, DispatchAuthorization::Send(_))) + .count(), + 1 + ); + assert_eq!( + decisions + .iter() + .filter(|decision| matches!(decision, DispatchAuthorization::Hold(_))) + .count(), + 1 + ); +} +#[tokio::test] +async fn uncertain_send_is_held_and_never_reauthorizes_dispatch() { + let store = store().await; + let candidate = attempt( + Uuid::parse_str("00000000-0000-4000-8000-000000000110").unwrap(), + Uuid::parse_str("00000000-0000-4000-8000-000000000111").unwrap(), + ); + let id = candidate.id; + store + .reserve(&candidate, "workflow-command", "request-digest") + .await + .unwrap(); + store.record_bound("g2p", "coordinator", id).await.unwrap(); + assert!(matches!( + store + .begin_dispatch("g2p", "coordinator", id, 1_800_000_000) + .await + .unwrap(), + DispatchAuthorization::Send(_) + )); + assert!(matches!( + store + .begin_dispatch("g2p", "coordinator", id, 1_800_000_001) + .await + .unwrap(), + DispatchAuthorization::Hold(_) + )); +} +#[tokio::test] +async fn failed_local_preflight_does_not_consume_the_first_send_grant() { + let store = store().await; + let candidate = attempt( + Uuid::parse_str("00000000-0000-4000-8000-000000000160").unwrap(), + Uuid::parse_str("00000000-0000-4000-8000-000000000161").unwrap(), + ); + let id = candidate.id; + let binding = candidate.binding.clone(); + store + .reserve(&candidate, "initial-command", "initial-digest") + .await + .unwrap(); + store.record_bound("g2p", "coordinator", id).await.unwrap(); + + let provider = Arc::new(PreflightFailureProvider::default()); + let service = G2pService::new(store.clone(), Arc::new(UnusedRegistry), provider.clone()) + .with_mapping(Arc::new(AvailableMapping)); + assert!(matches!( + service + .request_disbursement( + "g2p", + "coordinator", + "retry-command", + candidate.instruction.record_id, + candidate.instruction.instruction_version, + binding, + 1_800_000_000, + ) + .await, + Err(G2pError::Unavailable) + )); + assert_eq!(provider.preflights.load(Ordering::SeqCst), 1); + let retained = store.get_scoped("g2p", "coordinator", id).await.unwrap(); + assert_eq!(retained.state, G2pAttemptState::Bound); + assert_eq!(retained.first_send_at_unix_seconds, None); + assert!(matches!( + store + .begin_dispatch("g2p", "coordinator", id, 1_800_000_001) + .await + .unwrap(), + DispatchAuthorization::Send(_) + )); +} + +#[tokio::test] +async fn missing_retained_pack_holds_before_provider_preflight_or_dispatch() { + let store = store().await; + let candidate = attempt( + Uuid::parse_str("00000000-0000-4000-8000-000000000162").unwrap(), + Uuid::parse_str("00000000-0000-4000-8000-000000000163").unwrap(), + ); + let id = candidate.id; + let binding = candidate.binding.clone(); + store + .reserve(&candidate, "missing-pack-initial", "missing-pack-digest") + .await + .unwrap(); + store.record_bound("g2p", "coordinator", id).await.unwrap(); + + let provider = Arc::new(PreflightFailureProvider::default()); + let service = G2pService::new(store.clone(), Arc::new(UnusedRegistry), provider.clone()) + .with_mapping(Arc::new(PaymentMappingRegistry::new())); + assert!(matches!( + service + .request_disbursement( + "g2p", + "coordinator", + "missing-pack-retry", + candidate.instruction.record_id, + candidate.instruction.instruction_version, + binding, + 1_800_000_000, + ) + .await, + Err(G2pError::Unavailable) + )); + assert_eq!(provider.preflights.load(Ordering::SeqCst), 0); + let retained = store.get_scoped("g2p", "coordinator", id).await.unwrap(); + assert_eq!(retained.state, G2pAttemptState::Bound); + assert_eq!(retained.first_send_at_unix_seconds, None); +} +#[tokio::test] +async fn source_instruction_identity_is_unique_across_distinct_record_ids() { + let store = store().await; + let instruction_id = Uuid::parse_str("00000000-0000-4000-8000-000000000121").unwrap(); + let first = attempt( + Uuid::parse_str("00000000-0000-4000-8000-000000000120").unwrap(), + instruction_id, + ); + let second = attempt( + Uuid::parse_str("00000000-0000-4000-8000-000000000122").unwrap(), + instruction_id, + ); + store + .reserve(&first, "first-command", "first-digest") + .await + .unwrap(); + assert!(store + .reserve(&second, "second-command", "second-digest") + .await + .is_err()); +} +#[tokio::test] +async fn instruction_uniqueness_is_scoped_to_the_authoritative_source_namespace() { + let store = store().await; + let record_id = Uuid::parse_str("00000000-0000-4000-8000-000000000140").unwrap(); + let instruction_id = Uuid::parse_str("00000000-0000-4000-8000-000000000141").unwrap(); + + let first = attempt_for_registry( + record_id, + instruction_id, + "g2p-primary", + registry_binding("https://breg.invalid/"), + ); + let distinct_source = attempt_for_registry( + record_id, + instruction_id, + "g2p-secondary", + registry_binding("https://other-breg.invalid/"), + ); + let first_saved = store + .reserve(&first, "first-source-command", "first-source-digest") + .await + .unwrap(); + let second_saved = store + .reserve( + &distinct_source, + "second-source-command", + "second-source-digest", + ) + .await + .unwrap(); + assert_ne!(first_saved.id, second_saved.id); + + let mut renamed_binding = registry_binding("https://BREG.invalid:443"); + renamed_binding.credential_identity = "rotated-g2p-adapter".to_owned(); + renamed_binding.credential_ref = + SecretReference::new("secret:env/BREG_ROTATED_TEST_TOKEN").unwrap(); + renamed_binding.read_profile = "renamed-g2p-adapter-read".to_owned(); + renamed_binding.bind_profile = "renamed-g2p-adapter-bind".to_owned(); + renamed_binding.report_profile = "renamed-g2p-adapter-report".to_owned(); + let renamed_connection = + attempt_for_registry(record_id, instruction_id, "g2p-renamed", renamed_binding); + assert!(store + .reserve( + &renamed_connection, + "renamed-source-command", + "renamed-source-digest", + ) + .await + .is_err()); + + store + .record_bound("g2p-primary", "coordinator", first_saved.id) + .await + .unwrap(); + store + .record_bound("g2p-secondary", "coordinator", second_saved.id) + .await + .unwrap(); + assert!(matches!( + store + .begin_dispatch("g2p-primary", "coordinator", first_saved.id, 1_800_000_000,) + .await + .unwrap(), + DispatchAuthorization::Send(_) + )); + assert!(matches!( + store + .begin_dispatch( + "g2p-secondary", + "coordinator", + second_saved.id, + 1_800_000_000, + ) + .await + .unwrap(), + DispatchAuthorization::Send(_) + )); + assert!(matches!( + store + .begin_dispatch("g2p-primary", "coordinator", first_saved.id, 1_800_000_001,) + .await + .unwrap(), + DispatchAuthorization::Hold(_) + )); +} +#[tokio::test] +async fn request_receipt_lookup_requires_the_exact_saved_key_digest_and_principal() { + let store = store().await; + let candidate = attempt( + Uuid::parse_str("00000000-0000-4000-8000-000000000130").unwrap(), + Uuid::parse_str("00000000-0000-4000-8000-000000000131").unwrap(), + ); + let saved = store + .reserve(&candidate, "workflow-command", "request-digest") + .await + .unwrap(); + assert_eq!( + store + .lookup_command("g2p", "coordinator", "workflow-command", "request-digest") + .await + .unwrap() + .unwrap() + .id, + saved.id + ); + assert!(store + .lookup_command("g2p", "coordinator", "workflow-command", "changed-digest") + .await + .is_err()); + assert!(store + .lookup_command( + "g2p", + "another-caller", + "workflow-command", + "request-digest" + ) + .await + .unwrap() + .is_none()); + assert!(store + .lookup_command("g2p", "coordinator", "other-command", "request-digest") + .await + .unwrap() + .is_none()); +} +#[tokio::test] +async fn confirmation_key_is_bound_to_its_operation_scope_and_disbursement() { + let store = store().await; + let first = attempt( + Uuid::parse_str("00000000-0000-4000-8000-000000000150").unwrap(), + Uuid::parse_str("00000000-0000-4000-8000-000000000151").unwrap(), + ); + let second = attempt( + Uuid::parse_str("00000000-0000-4000-8000-000000000152").unwrap(), + Uuid::parse_str("00000000-0000-4000-8000-000000000153").unwrap(), + ); + let first_saved = store + .reserve(&first, "first-request-command", "first-request-digest") + .await + .unwrap(); + let second_saved = store + .reserve(&second, "second-request-command", "second-request-digest") + .await + .unwrap(); + + let claimed = store + .claim_confirmation_command( + "g2p", + "coordinator", + first_saved.id, + "confirmation-key", + "confirmation-first-digest", + ) + .await + .unwrap(); + assert_eq!(claimed.id, first_saved.id); + assert_eq!( + store + .claim_confirmation_command( + "g2p", + "coordinator", + first_saved.id, + "confirmation-key", + "confirmation-first-digest", + ) + .await + .unwrap() + .id, + first_saved.id + ); + assert!(store + .claim_confirmation_command( + "g2p", + "coordinator", + second_saved.id, + "confirmation-key", + "confirmation-second-digest", + ) + .await + .is_err()); + assert!(store + .claim_existing_command(&first_saved, "confirmation-key", "request-operation-digest",) + .await + .is_err()); +} + +async fn store() -> G2pStore { + let url = std::env::var("ADAPTER_TEST_DATABASE_URL") + .expect("postgres-test requires ADAPTER_TEST_DATABASE_URL"); + let config = url.parse().unwrap(); + let manager = deadpool_postgres::Manager::new(config, tokio_postgres::NoTls); + let pool = deadpool_postgres::Pool::builder(manager) + .max_size(8) + .build() + .unwrap(); + let mut client = pool.get().await.unwrap(); + migrate_g2p(&mut client).await.unwrap(); + drop(client); + G2pStore::new(pool, format!("g2p-test-{}", Uuid::new_v4())) +} + +fn attempt(record_id: Uuid, instruction_id: Uuid) -> G2pAttempt { + attempt_for_registry( + record_id, + instruction_id, + "g2p", + registry_binding("https://breg.invalid/"), + ) +} + +fn attempt_for_registry( + record_id: Uuid, + instruction_id: Uuid, + connection: &str, + registry: G2pRegistryBinding, +) -> G2pAttempt { + let instruction = DisbursementInstruction { + record_id, + instruction_id, + instruction_version: 1, + instruction_digest: "a".repeat(64), + institution_id: "ministry-social-protection".to_owned(), + service_id: "cash-transfer".to_owned(), + programme_id: "cash-programme".to_owned(), + cycle_id: "cycle-2026-11".to_owned(), + beneficiary_id: "beneficiary-001".to_owned(), + beneficiary_destination: "254700000002".to_owned(), + funding_account_id: "programme-account".to_owned(), + amount_minor: 100_000, + currency: "KES".to_owned(), + currency_scale: 2, + }; + let binding = G2pConnectionSnapshot { + institution_id: "ministry-social-protection".to_owned(), + service_id: "cash-transfer".to_owned(), + programme_id: "cash-programme".to_owned(), + funding_account_id: "programme-account".to_owned(), + currency: "KES".to_owned(), + currency_scale: 2, + provider_pack: ProviderPackPin { + id: "g2p-test".to_owned(), + version: "1".to_owned(), + digest: format!("sha256:{}", "a".repeat(64)), + }, + funding_party_key: "ACCOUNT_ID".to_owned(), + recipient_party_key: "MSISDN".to_owned(), + provider: G2pProviderBinding::Http { + revision: "http-test-v1".to_owned(), + submit_base_url: "http://127.0.0.1:31002/".to_owned(), + status_base_url: "http://127.0.0.1:31003/".to_owned(), + credential_identity: "provider-test-client".to_owned(), + credential_ref: SecretReference::new("secret:env/PROVIDER_TEST_TOKEN").unwrap(), + auth: G2pHttpAuth::Bearer, + settings: json!({"tenant": "default"}), + }, + registry, + }; + let intent = binding.provider_intent(&instruction).unwrap(); + let prepared_submit = PreparedProviderRequest { + provider_pack: binding.provider_pack.clone(), + role: PaymentEndpointRole::DisbursementSubmit, + method: PaymentHttpMethod::Post, + path: "/bulk/transactions".to_owned(), + query: BTreeMap::new(), + headers: BTreeMap::new(), + body: Some( + registry_platform_canonical_json::canonicalize_json(&json!({ + "correlationId": intent.correlation_id, + "amountMinor": "100000" + })) + .unwrap(), + ), + }; + G2pAttempt::new( + Uuid::new_v4(), + connection.to_owned(), + "coordinator".to_owned(), + instruction, + binding, + prepared_submit, + PreparedG2pRegistryAction { + action: "bind-payout-attempt".to_owned(), + key: "g2p-bind-test".to_owned(), + inputs: Map::new(), + evidence: "prepared".to_owned(), + }, + ) + .unwrap() +} + +fn registry_binding(base_url: &str) -> G2pRegistryBinding { + G2pRegistryBinding { + base_url: base_url.to_owned(), + credential_identity: "g2p-adapter".to_owned(), + credential_ref: SecretReference::new("secret:env/BREG_TEST_TOKEN").unwrap(), + record_route: "disbursement-instructions".to_owned(), + record_type: "disbursement-instruction".to_owned(), + read_profile: "g2p-adapter-read".to_owned(), + bind_action: "bind-payout-attempt".to_owned(), + bind_profile: "g2p-adapter-bind".to_owned(), + report_action: "record-provider-confirmation".to_owned(), + report_profile: "g2p-adapter-report".to_owned(), + } +} + +#[derive(Default)] +struct PreflightFailureProvider { + preflights: AtomicUsize, +} + +#[async_trait] +impl G2pProviderPort for PreflightFailureProvider { + async fn preflight_submit( + &self, + _binding: &G2pProviderBinding, + _request: &PreparedProviderRequest, + ) -> Result { + self.preflights.fetch_add(1, Ordering::SeqCst); + Err(G2pProviderError::Unavailable) + } + + async fn recover_acceptance( + &self, + _binding: &G2pProviderBinding, + _request: &PreparedProviderRequest, + ) -> Result, G2pProviderError> { + panic!("preflight failure must not enter recovery") + } + + async fn observe( + &self, + _binding: &G2pProviderBinding, + _request: &PreparedProviderRequest, + ) -> Result { + panic!("preflight failure must not observe the provider") + } +} + +struct AvailableMapping; + +impl G2pMappingPort for AvailableMapping { + fn ensure_available(&self, _pin: &ProviderPackPin) -> Result<(), PaymentMappingError> { + Ok(()) + } + + fn prepare( + &self, + _pin: &ProviderPackPin, + _role: PaymentEndpointRole, + _intent: &serde_json::Value, + _settings: &serde_json::Value, + _acceptance: Option<&ProviderAcceptance>, + ) -> Result { + Err(PaymentMappingError::ArtifactUnavailable) + } + + fn interpret( + &self, + _pin: &ProviderPackPin, + _role: PaymentEndpointRole, + _intent: &serde_json::Value, + _settings: &serde_json::Value, + _acceptance: Option<&ProviderAcceptance>, + _response: &ProviderHttpResponse, + ) -> Result { + Err(PaymentMappingError::ArtifactUnavailable) + } +} + +struct UnusedRegistry; + +#[async_trait] +impl G2pRegistryPort for UnusedRegistry { + async fn read_instruction( + &self, + _binding: &G2pRegistryBinding, + _record_id: Uuid, + ) -> Result { + panic!("retained attempt must not reread BReg before preflight") + } + + async fn prepare_bind( + &self, + _binding: &G2pRegistryBinding, + _key: &str, + _inputs: Map, + ) -> Result { + panic!("retained bound attempt must not prepare another BReg bind") + } + + async fn invoke_bind( + &self, + _binding: &G2pRegistryBinding, + _prepared: &PreparedG2pRegistryAction, + ) -> Result<(), G2pError> { + panic!("retained bound attempt must not invoke another BReg bind") + } + + async fn prepare_confirmation( + &self, + _binding: &G2pRegistryBinding, + _key: &str, + _inputs: Map, + ) -> Result { + panic!("preflight failure cannot prepare confirmation") + } + + async fn invoke_confirmation( + &self, + _binding: &G2pRegistryBinding, + _prepared: &PreparedG2pRegistryAction, + ) -> Result<(), G2pError> { + panic!("preflight failure cannot invoke confirmation") + } +} diff --git a/crates/registry-adapter/tests/g2p_provider.rs b/crates/registry-adapter/tests/g2p_provider.rs new file mode 100644 index 0000000000..9b1d00faac --- /dev/null +++ b/crates/registry-adapter/tests/g2p_provider.rs @@ -0,0 +1,369 @@ +// SPDX-License-Identifier: Apache-2.0 + +use axum::{ + body::Bytes, + extract::State, + http::{HeaderMap, Uri}, + response::IntoResponse, + routing::{get, post}, + Router, +}; +use registry_adapter::payments::{ + g2p_model::{ + DisbursementInstruction, G2pAttempt, G2pConnectionSnapshot, G2pError, G2pHttpAuth, + G2pProviderBinding, G2pRegistryBinding, PreparedG2pRegistryAction, + }, + g2p_service::{G2pProviderError, G2pProviderPort, HttpG2pProvider}, + pack::ProviderPackPin, + provider_mapping::{ + PaymentEndpointRole, PaymentHttpMethod, PreparedProviderRequest, ProviderAcceptance, + ProviderObservation, ProviderObservationState, ProviderObservedMoney, + ProviderObservedParty, ProviderPartyRole, + }, +}; +use registry_platform_config::{SecretProvider, SecretResolver}; +use registry_platform_yaml::SecretReference; +use serde_json::json; +use std::{ + collections::BTreeMap, + os::unix::fs::PermissionsExt, + sync::{Arc, Mutex}, +}; +use uuid::Uuid; + +#[derive(Clone, Debug, PartialEq, Eq)] +struct SeenRequest { + method: &'static str, + path_and_query: String, + tenant: Option, + authorization_ok: bool, + body: Vec, +} + +#[tokio::test] +async fn bearer_http_host_preserves_one_send_and_validates_wire_observations() { + let seen = Arc::new(Mutex::new(Vec::new())); + let router = Router::new() + .route("/v2/payouts", post(capture_submit)) + .route("/v2/uncertain", post(capture_uncertain)) + .route("/v2/payouts/{reference}", get(capture_status)) + .with_state(seen.clone()); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let origin = format!("http://{}/", listener.local_addr().unwrap()); + let server = tokio::spawn(async move { + axum::serve(listener, router).await.unwrap(); + }); + + let secrets = tempfile::tempdir().unwrap(); + write_secret(secrets.path().join("provider-token"), b"test-only-bearer"); + write_secret(secrets.path().join("signing-key"), b"test-only-signing-key"); + write_secret( + secrets.path().join("response-key"), + b"test-only-response-key", + ); + let resolver = Arc::new( + SecretResolver::new([SecretProvider::File], secrets.path()).expect("file resolver"), + ); + let provider = HttpG2pProvider::new(resolver); + let provider_binding = binding(&origin, G2pHttpAuth::Bearer); + let pack = pin(); + let instruction = instruction(); + let snapshot = snapshot(provider_binding.clone(), pack.clone()); + let intent = snapshot.provider_intent(&instruction).unwrap(); + let exact_body = registry_platform_canonical_json::canonicalize_json(&json!({ + "amountMinor": "100000", + "clientReference": intent.correlation_id + })) + .unwrap(); + let submit = PreparedProviderRequest { + provider_pack: pack.clone(), + role: PaymentEndpointRole::DisbursementSubmit, + method: PaymentHttpMethod::Post, + path: "/v2/payouts".to_owned(), + query: BTreeMap::from([("channel".to_owned(), "benefits".to_owned())]), + headers: BTreeMap::from([("x-provider-tenant".to_owned(), "pilot-beta".to_owned())]), + body: Some(exact_body.clone()), + }; + let prepared_send = provider + .preflight_submit(&provider_binding, &submit) + .await + .unwrap(); + let accepted = prepared_send.send().await.unwrap(); + assert_eq!(accepted.status, 202); + let attempt = G2pAttempt::new( + Uuid::new_v4(), + "second-provider".to_owned(), + "coordinator".to_owned(), + instruction, + snapshot, + submit.clone(), + PreparedG2pRegistryAction { + action: "bind-payout-attempt".to_owned(), + key: "bind-test".to_owned(), + inputs: Default::default(), + evidence: "prepared".to_owned(), + }, + ) + .unwrap(); + let acceptance = ProviderAcceptance { + correlation_id: attempt.provider_intent.correlation_id.clone(), + references: BTreeMap::from([("payoutId".to_owned(), "provider-001".to_owned())]), + }; + + let status = PreparedProviderRequest { + provider_pack: pack, + role: PaymentEndpointRole::DisbursementStatus, + method: PaymentHttpMethod::Get, + path: "/v2/payouts/provider-001".to_owned(), + query: BTreeMap::from([("view".to_owned(), "settlement".to_owned())]), + headers: BTreeMap::new(), + body: None, + }; + let observed = provider.observe(&provider_binding, &status).await.unwrap(); + assert_eq!(observed.status, 200); + let exact_observation = observation(&attempt.provider_intent.correlation_id); + attempt + .validate_mapped_observation(&acceptance, &exact_observation) + .unwrap(); + for mismatched in [ + { + let mut value = exact_observation.clone(); + value.money.minor_units = "99999".to_owned(); + value + }, + { + let mut value = exact_observation.clone(); + value.parties[0].value = "other-funding".to_owned(); + value + }, + { + let mut value = exact_observation.clone(); + value.parties[1].value = "other-recipient".to_owned(); + value + }, + ] { + assert!(matches!( + attempt.validate_mapped_observation(&acceptance, &mismatched), + Err(G2pError::Conflict) + )); + } + + { + let requests = seen.lock().unwrap(); + assert_eq!(requests.len(), 2); + assert_eq!( + requests[0], + SeenRequest { + method: "POST", + path_and_query: "/v2/payouts?channel=benefits".to_owned(), + tenant: Some("pilot-beta".to_owned()), + authorization_ok: true, + body: exact_body, + } + ); + assert_eq!( + requests[1], + SeenRequest { + method: "GET", + path_and_query: "/v2/payouts/provider-001?view=settlement".to_owned(), + tenant: None, + authorization_ok: true, + body: Vec::new(), + } + ); + } + + let legacy = binding( + &origin, + G2pHttpAuth::MifosLegacySignature { + signing_key_identity: "test-signing-key".to_owned(), + signing_key_ref: SecretReference::new("secret:file/signing-key").unwrap(), + response_key_identity: "test-response-key".to_owned(), + response_key_ref: SecretReference::new("secret:file/response-key").unwrap(), + }, + ); + assert!(matches!( + provider.preflight_submit(&legacy, &submit).await, + Err(G2pProviderError::Unavailable) + )); + assert_eq!(seen.lock().unwrap().len(), 2); + + let mut uncertain = submit.clone(); + uncertain.path = "/v2/uncertain".to_owned(); + let uncertain_send = provider + .preflight_submit(&provider_binding, &uncertain) + .await + .unwrap(); + assert!(matches!( + uncertain_send.send().await, + Err(G2pProviderError::OutcomeUnknown) + )); + assert_eq!( + provider + .recover_acceptance(&provider_binding, &uncertain) + .await + .unwrap(), + None + ); + let requests = seen.lock().unwrap(); + assert_eq!(requests.len(), 3); + assert_eq!( + requests + .iter() + .filter(|request| request.path_and_query.starts_with("/v2/uncertain")) + .count(), + 1 + ); + server.abort(); +} + +async fn capture_submit( + State(seen): State>>>, + uri: Uri, + headers: HeaderMap, + body: Bytes, +) -> impl IntoResponse { + capture(&seen, "POST", uri, headers, body); + (axum::http::StatusCode::ACCEPTED, r#"{"accepted":true}"#) +} + +async fn capture_status( + State(seen): State>>>, + uri: Uri, + headers: HeaderMap, + body: Bytes, +) -> impl IntoResponse { + capture(&seen, "GET", uri, headers, body); + (axum::http::StatusCode::OK, r#"{"state":"complete"}"#) +} + +async fn capture_uncertain( + State(seen): State>>>, + uri: Uri, + headers: HeaderMap, + body: Bytes, +) -> impl IntoResponse { + capture(&seen, "POST", uri, headers, body); + vec![b'x'; 131_073] +} + +fn capture( + seen: &Mutex>, + method: &'static str, + uri: Uri, + headers: HeaderMap, + body: Bytes, +) { + seen.lock().unwrap().push(SeenRequest { + method, + path_and_query: uri + .path_and_query() + .expect("request target") + .as_str() + .to_owned(), + tenant: headers + .get("x-provider-tenant") + .and_then(|value| value.to_str().ok()) + .map(str::to_owned), + authorization_ok: headers + .get(axum::http::header::AUTHORIZATION) + .is_some_and(|value| value.as_bytes() == b"Bearer test-only-bearer"), + body: body.to_vec(), + }); +} + +fn binding(origin: &str, auth: G2pHttpAuth) -> G2pProviderBinding { + G2pProviderBinding::Http { + revision: "second-provider-v1".to_owned(), + submit_base_url: origin.to_owned(), + status_base_url: origin.to_owned(), + credential_identity: "second-provider-operator".to_owned(), + credential_ref: SecretReference::new("secret:file/provider-token").unwrap(), + auth, + settings: json!({"tenant": "pilot-beta"}), + } +} + +fn pin() -> ProviderPackPin { + ProviderPackPin { + id: "second-provider".to_owned(), + version: "1".to_owned(), + digest: format!("sha256:{}", "a".repeat(64)), + } +} + +fn instruction() -> DisbursementInstruction { + DisbursementInstruction { + record_id: Uuid::parse_str("00000000-0000-4000-8000-000000000200").unwrap(), + instruction_id: Uuid::parse_str("00000000-0000-4000-8000-000000000201").unwrap(), + instruction_version: 1, + instruction_digest: "a".repeat(64), + institution_id: "ministry-social-protection".to_owned(), + service_id: "cash-transfer".to_owned(), + programme_id: "cash-programme".to_owned(), + cycle_id: "cycle-2026-11".to_owned(), + beneficiary_id: "beneficiary-001".to_owned(), + beneficiary_destination: "254700000002".to_owned(), + funding_account_id: "programme-account".to_owned(), + amount_minor: 100_000, + currency: "KES".to_owned(), + currency_scale: 2, + } +} + +fn snapshot(provider: G2pProviderBinding, provider_pack: ProviderPackPin) -> G2pConnectionSnapshot { + G2pConnectionSnapshot { + institution_id: "ministry-social-protection".to_owned(), + service_id: "cash-transfer".to_owned(), + programme_id: "cash-programme".to_owned(), + funding_account_id: "programme-account".to_owned(), + currency: "KES".to_owned(), + currency_scale: 2, + provider_pack, + funding_party_key: "ACCOUNT_ID".to_owned(), + recipient_party_key: "MSISDN".to_owned(), + provider, + registry: G2pRegistryBinding { + base_url: "https://breg.invalid/".to_owned(), + credential_identity: "g2p-adapter".to_owned(), + credential_ref: SecretReference::new("secret:file/provider-token").unwrap(), + record_route: "disbursement-instructions".to_owned(), + record_type: "disbursement-instruction".to_owned(), + read_profile: "g2p-adapter-read".to_owned(), + bind_action: "bind-payout-attempt".to_owned(), + bind_profile: "g2p-adapter-bind".to_owned(), + report_action: "record-provider-confirmation".to_owned(), + report_profile: "g2p-adapter-report".to_owned(), + }, + } +} + +fn observation(correlation_id: &str) -> ProviderObservation { + ProviderObservation { + correlation_id: correlation_id.to_owned(), + provider_reference: "provider-001".to_owned(), + state: ProviderObservationState::ProviderConfirmed, + money: ProviderObservedMoney { + minor_units: "100000".to_owned(), + currency: "KES".to_owned(), + scale: 2, + }, + parties: vec![ + ProviderObservedParty { + role: ProviderPartyRole::Funding, + key: "ACCOUNT_ID".to_owned(), + value: "programme-account".to_owned(), + }, + ProviderObservedParty { + role: ProviderPartyRole::Recipient, + key: "MSISDN".to_owned(), + value: "254700000002".to_owned(), + }, + ], + } +} + +fn write_secret(path: std::path::PathBuf, value: &[u8]) { + std::fs::write(&path, value).unwrap(); + std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600)).unwrap(); +} diff --git a/crates/registry-adapter/tests/payment_config.rs b/crates/registry-adapter/tests/payment_config.rs index bb3a904dac..c1585c3d16 100644 --- a/crates/registry-adapter/tests/payment_config.rs +++ b/crates/registry-adapter/tests/payment_config.rs @@ -7,14 +7,90 @@ fn config() -> Value { "allowedClients":["payment-coordinator"], "requiredScope":"payments:collections", "binding": { "simulation":true, "currency":"USD", "currencyScale":2, "providerCredentialRef":"secret:env/SIMULATOR_TOKEN", "providerCredentialIdentity":"synthetic-producer", "replayWindowSeconds":3600, - "provider": { "baseUrl":"http://127.0.0.1:8099/", "tenant":"pilot", "biller":"ministry", - "billerName":"Ministry", "callbackUrl":"https://programme.example.test/callback", "payerFiBic":"SIMBANK" }, + "provider": { "type":"simulator", "connection": { + "baseUrl":"http://127.0.0.1:8099/", "tenant":"pilot", "biller":"ministry", + "billerName":"Ministry", "callbackUrl":"https://programme.example.test/callback", "payerFiBic":"SIMBANK" } }, "registry": { "baseUrl":"http://127.0.0.1:8080/", "readProfile":"payment-adapter-reporter", "bindProfile":"payment-adapter-binder", "receiptProfile":"payment-adapter-reporter", "recordType":"service-fee-bill", "recordRoute":"service-fee-bills", "bindAction":"bind-payment-attempt", "receiptAction":"record-payment-receipt", "credentialRef":"secret:env/PAYMENT_REPORTER_TOKEN", "credentialIdentity":"payment-adapter" } } }] }) } + +fn mifos_config() -> Value { + let mut value = config(); + value["connections"][0]["binding"]["simulation"] = json!(false); + value["connections"][0]["binding"]["currency"] = json!("KES"); + value["connections"][0]["binding"]["provider"] = json!({ + "type": "mifos", + "connection": { + "channelBaseUrl": "https://channel.example.test/", + "bulkBaseUrl": "https://bulk.example.test/", + "operationsBaseUrl": "https://operations.example.test/", + "tenant": "pilot", + "paymentScheme": "mpesa" + }, + "payer": { + "financialAddressKey": "MSISDN", + "payerIdKey": "ACCOUNTID" + }, + "transactionType": { + "scenario": "MPESA", + "subScenario": "BUYGOODS", + "initiator": "PAYEE", + "initiatorType": "BUSINESS" + } + }); + value +} + +fn http_config() -> Value { + let mut value = mifos_config(); + value["connections"][0]["binding"]["providerPack"] = json!({ + "id": "mifos-payment-hub", "version": "1", + "digest": format!("sha256:{}", "a".repeat(64)) + }); + value["connections"][0]["binding"]["provider"] = json!({ + "type": "http", + "submitBaseUrl": "https://channel.example.test/", + "statusBaseUrl": "https://operations.example.test/", + "settings": {"tenant":"pilot", "paymentScheme":"mpesa"} + }); + value +} + +#[test] +fn mapped_http_provider_requires_a_pin_and_bounded_separate_origins() { + let valid: PaymentsConfig = serde_json::from_value(http_config()).unwrap(); + assert!(valid.validate().is_ok()); + let mut missing_pin = http_config(); + missing_pin["connections"][0]["binding"] + .as_object_mut() + .unwrap() + .remove("providerPack"); + assert!(serde_json::from_value::(missing_pin) + .unwrap() + .validate() + .is_err()); + for pointer in [ + "/connections/0/binding/provider/submitBaseUrl", + "/connections/0/binding/provider/statusBaseUrl", + ] { + let mut invalid = http_config(); + *invalid.pointer_mut(pointer).unwrap() = json!("http://example.test/path"); + assert!(serde_json::from_value::(invalid) + .unwrap() + .validate() + .is_err()); + } + let mut oversized = http_config(); + oversized["connections"][0]["binding"]["provider"]["settings"]["tenant"] = + json!("x".repeat(20_000)); + assert!(serde_json::from_value::(oversized) + .unwrap() + .validate() + .is_err()); +} #[test] fn connections_are_explicit_scoped_and_synthetic() { let valid: PaymentsConfig = serde_json::from_value(config()).unwrap(); @@ -40,13 +116,39 @@ fn connections_are_explicit_scoped_and_synthetic() { .validate() .is_err()); } + +#[test] +fn only_mifos_can_back_a_non_simulation_collection() { + let live: PaymentsConfig = serde_json::from_value(mifos_config()).unwrap(); + assert!(live.validate().is_ok()); + + let mut simulated_mifos = mifos_config(); + simulated_mifos["connections"][0]["binding"]["simulation"] = json!(true); + assert!(serde_json::from_value::(simulated_mifos) + .unwrap() + .validate() + .is_err()); + + let mut unknown = mifos_config(); + unknown["connections"][0]["binding"]["provider"]["connection"]["extra"] = json!(true); + assert!(serde_json::from_value::(unknown).is_err()); + + for provider in [ + json!({"connection": {}}), + json!({"type": "unknown", "connection": {}}), + ] { + let mut invalid = mifos_config(); + invalid["connections"][0]["binding"]["provider"] = provider; + assert!(serde_json::from_value::(invalid).is_err()); + } +} #[test] fn routing_or_credential_identity_changes_the_frozen_binding() { let original: PaymentsConfig = serde_json::from_value(config()).unwrap(); let digest = original.connections[0].binding.revision().unwrap(); for pointer in [ - "/connections/0/binding/provider/tenant", - "/connections/0/binding/provider/biller", + "/connections/0/binding/provider/connection/tenant", + "/connections/0/binding/provider/connection/biller", "/connections/0/binding/providerCredentialIdentity", "/connections/0/binding/registry/credentialIdentity", ] { @@ -57,6 +159,24 @@ fn routing_or_credential_identity_changes_the_frozen_binding() { } } +#[test] +fn the_reviewed_provider_pack_is_part_of_the_frozen_binding() { + let original: PaymentsConfig = serde_json::from_value(config()).unwrap(); + let original_revision = original.connections[0].binding.revision().unwrap(); + let mut pinned = config(); + pinned["connections"][0]["binding"]["providerPack"] = json!({ + "id": "mifos-payment-hub", + "version": "1", + "digest": format!("sha256:{}", "a".repeat(64)) + }); + let pinned: PaymentsConfig = serde_json::from_value(pinned).unwrap(); + assert!(pinned.validate().is_ok()); + assert_ne!( + original_revision, + pinned.connections[0].binding.revision().unwrap() + ); +} + fn attempt() -> registry_adapter::payments::model::Attempt { use registry_adapter::payments::model::{Attempt, BillSnapshot}; use registry_payment_protocol::Money; @@ -88,12 +208,14 @@ fn attempt() -> registry_adapter::payments::model::Attempt { bill_snapshot_digest: bill.digest().unwrap(), binding_revision: binding.revision().unwrap(), provider_command: bill.provider_command(&binding).unwrap(), + provider_command_digest: None, bill, binding, bind_action: None, bound: false, first_send_at: None, transfer_id: None, + provider_acceptance: None, observation: None, report_action: None, receipt_digest: None, @@ -110,7 +232,7 @@ fn provider_identity_is_stable_bounded_and_independent_of_store_or_credentials() independent.binding.provider_credential_ref = serde_json::from_value(json!("secret:env/ROTATED_TOKEN")).unwrap(); independent.binding.replay_window_seconds = 1; - independent.binding.provider.base_url.pop(); // Equivalent root URL without its slash. + independent.binding.simulator_mut().unwrap().base_url.pop(); // Equivalent root URL without its slash. assert_eq!( first.provider_command, independent @@ -118,8 +240,9 @@ fn provider_identity_is_stable_bounded_and_independent_of_store_or_credentials() .provider_command(&independent.binding) .unwrap() ); - assert_eq!(first.provider_command.request_id.len(), 12); - assert_eq!(first.provider_command.bill_id.len(), 10); + let command = first.provider_command.simulator().unwrap(); + assert_eq!(command.request_id.len(), 12); + assert_eq!(command.bill_id.len(), 10); first.provider_command.validate().unwrap(); let mut other_bill = first.bill.clone(); other_bill.bill_id = uuid::Uuid::new_v4(); @@ -134,10 +257,11 @@ fn v1_provider_identity_matches_the_retained_command_golden_vector() { let mut saved = attempt(); saved.bill.bill_id = "9303e1c2-9c2c-4c1e-8ecb-06bfa02d70cf".parse().unwrap(); let command = saved.bill.provider_command(&saved.binding).unwrap(); - assert_eq!(command.request_id, "90RVxEyflgHP"); - assert_eq!(command.bill_id, "emwUe0iT0w"); - assert_eq!(command.rtp_id, 1_364_251_476_903_812); - saved.binding.provider.base_url.pop(); + let simulator = command.simulator().unwrap(); + assert_eq!(simulator.request_id, "90RVxEyflgHP"); + assert_eq!(simulator.bill_id, "emwUe0iT0w"); + assert_eq!(simulator.rtp_id, 1_364_251_476_903_812); + saved.binding.simulator_mut().unwrap().base_url.pop(); assert_eq!( saved.bill.provider_command(&saved.binding).unwrap(), command @@ -148,9 +272,10 @@ fn v1_provider_identity_matches_the_retained_command_golden_vector() { fn sequence_based_development_snapshots_are_held_without_rewriting_the_command() { use registry_payment_protocol::PaymentProblemCode; let mut saved = attempt(); - saved.provider_command.request_id = "p1".into(); - saved.provider_command.rtp_id = 1; - saved.provider_command.bill_id = "1".into(); + let command = saved.provider_command.simulator_mut().unwrap(); + command.request_id = "p1".into(); + command.rtp_id = 1; + command.bill_id = "1".into(); let prior = serde_json::to_value(&saved).unwrap(); assert_eq!( saved.validate_integrity(), @@ -159,6 +284,161 @@ fn sequence_based_development_snapshots_are_held_without_rewriting_the_command() assert_eq!(serde_json::to_value(&saved).unwrap(), prior); } +#[test] +fn restored_http_attempt_refuses_tampered_prepared_request_bytes_or_authority() { + use registry_adapter::payments::{ + model::{digest, BillSnapshot, CollectionProviderCommand, HttpCollectionCommand}, + provider_mapping::{PaymentEndpointRole, PaymentHttpMethod, PreparedProviderRequest}, + }; + use registry_payment_protocol::Money; + use std::collections::BTreeMap; + + let parsed: PaymentsConfig = serde_json::from_value(http_config()).unwrap(); + let binding = parsed.connections[0].binding.clone(); + let bill = BillSnapshot { + bill_id: uuid::Uuid::new_v4(), + bill_version: 1, + bill_digest: "a".repeat(64), + institution_id: "ministry".into(), + service_id: "permit".into(), + request_id: "request-1".into(), + tariff_id: "permit-fee".into(), + tariff_version: 1, + tariff_digest: "b".repeat(64), + payer_id: "payer-1".into(), + payer_financial_address: "254700000001".into(), + money: Money { + value: "25.00".into(), + currency: "KES".into(), + scale: 2, + }, + simulation: false, + }; + let provider_command = CollectionProviderCommand::Http(HttpCollectionCommand { + intent: bill.http_intent(&binding).unwrap(), + prepared_submit: PreparedProviderRequest { + provider_pack: binding.provider_pack.clone().unwrap(), + role: PaymentEndpointRole::CollectionSubmit, + method: PaymentHttpMethod::Post, + path: "/channel/collection".into(), + query: BTreeMap::new(), + headers: BTreeMap::from([("platform-tenantid".into(), "pilot".into())]), + body: Some(br#"{"amount":{"amount":"25.00","currency":"KES"}}"#.to_vec()), + }, + }); + let mut saved = registry_adapter::payments::model::Attempt { + id: uuid::Uuid::new_v4(), + connection: "fees".into(), + principal: "caller".into(), + bill_snapshot_digest: bill.digest().unwrap(), + binding_revision: binding.revision().unwrap(), + provider_command_digest: Some(digest(&provider_command).unwrap()), + provider_command, + bill, + binding, + bind_action: None, + bound: false, + first_send_at: None, + transfer_id: None, + provider_acceptance: None, + observation: None, + report_action: None, + receipt_digest: None, + receipt: None, + }; + assert!(saved.validate_integrity().is_ok()); + + if let CollectionProviderCommand::Http(command) = &mut saved.provider_command { + command + .prepared_submit + .headers + .insert("authorization".into(), "script-selected".into()); + } else { + unreachable!() + } + saved.provider_command_digest = Some(digest(&saved.provider_command).unwrap()); + assert_eq!( + saved.validate_integrity(), + Err(registry_payment_protocol::PaymentProblemCode::Unavailable) + ); + + if let CollectionProviderCommand::Http(command) = &mut saved.provider_command { + command.prepared_submit.headers.remove("authorization"); + command.prepared_submit.body = Some(br#"{ "amount": "25.00" }"#.to_vec()); + } else { + unreachable!() + } + saved.provider_command_digest = Some(digest(&saved.provider_command).unwrap()); + assert_eq!( + saved.validate_integrity(), + Err(registry_payment_protocol::PaymentProblemCode::Unavailable) + ); +} + +#[test] +fn mifos_command_uses_only_the_frozen_bill_and_provider_mapping() { + use registry_adapter::payments::model::{BillSnapshot, CollectionProviderCommand}; + use registry_payment_mifos_connector::{PartyIdentifier, TransactionType}; + use registry_payment_protocol::Money; + + let parsed: PaymentsConfig = serde_json::from_value(mifos_config()).unwrap(); + let binding = &parsed.connections[0].binding; + let bill = BillSnapshot { + bill_id: "9303e1c2-9c2c-4c1e-8ecb-06bfa02d70cf".parse().unwrap(), + bill_version: 4, + bill_digest: "a".repeat(64), + institution_id: "ministry".into(), + service_id: "permit".into(), + request_id: "request-1".into(), + tariff_id: "permit-fee".into(), + tariff_version: 2, + tariff_digest: "b".repeat(64), + payer_id: "payer-account-1".into(), + payer_financial_address: "254700000001".into(), + money: Money { + value: "25.00".into(), + currency: "KES".into(), + scale: 2, + }, + simulation: false, + }; + let CollectionProviderCommand::Mifos(command) = bill.provider_command(binding).unwrap() else { + panic!("live Mifos binding must create a Mifos command"); + }; + assert_eq!( + command.payer, + [ + PartyIdentifier { + key: "MSISDN".into(), + value: "254700000001".into() + }, + PartyIdentifier { + key: "ACCOUNTID".into(), + value: "payer-account-1".into() + }, + ] + ); + assert_eq!(command.money.amount, "25.00"); + assert_eq!(command.money.currency, "KES"); + assert_eq!( + command.transaction_type, + TransactionType { + scenario: "MPESA".into(), + sub_scenario: "BUYGOODS".into(), + initiator: "PAYEE".into(), + initiator_type: "BUSINESS".into(), + } + ); + command.validate().unwrap(); + + let mut changed = bill.clone(); + changed.money.value = "25.01".into(); + assert_ne!( + CollectionProviderCommand::Mifos(command), + changed.provider_command(binding).unwrap() + ); +} + #[test] fn persisted_command_cannot_be_borrowed_by_another_bill_or_provider_namespace() { use registry_adapter::payments::model::Attempt; @@ -173,8 +453,14 @@ fn persisted_command_cannot_be_borrowed_by_another_bill_or_provider_namespace() ("/bill/serviceId", json!("another-service")), ("/bill/requestId", json!("another-request")), ("/bill/tariffDigest", json!("d".repeat(64))), - ("/binding/provider/tenant", json!("another-tenant")), - ("/binding/provider/biller", json!("another-biller")), + ( + "/binding/provider/connection/tenant", + json!("another-tenant"), + ), + ( + "/binding/provider/connection/biller", + json!("another-biller"), + ), ( "/binding/providerCredentialIdentity", json!("another-producer"), @@ -195,16 +481,15 @@ fn persisted_command_cannot_be_borrowed_by_another_bill_or_provider_namespace() #[cfg(feature = "schema")] #[test] -fn authored_connections_cannot_enable_live_mode_or_omit_scope() { +fn authored_connections_allow_the_strict_mifos_shape_and_require_scope() { let schema = serde_json::to_value(schemars::schema_for!(PaymentsConfig)).unwrap(); let compiled = jsonschema::JSONSchema::options() .with_draft(jsonschema::Draft::Draft202012) .compile(&schema) .unwrap(); assert!(compiled.is_valid(&config())); - let mut value = config(); - value["connections"][0]["binding"]["simulation"] = json!(false); - assert!(!compiled.is_valid(&value)); + assert!(compiled.is_valid(&mifos_config())); + assert!(compiled.is_valid(&http_config())); let mut value = config(); value["connections"][0] .as_object_mut() @@ -213,5 +498,24 @@ fn authored_connections_cannot_enable_live_mode_or_omit_scope() { assert!(!compiled.is_valid(&value)); let mut value = config(); value["connections"] = json!([]); - assert!(!compiled.is_valid(&value)); + assert!(compiled.is_valid(&value)); + assert!(serde_json::from_value::(value) + .unwrap() + .validate() + .is_err()); + for provider_type in [None, Some("unknown")] { + let mut value = mifos_config(); + match provider_type { + Some(provider_type) => { + value["connections"][0]["binding"]["provider"]["type"] = json!(provider_type); + } + None => { + value["connections"][0]["binding"]["provider"] + .as_object_mut() + .unwrap() + .remove("type"); + } + } + assert!(!compiled.is_valid(&value)); + } } diff --git a/crates/registry-adapter/tests/payment_provider_mapping.rs b/crates/registry-adapter/tests/payment_provider_mapping.rs new file mode 100644 index 0000000000..7477b9ab5a --- /dev/null +++ b/crates/registry-adapter/tests/payment_provider_mapping.rs @@ -0,0 +1,725 @@ +// SPDX-License-Identifier: Apache-2.0 + +use std::collections::BTreeMap; + +use registry_adapter::payments::pack::{PaymentProviderAuth, PaymentProviderPack}; +use registry_adapter::payments::provider_mapping::{ + MappedProviderResponse, PaymentEndpointRole, PaymentHttpMethod, PaymentMappingError, + PaymentMappingProgram, PreparedProviderRequest, ProviderAcceptance, ProviderHttpResponse, + ProviderObservationState, ProviderPartyRole, +}; +use serde_json::{json, Value}; + +const ALPHA: &str = r#" +fn alpha_submit_request(intent, settings, acceptance) { + if acceptance != () { throw "submit accepts no prior acceptance"; } + #{ + pathParameters: #{}, + query: #{}, + headers: #{"x-tenant": settings.tenant}, + body: #{ + payer: #{scheme: intent.source.scheme, identifier: intent.source.value}, + amount: #{minorUnits: intent.money.minorUnits, currency: intent.money.currency}, + clientReference: intent.correlationId + } + } +} + +fn alpha_submit_response(intent, settings, acceptance, response) { + if settings == () || acceptance != () || response.status != 202 { + throw "unexpected submit response"; + } + #{correlationId: intent.correlationId, references: #{transaction: response.body.transactionId}} +} + +fn alpha_status_request(intent, settings, acceptance) { + if settings == () || acceptance == () { throw "status needs acceptance"; } + #{ + pathParameters: #{id: acceptance.references.transaction}, + query: #{}, + headers: #{}, + body: () + } +} + +fn alpha_status_response(intent, settings, acceptance, response) { + if settings == () || acceptance == () || response.body.clientReference != intent.correlationId { + throw "correlation mismatch"; + } + #{ + correlationId: response.body.clientReference, + providerReference: response.body.transactionId, + state: if response.body.status == "DONE" { "provider-confirmed" } else { "pending" }, + money: #{ + minorUnits: response.body.amount.minorUnits, + currency: response.body.amount.currency, + scale: 2 + }, + parties: [ + #{role: "payer", key: response.body.payer.scheme, value: response.body.payer.identifier}, + #{role: "payer", key: response.body.payerId.scheme, value: response.body.payerId.identifier} + ] + } +} +"#; + +const BETA: &str = r#" +fn beta_submit_request(intent, settings, acceptance) { + if acceptance != () { throw "submit accepts no prior acceptance"; } + #{ + pathParameters: #{}, + query: #{channel: settings.channel}, + headers: #{}, + body: #{ + transfer: [intent.correlationId, intent.money.currency, intent.money.minorUnits], + account: intent.source.value + } + } +} + +fn beta_submit_response(intent, settings, acceptance, response) { + if settings == () || acceptance != () || response.status != 200 { + throw "unexpected submit response"; + } + #{correlationId: intent.correlationId, references: #{ticket: response.body.result.ticket}} +} + +fn beta_status_request(intent, settings, acceptance) { + if intent == () || settings == () || acceptance == () { throw "status needs context"; } + #{ + pathParameters: #{}, + query: #{ticket: acceptance.references.ticket}, + headers: #{}, + body: () + } +} + +fn beta_status_response(intent, settings, acceptance, response) { + if settings == () || acceptance == () || response.body.echo[0] != intent.correlationId { + throw "correlation mismatch"; + } + #{ + correlationId: response.body.echo[0], + providerReference: response.body.result.ticket, + state: if response.body.result.code == "7" { "provider-confirmed" } else { "pending" }, + money: #{ + minorUnits: response.body.echo[2], + currency: response.body.echo[1], + scale: 2 + }, + parties: [ + #{role: "payer", key: "account", value: response.body.account}, + #{role: "payer", key: "payer-id", value: response.body.payerId} + ] + } +} +"#; + +const G2P: &str = r#" +fn submit_request(intent, settings, acceptance) { + if settings == () || acceptance != () { throw "invalid submit context"; } + #{ + pathParameters: #{}, query: #{}, headers: #{}, + body: #{ + correlation: intent.correlationId, + debit: intent.funding.value, + credit: intent.recipient.value, + minorUnits: intent.money.minorUnits, + currency: intent.money.currency + } + } +} +fn submit_response(intent, settings, acceptance, response) { + if settings == () || acceptance != () { throw "invalid submit context"; } + #{correlationId: intent.correlationId, references: #{transfer: response.body.id}} +} +fn status_request(intent, settings, acceptance) { + if intent == () || settings == () || acceptance == () { throw "status needs context"; } + #{pathParameters: #{}, query: #{id: acceptance.references.transfer}, headers: #{}, body: ()} +} +fn status_response(intent, settings, acceptance, response) { + if settings == () || acceptance == () { throw "status needs context"; } + #{ + correlationId: response.body.correlation, + providerReference: response.body.id, + state: "provider-confirmed", + money: #{minorUnits: response.body.minorUnits, currency: response.body.currency, scale: 2}, + parties: [ + #{role: "funding", key: response.body.debit.scheme, value: response.body.debit.value}, + #{role: "recipient", key: response.body.credit.scheme, value: response.body.credit.value} + ] + } +} +"#; + +fn provider_pack(id: &str, script_path: &str, script: &str, beta: bool) -> String { + let prefix = if beta { "beta" } else { "alpha" }; + let (submit_path, status_path) = if beta { + ("/transfers", "/lookup") + } else { + ("/collections", "/transactions/{{id}}") + }; + format!( + r#"apiVersion: id.registrystack.org/formats/adapter/payment-provider-pack/v1alpha1 +kind: AdapterPaymentProviderPack +id: {id} +version: '1' +connector: adapter-payment-http/v1 +capabilities: [collection] +mapping: + collection: + auth: bearer + submit: + path: {submit_path} + request: {{file: {script_path}, entrypoint: {prefix}_submit_request}} + response: {{file: {script_path}, entrypoint: {prefix}_submit_response}} + status: + path: {status_path} + request: {{file: {script_path}, entrypoint: {prefix}_status_request}} + response: {{file: {script_path}, entrypoint: {prefix}_status_response}} + scripts: + - path: {script_path} + digest: {} +"#, + registry_platform_config::sha256_uri(script.as_bytes()) + ) +} + +fn compile(yaml: &str, path: &str, script: &str) -> PaymentMappingProgram { + let pack = PaymentProviderPack::from_yaml(yaml.as_bytes()).expect("pack decodes"); + pack.validate().expect("pack validates"); + PaymentMappingProgram::compile( + &pack, + yaml.as_bytes(), + &BTreeMap::from([(path.to_owned(), script.as_bytes().to_vec())]), + ) + .expect("mapping compiles") +} + +fn disbursement_pack(script: &str) -> String { + format!( + r#"apiVersion: id.registrystack.org/formats/adapter/payment-provider-pack/v1alpha1 +kind: AdapterPaymentProviderPack +id: g2p-pay +version: '1' +connector: adapter-payment-http/v1 +capabilities: [disbursement] +mapping: + disbursement: + auth: mifos-legacy-signature + submit: + path: /disbursements + request: {{file: scripts/g2p.rhai, entrypoint: submit_request}} + response: {{file: scripts/g2p.rhai, entrypoint: submit_response}} + status: + path: /disbursements/status + request: {{file: scripts/g2p.rhai, entrypoint: status_request}} + response: {{file: scripts/g2p.rhai, entrypoint: status_response}} + scripts: + - path: scripts/g2p.rhai + digest: {} +"#, + registry_platform_config::sha256_uri(script.as_bytes()) + ) +} + +fn intent() -> Value { + json!({ + "correlationId": "collect_123", + "money": {"minorUnits": 1250, "currency": "USD", "scale": 2}, + "source": {"scheme": "phone", "value": "+15550100"} + }) +} + +fn acceptance(mapped: MappedProviderResponse) -> ProviderAcceptance { + match mapped { + MappedProviderResponse::Acceptance(acceptance) => acceptance, + MappedProviderResponse::Observation(_) => panic!("submit returned an observation"), + } +} + +fn provider_response(status: u16, body: Value) -> ProviderHttpResponse { + ProviderHttpResponse { + status, + body: serde_json::to_vec(&body).expect("provider response serializes"), + } +} + +#[test] +fn compiled_provider_packs_remain_mapping_free() { + let simulator = PaymentProviderPack::from_yaml( + b"apiVersion: id.registrystack.org/formats/adapter/payment-provider-pack/v1alpha1\nkind: AdapterPaymentProviderPack\nid: payment-simulator\nversion: '1'\nconnector: simulator-p2g/v1\ncapabilities: [collection]\n", + ) + .expect("legacy simulator pack decodes"); + assert!(simulator.validate().is_ok()); + assert!(simulator.mapping.is_none()); +} + +#[test] +fn data_driven_operations_require_a_closed_auth_profile() { + let collection_yaml = provider_pack("alpha-pay", "scripts/alpha.rhai", ALPHA, false); + let collection = PaymentProviderPack::from_yaml(collection_yaml.as_bytes()) + .expect("collection pack decodes"); + assert_eq!( + collection + .mapping + .as_ref() + .and_then(|mapping| mapping.collection.as_ref()) + .map(|operation| operation.auth), + Some(PaymentProviderAuth::Bearer) + ); + + let disbursement_yaml = disbursement_pack(G2P); + let disbursement = PaymentProviderPack::from_yaml(disbursement_yaml.as_bytes()) + .expect("disbursement pack decodes"); + assert_eq!( + disbursement + .mapping + .as_ref() + .and_then(|mapping| mapping.disbursement.as_ref()) + .map(|operation| operation.auth), + Some(PaymentProviderAuth::MifosLegacySignature) + ); + + let missing = collection_yaml.replace(" auth: bearer\n", ""); + assert!(PaymentProviderPack::from_yaml(missing.as_bytes()).is_err()); + let unknown = collection_yaml.replace("auth: bearer", "auth: provider-default"); + assert!(PaymentProviderPack::from_yaml(unknown.as_bytes()).is_err()); +} + +#[test] +fn two_provider_wire_shapes_run_through_the_same_mapping_program() { + let alpha_yaml = provider_pack("alpha-pay", "scripts/alpha.rhai", ALPHA, false); + let alpha = compile(&alpha_yaml, "scripts/alpha.rhai", ALPHA); + let settings = json!({"tenant": "district-7"}); + let alpha_request = alpha + .prepare( + PaymentEndpointRole::CollectionSubmit, + &intent(), + &settings, + None, + ) + .expect("alpha request maps"); + assert_eq!(alpha_request.method, PaymentHttpMethod::Post); + assert_eq!(alpha_request.path, "/collections"); + assert_eq!( + alpha_request.provider_pack.digest, + registry_platform_config::sha256_uri(alpha_yaml.as_bytes()) + ); + assert_eq!(alpha_request.headers["x-tenant"], "district-7"); + assert_eq!( + serde_json::from_slice::(alpha_request.body.as_deref().expect("POST body")) + .expect("canonical JSON body"), + json!({ + "payer": {"scheme": "phone", "identifier": "+15550100"}, + "amount": {"minorUnits": 1250, "currency": "USD"}, + "clientReference": "collect_123" + }) + ); + assert_eq!( + alpha_request.body.as_deref(), + Some( + br#"{"amount":{"currency":"USD","minorUnits":1250},"clientReference":"collect_123","payer":{"identifier":"+15550100","scheme":"phone"}}"# + .as_slice() + ), + "the retained bytes are canonical and need no remapping before send" + ); + let retained = serde_json::to_vec(&alpha_request).expect("request serializes"); + assert_eq!( + serde_json::from_slice::(&retained).expect("request deserializes"), + alpha_request + ); + let alpha_acceptance = acceptance( + alpha + .interpret( + PaymentEndpointRole::CollectionSubmit, + &intent(), + &settings, + None, + &provider_response(202, json!({"transactionId": "alpha-77"})), + ) + .expect("alpha acceptance maps"), + ); + let alpha_status = alpha + .prepare( + PaymentEndpointRole::CollectionStatus, + &intent(), + &settings, + Some(&alpha_acceptance), + ) + .expect("alpha status maps"); + assert_eq!(alpha_status.method, PaymentHttpMethod::Get); + assert_eq!(alpha_status.path, "/transactions/alpha-77"); + for dot_segment in [".", ".."] { + let unsafe_acceptance = ProviderAcceptance { + correlation_id: "collect_123".to_owned(), + references: BTreeMap::from([("transaction".to_owned(), dot_segment.to_owned())]), + }; + assert!(alpha + .prepare( + PaymentEndpointRole::CollectionStatus, + &intent(), + &settings, + Some(&unsafe_acceptance), + ) + .is_err()); + } + + let beta_yaml = provider_pack("beta-pay", "scripts/beta.rhai", BETA, true); + let beta = compile(&beta_yaml, "scripts/beta.rhai", BETA); + let beta_settings = json!({"channel": "cashier"}); + let beta_request = beta + .prepare( + PaymentEndpointRole::CollectionSubmit, + &intent(), + &beta_settings, + None, + ) + .expect("beta request maps"); + assert_eq!(beta_request.method, PaymentHttpMethod::Post); + assert_eq!(beta_request.path, "/transfers"); + assert_eq!(beta_request.query["channel"], "cashier"); + assert_eq!( + serde_json::from_slice::(beta_request.body.as_deref().expect("POST body")) + .expect("canonical JSON body"), + json!({ + "transfer": ["collect_123", "USD", 1250], + "account": "+15550100" + }) + ); + let beta_acceptance = acceptance( + beta.interpret( + PaymentEndpointRole::CollectionSubmit, + &intent(), + &beta_settings, + None, + &provider_response(200, json!({"result": {"ticket": "B-998"}})), + ) + .expect("beta acceptance maps"), + ); + let observed = beta + .interpret( + PaymentEndpointRole::CollectionStatus, + &intent(), + &beta_settings, + Some(&beta_acceptance), + &provider_response( + 200, + json!({ + "result": {"ticket": "B-998", "code": 7}, + "echo": ["collect_123", "USD", 1250], + "account": "+15550100", + "payerId": "payer-42" + }), + ), + ) + .expect("beta observation maps"); + let MappedProviderResponse::Observation(observed) = observed else { + panic!("status returned an acceptance"); + }; + assert_eq!(observed.state, ProviderObservationState::ProviderConfirmed); + assert_eq!(observed.provider_reference, "B-998"); + assert_eq!(observed.money.minor_units, "1250"); + assert_eq!(observed.parties[0].role, ProviderPartyRole::Payer); + assert_eq!(observed.parties[1].role, ProviderPartyRole::Payer); + + let duplicate_keys = BETA.replace( + r#"key: "payer-id", value: response.body.payerId"#, + r#"key: "account", value: response.body.payerId"#, + ); + assert_ne!(duplicate_keys, BETA, "fixture must duplicate the payer key"); + let duplicate_yaml = provider_pack( + "duplicate-payer-keys", + "scripts/beta.rhai", + &duplicate_keys, + true, + ); + let duplicate = compile(&duplicate_yaml, "scripts/beta.rhai", &duplicate_keys); + assert!(duplicate + .interpret( + PaymentEndpointRole::CollectionStatus, + &intent(), + &beta_settings, + Some(&beta_acceptance), + &provider_response( + 200, + json!({ + "result": {"ticket": "B-998", "code": 7}, + "echo": ["collect_123", "USD", 1250], + "account": "+15550100", + "payerId": "payer-42" + }), + ), + ) + .is_err()); +} + +#[test] +fn restored_prepared_request_refuses_tampered_serialized_authority() { + let yaml = provider_pack("alpha-pay", "scripts/alpha.rhai", ALPHA, false); + let program = compile(&yaml, "scripts/alpha.rhai", ALPHA); + let request = program + .prepare( + PaymentEndpointRole::CollectionSubmit, + &intent(), + &json!({"tenant": "district-7"}), + None, + ) + .expect("request maps"); + request + .validate_restored( + PaymentEndpointRole::CollectionSubmit, + program.provider_pack(), + ) + .expect("untampered retained request validates"); + + let serialized = serde_json::to_value(&request).expect("request serializes"); + let mut tampered = Vec::new(); + + let mut path = serialized.clone(); + path["path"] = json!("/.."); + tampered.push(path); + + let mut header = serialized.clone(); + header["headers"]["x-http-method-override"] = json!("DELETE"); + tampered.push(header); + + let mut header_value = serialized.clone(); + header_value["headers"]["x-tenant"] = json!("district-7\r\ninjected: true"); + tampered.push(header_value); + + let mut query = serialized.clone(); + query["query"][""] = json!("invalid-name"); + tampered.push(query); + + let mut method = serialized.clone(); + method["method"] = json!("GET"); + tampered.push(method); + + let mut role = serialized.clone(); + role["role"] = json!("disbursement-submit"); + tampered.push(role); + + let mut body = serialized.clone(); + body["body"] = + serde_json::to_value(br#"{ "amount": 1 }"#.to_vec()).expect("tampered bytes serialize"); + tampered.push(body); + + let mut pin = serialized; + pin["providerPack"]["digest"] = json!(registry_platform_config::sha256_uri(b"other pack")); + tampered.push(pin); + + for value in tampered { + let restored: PreparedProviderRequest = + serde_json::from_value(value).expect("tampered request remains structurally decodable"); + assert_eq!( + restored.validate_restored( + PaymentEndpointRole::CollectionSubmit, + program.provider_pack(), + ), + Err(PaymentMappingError::RestoredRequestInvalid) + ); + } +} + +#[test] +fn the_mapping_boundary_refuses_unpinned_scripts_and_transport_authority() { + let yaml = provider_pack("alpha-pay", "scripts/alpha.rhai", ALPHA, false); + let pack = PaymentProviderPack::from_yaml(yaml.as_bytes()).expect("pack decodes"); + let changed = format!("{ALPHA}\n// changed after review"); + assert!(PaymentMappingProgram::compile( + &pack, + yaml.as_bytes(), + &BTreeMap::from([("scripts/alpha.rhai".to_owned(), changed.into_bytes())]), + ) + .is_err()); + + let forbidden = r#" +fn request(intent, settings, acceptance) { + #{ + pathParameters: #{}, query: #{}, + headers: #{"authorization": settings.secret}, + body: intent + } +} + +fn response(intent, settings, acceptance, response) { + #{correlationId: intent.correlationId, references: #{id: response.body.id}} +} +"#; + for header in [ + "authorization", + "x-http-method-override", + "x-method-override", + "x-original-url", + "x-rewrite-url", + "te", + "trailer", + "keep-alive", + "proxy-connection", + ] { + let forbidden = forbidden.replace("authorization", header); + let forbidden_yaml = format!( + r#"apiVersion: id.registrystack.org/formats/adapter/payment-provider-pack/v1alpha1 +kind: AdapterPaymentProviderPack +id: forbidden-pay +version: '1' +connector: adapter-payment-http/v1 +capabilities: [collection] +mapping: + collection: + auth: bearer + submit: + path: /collect + request: {{file: scripts/forbidden.rhai, entrypoint: request}} + response: {{file: scripts/forbidden.rhai, entrypoint: response}} + scripts: + - path: scripts/forbidden.rhai + digest: {} +"#, + registry_platform_config::sha256_uri(forbidden.as_bytes()) + ); + let program = compile(&forbidden_yaml, "scripts/forbidden.rhai", &forbidden); + assert!(program + .prepare( + PaymentEndpointRole::CollectionSubmit, + &intent(), + &json!({"secret": "must-not-cross"}), + None, + ) + .is_err()); + } +} + +#[test] +fn disbursement_observation_requires_funding_and_recipient_roles() { + let yaml = disbursement_pack(G2P); + let program = compile(&yaml, "scripts/g2p.rhai", G2P); + let intent = json!({ + "correlationId": "g2p_123", + "money": {"minorUnits": 9900, "currency": "USD", "scale": 2}, + "funding": {"scheme": "account", "value": "treasury"}, + "recipient": {"scheme": "wallet", "value": "beneficiary-7"} + }); + let settings = json!({}); + let accepted = acceptance( + program + .interpret( + PaymentEndpointRole::DisbursementSubmit, + &intent, + &settings, + None, + &provider_response(202, json!({"id": "transfer-7"})), + ) + .expect("acceptance maps"), + ); + let response = provider_response( + 200, + json!({ + "id": "transfer-7", + "correlation": "g2p_123", + "minorUnits": 9900, + "currency": "USD", + "debit": {"scheme": "account", "value": "treasury"}, + "credit": {"scheme": "wallet", "value": "beneficiary-7"} + }), + ); + let mapped = program + .interpret( + PaymentEndpointRole::DisbursementStatus, + &intent, + &settings, + Some(&accepted), + &response, + ) + .expect("role-complete observation maps"); + let MappedProviderResponse::Observation(observed) = mapped else { + panic!("status returned acceptance"); + }; + assert_eq!(observed.parties[0].role, ProviderPartyRole::Funding); + assert_eq!(observed.parties[1].role, ProviderPartyRole::Recipient); + + let missing_funding = G2P.replace("role: \"funding\"", "role: \"recipient\""); + let refused_yaml = disbursement_pack(&missing_funding); + let refused = compile(&refused_yaml, "scripts/g2p.rhai", &missing_funding); + assert!(refused + .interpret( + PaymentEndpointRole::DisbursementStatus, + &intent, + &settings, + Some(&accepted), + &response, + ) + .is_err()); +} + +#[test] +fn provider_json_numbers_reach_response_scripts_as_exact_strings() { + let script = r#" +fn submit_request(intent, settings, acceptance) { + if acceptance != () { throw "submit accepts no prior acceptance"; } + #{pathParameters: #{}, query: #{}, headers: #{}, body: intent} +} +fn submit_response(intent, settings, acceptance, response) { + if acceptance != () { throw "submit accepts no prior acceptance"; } + #{ + correlationId: intent.correlationId, + references: #{amount: response.body.amount, sequence: response.body.sequence} + } +} +"#; + let yaml = format!( + r#"apiVersion: id.registrystack.org/formats/adapter/payment-provider-pack/v1alpha1 +kind: AdapterPaymentProviderPack +id: exact-number-pay +version: '1' +connector: adapter-payment-http/v1 +capabilities: [collection] +mapping: + collection: + auth: bearer + submit: + path: /collect + request: {{file: scripts/exact.rhai, entrypoint: submit_request}} + response: {{file: scripts/exact.rhai, entrypoint: submit_response}} + scripts: + - path: scripts/exact.rhai + digest: {} +"#, + registry_platform_config::sha256_uri(script.as_bytes()) + ); + let program = compile(&yaml, "scripts/exact.rhai", script); + let mapped = program + .interpret( + PaymentEndpointRole::CollectionSubmit, + &intent(), + &json!({}), + None, + &ProviderHttpResponse { + status: 202, + body: br#"{"amount":12.50,"sequence":9007199254740993}"#.to_vec(), + }, + ) + .expect("exact provider number spellings map"); + let accepted = acceptance(mapped); + assert_eq!(accepted.references["amount"], "12.50"); + assert_eq!(accepted.references["sequence"], "9007199254740993"); + + for invalid in [ + br#"{"amount":12.50,"amount":12.50}"#.as_slice(), + br#"{"amount":12.50"#.as_slice(), + ] { + assert!(program + .interpret( + PaymentEndpointRole::CollectionSubmit, + &intent(), + &json!({}), + None, + &ProviderHttpResponse { + status: 202, + body: invalid.to_vec(), + }, + ) + .is_err()); + } +} diff --git a/crates/registry-adapter/tests/payment_provider_pack.rs b/crates/registry-adapter/tests/payment_provider_pack.rs new file mode 100644 index 0000000000..d6039af6a0 --- /dev/null +++ b/crates/registry-adapter/tests/payment_provider_pack.rs @@ -0,0 +1,17 @@ +// SPDX-License-Identifier: Apache-2.0 +use registry_adapter::payments::pack::{PaymentProviderPack, ProviderPackPin}; + +const PACK: &str = "apiVersion: id.registrystack.org/formats/adapter/payment-provider-pack/v1alpha1\nkind: AdapterPaymentProviderPack\nid: payment-simulator\nversion: '1'\nconnector: simulator-p2g/v1\ncapabilities: [collection]\n"; + +#[test] +fn a_payment_connection_pins_the_exact_provider_pack() { + let pack = PaymentProviderPack::from_yaml(PACK.as_bytes()).unwrap(); + let pin = ProviderPackPin { + id: "payment-simulator".into(), + version: "1".into(), + digest: registry_platform_config::sha256_uri(PACK.as_bytes()), + }; + assert!(pack.check_pin(&pin, PACK.as_bytes()).is_ok()); + let changed = PACK.replace("simulator-p2g/v1", "mifos-ph-ee/v1"); + assert!(pack.check_pin(&pin, changed.as_bytes()).is_err()); +} diff --git a/crates/registry-adapter/tests/payment_service.rs b/crates/registry-adapter/tests/payment_service.rs index 180d242624..f03f2e6b68 100644 --- a/crates/registry-adapter/tests/payment_service.rs +++ b/crates/registry-adapter/tests/payment_service.rs @@ -5,9 +5,11 @@ use async_trait::async_trait; use registry_adapter::{ payments::{ config::{PaymentBinding, PaymentsConfig}, - model::{BillSnapshot, PreparedRegistryAction}, + model::{digest, BillSnapshot, CollectionProviderCommand, PreparedRegistryAction}, + pack::PaymentProviderPack, + provider_mapping::{PaymentMappingProgram, PaymentMappingRegistry, ProviderAcceptance}, registry::{BillState, BillView, RegistryPort}, - service::{PaymentService, ProviderPort}, + service::{PaymentService, ProviderPort, ProviderSubmission, SyntheticProvider}, store::{migrate, PaymentStore}, }, serve::Caller, @@ -15,10 +17,12 @@ use registry_adapter::{ use registry_payment_protocol::{ CollectionState, Money, PaymentProblemCode as Error, RequestCollection, }; -use registry_payment_simulator_connector::{ConnectorError, Observation, ProviderCommand}; +use registry_payment_simulator_connector::{ConnectorError, Observation}; +use registry_platform_config::{SecretProvider, SecretResolver}; use serde_json::{json, Map, Value}; use std::{ - collections::HashMap, + collections::BTreeMap, + os::unix::fs::PermissionsExt, sync::{ atomic::{AtomicBool, AtomicUsize, Ordering}, Arc, Mutex, @@ -30,10 +34,31 @@ fn config() -> PaymentsConfig { serde_json::from_value(json!({"connections":[{ "id":"fees","institutionId":"ministry","serviceId":"permit","allowedClients":["coordinator"],"requiredScope":"payments:collections", "binding":{"simulation":true,"currency":"USD","currencyScale":2,"providerCredentialRef":"secret:env/SIMULATOR_TOKEN","providerCredentialIdentity":"producer","replayWindowSeconds":3600, - "provider":{"baseUrl":"http://127.0.0.1:8099/","tenant":"pilot","biller":"ministry","billerName":"Ministry","callbackUrl":"https://programme.example.test/callback","payerFiBic":"SIMBANK"}, + "provider":{"type":"simulator","connection":{"baseUrl":"http://127.0.0.1:8099/","tenant":"pilot","biller":"ministry","billerName":"Ministry","callbackUrl":"https://programme.example.test/callback","payerFiBic":"SIMBANK"}}, "registry":{"baseUrl":"http://127.0.0.1:8080/","recordType":"service-fee-bill","recordRoute":"service-fee-bills","readProfile":"reporter","bindProfile":"binder","receiptProfile":"reporter","bindAction":"bind-payment-attempt","receiptAction":"record-payment-receipt","credentialRef":"secret:env/REPORTER_TOKEN","credentialIdentity":"payment-adapter"} }}]})).unwrap() } +fn mifos_config() -> PaymentsConfig { + let mut value = serde_json::to_value(config()).unwrap(); + value["connections"][0]["binding"]["simulation"] = json!(false); + value["connections"][0]["binding"]["currency"] = json!("KES"); + value["connections"][0]["binding"]["provider"] = json!({ + "type": "mifos", + "connection": { + "channelBaseUrl": "https://channel.example.test/", + "bulkBaseUrl": "https://bulk.example.test/", + "operationsBaseUrl": "https://operations.example.test/", + "tenant": "pilot", + "paymentScheme": "mpesa" + }, + "payer": {"financialAddressKey": "MSISDN", "payerIdKey": "ACCOUNTID"}, + "transactionType": { + "scenario": "MPESA", "subScenario": "BUYGOODS", + "initiator": "PAYEE", "initiatorType": "BUSINESS" + } + }); + serde_json::from_value(value).unwrap() +} fn caller() -> Caller { Caller { reference: "workflow-service".into(), @@ -155,7 +180,7 @@ impl RegistryPort for Registry { } struct Provider { registry: Arc, - commands: Mutex>, + commands: Mutex>, tenants: Mutex>, lose_ack: AtomicBool, confirmed: AtomicBool, @@ -167,39 +192,42 @@ impl ProviderPort for Provider { async fn submit( &self, binding: &PaymentBinding, - command: &ProviderCommand, - ) -> Result { + command: &CollectionProviderCommand, + ) -> Result { assert_eq!( self.registry.bill.lock().unwrap().state, BillState::AttemptBound, "binding must commit before provider dispatch" ); self.sends.fetch_add(1, Ordering::SeqCst); - self.tenants - .lock() - .unwrap() - .push(binding.provider.tenant.clone()); + self.tenants.lock().unwrap().push(provider_tenant(binding)); let mut commands = self.commands.lock().unwrap(); - if let Some(prior) = commands.get(&command.rtp_id) { - assert_eq!(prior, command); - } else { - commands.insert(command.rtp_id, command.clone()); + if !commands.contains(command) { + commands.push(command.clone()); } if self.lose_ack.swap(false, Ordering::SeqCst) { return Err(ConnectorError::Unknown); } - Ok(format!("transfer-{}", command.rtp_id)) + let transfer_id = match command { + CollectionProviderCommand::Simulator(command) => format!("transfer-{}", command.rtp_id), + CollectionProviderCommand::Mifos(command) => { + format!("transfer-{}", command.correlation_id) + } + CollectionProviderCommand::Http(_) => return Err(ConnectorError::Configuration), + }; + Ok(ProviderSubmission { + transfer_id, + acceptance: None, + }) } async fn observe( &self, binding: &PaymentBinding, - _: &ProviderCommand, + _: &CollectionProviderCommand, _: &str, + _: Option<&ProviderAcceptance>, ) -> Result { - self.tenants - .lock() - .unwrap() - .push(binding.provider.tenant.clone()); + self.tenants.lock().unwrap().push(provider_tenant(binding)); let confirmed = self.confirmed.load(Ordering::SeqCst); let failed = self.failed.load(Ordering::SeqCst); Ok(Observation { @@ -216,6 +244,22 @@ impl ProviderPort for Provider { }) } } + +fn provider_tenant(binding: &PaymentBinding) -> String { + match &binding.provider { + registry_adapter::payments::config::CollectionProvider::Simulator { connection } => { + connection.tenant.clone() + } + registry_adapter::payments::config::CollectionProvider::Mifos { connection, .. } => { + connection.tenant.clone() + } + registry_adapter::payments::config::CollectionProvider::Http { settings, .. } => settings + .get("tenant") + .and_then(Value::as_str) + .unwrap_or("http") + .to_owned(), + } +} async fn setup() -> (PaymentStore, Arc, Arc) { let url = std::env::var("ADAPTER_TEST_DATABASE_URL") .expect("postgres-test requires ADAPTER_TEST_DATABASE_URL"); @@ -239,7 +283,7 @@ async fn setup() -> (PaymentStore, Arc, Arc) { }); let provider = Arc::new(Provider { registry: registry.clone(), - commands: Mutex::new(HashMap::new()), + commands: Mutex::new(Vec::new()), tenants: Mutex::new(Vec::new()), lose_ack: AtomicBool::new(false), confirmed: AtomicBool::new(false), @@ -339,7 +383,11 @@ async fn lost_bind_provider_and_receipt_responses_recover_without_new_effects() ); drop(service); let mut changed = config(); - changed.connections[0].binding.provider.tenant = "new-tenant".into(); + changed.connections[0] + .binding + .simulator_mut() + .unwrap() + .tenant = "new-tenant".into(); let service = PaymentService::new( changed.clone(), store.clone(), @@ -502,3 +550,707 @@ async fn uncertain_attempt_is_held_after_its_original_replay_window() { assert_eq!(provider.sends.load(Ordering::SeqCst), 1); assert_eq!(provider.commands.lock().unwrap().len(), 1); } + +#[tokio::test] +async fn an_unknown_mifos_submit_is_never_sent_again() { + let (store, registry, provider) = setup().await; + { + let mut bill = registry.bill.lock().unwrap(); + bill.snapshot.simulation = false; + bill.snapshot.money.currency = "KES".into(); + bill.snapshot.payer_financial_address = "254700000001".into(); + bill.snapshot.payer_id = "payer-account-1".into(); + } + provider.lose_ack.store(true, Ordering::SeqCst); + let request = RequestCollection { + bill_id: registry.bill.lock().unwrap().snapshot.bill_id, + bill_version: 1, + }; + let service = + PaymentService::new(mifos_config(), store, registry.clone(), provider.clone()).unwrap(); + assert_eq!( + service + .request("fees", &caller(), "mifos-key", &request) + .await + .unwrap_err(), + Error::OutcomeUnknown + ); + assert_eq!( + service + .request("fees", &caller(), "mifos-key", &request) + .await + .unwrap_err(), + Error::RecoveryHeld + ); + assert_eq!(provider.sends.load(Ordering::SeqCst), 1); + assert_eq!(provider.commands.lock().unwrap().len(), 1); +} + +#[tokio::test] +async fn mifos_provider_success_cannot_advance_the_registry_bill_to_paid() { + let (store, registry, provider) = setup().await; + { + let mut bill = registry.bill.lock().unwrap(); + bill.snapshot.simulation = false; + bill.snapshot.money.currency = "KES".into(); + bill.snapshot.payer_financial_address = "254700000001".into(); + bill.snapshot.payer_id = "payer-account-1".into(); + } + let request = RequestCollection { + bill_id: registry.bill.lock().unwrap().snapshot.bill_id, + bill_version: 1, + }; + let service = + PaymentService::new(mifos_config(), store, registry.clone(), provider.clone()).unwrap(); + let accepted = service + .request("fees", &caller(), "mifos-key", &request) + .await + .unwrap(); + provider.confirmed.store(true, Ordering::SeqCst); + assert_eq!( + service + .read("fees", &caller(), accepted.collection_id) + .await + .unwrap() + .state, + CollectionState::Confirmed + ); + assert_eq!( + service + .record_receipt("fees", &caller(), "mifos-receipt", accepted.collection_id,) + .await + .unwrap_err(), + Error::RecoveryHeld + ); + assert_eq!(registry.reports.load(Ordering::SeqCst), 0); + assert_eq!(registry.bill.lock().unwrap().state, BillState::AttemptBound); +} + +const SECOND_PROVIDER_SCRIPT: &str = r#" +fn submit_request(intent, settings, acceptance) { + if acceptance != () { throw "submit accepts no prior acceptance"; } + #{ + pathParameters: #{}, + query: #{mode: "direct"}, + headers: #{"x-provider-tenant": settings.tenant}, + body: #{ + command: #{id: intent.correlationId}, + debtor: #{account: intent.payerId, address: intent.payerFinancialAddress}, + total: intent.money + } + } +} + +fn submit_response(intent, settings, acceptance, response) { + if settings == () || acceptance != () || response.status != 202 + || response.body.correlation != intent.correlationId { + throw "submit response mismatch"; + } + #{correlationId: intent.correlationId, references: #{payment: response.body.receipt}} +} + +fn status_request(intent, settings, acceptance) { + if intent == () || acceptance == () { throw "status needs retained context"; } + #{ + pathParameters: #{payment: acceptance.references.payment}, + query: #{view: "full"}, + headers: #{"x-provider-tenant": settings.tenant}, + body: () + } +} + +fn status_response(intent, settings, acceptance, response) { + if settings == () || acceptance == () || response.status != 200 + || response.body.correlation != intent.correlationId + || response.body.receipt != acceptance.references.payment { + throw "status response mismatch"; + } + #{ + correlationId: response.body.correlation, + providerReference: response.body.receipt, + state: if response.body.state == "complete" { "provider-confirmed" } else { "pending" }, + money: #{ + minorUnits: response.body.total.minorUnits, + currency: response.body.total.currency, + scale: intent.money.scale + }, + parties: [ + #{role: "payer", key: "account", value: response.body.debtor.account}, + #{role: "payer", key: "address", value: response.body.debtor.address} + ] + } +} +"#; + +fn generic_provider_pack(id: &str, submit_path: &str, status_path: &str) -> Vec { + format!( + r#"apiVersion: id.registrystack.org/formats/adapter/payment-provider-pack/v1alpha1 +kind: AdapterPaymentProviderPack +id: {id} +version: '1' +connector: adapter-payment-http/v1 +capabilities: [collection] +mapping: + collection: + auth: bearer + submit: + path: {submit_path} + request: {{file: scripts/provider.rhai, entrypoint: submit_request}} + response: {{file: scripts/provider.rhai, entrypoint: submit_response}} + status: + path: {status_path} + request: {{file: scripts/provider.rhai, entrypoint: status_request}} + response: {{file: scripts/provider.rhai, entrypoint: status_response}} + scripts: + - path: scripts/provider.rhai + digest: {} +"#, + registry_platform_config::sha256_uri(SECOND_PROVIDER_SCRIPT.as_bytes()) + ) + .into_bytes() +} + +fn second_provider_pack() -> Vec { + generic_provider_pack( + "second-provider", + "/v2/payments", + "/v2/payments/{{payment}}", + ) +} + +fn compile_provider(pack_bytes: &[u8]) -> PaymentMappingProgram { + let pack = PaymentProviderPack::from_yaml(pack_bytes).unwrap(); + PaymentMappingProgram::compile( + &pack, + pack_bytes, + &BTreeMap::from([( + "scripts/provider.rhai".to_owned(), + SECOND_PROVIDER_SCRIPT.as_bytes().to_vec(), + )]), + ) + .unwrap() +} + +#[derive(Clone)] +struct WireProviderState { + requests: Arc>>, + correlation: Arc>>, + mismatched_observation: Arc, + unknown_submit: Arc, +} + +struct WireRequest { + method: http::Method, + path: String, + query: Option, + authorization: Option, + tenant: Option, + content_type: Option, + body: Vec, +} + +async fn second_provider_submit( + axum::extract::State(state): axum::extract::State, + headers: http::HeaderMap, + uri: http::Uri, + body: axum::body::Bytes, +) -> impl axum::response::IntoResponse { + let decoded: Value = serde_json::from_slice(&body).unwrap(); + let correlation = decoded["command"]["id"].as_str().unwrap().to_owned(); + *state.correlation.lock().unwrap() = Some(correlation.clone()); + state.requests.lock().unwrap().push(WireRequest { + method: http::Method::POST, + path: uri.path().to_owned(), + query: uri.query().map(str::to_owned), + authorization: headers + .get(http::header::AUTHORIZATION) + .and_then(|value| value.to_str().ok()) + .map(str::to_owned), + tenant: headers + .get("x-provider-tenant") + .and_then(|value| value.to_str().ok()) + .map(str::to_owned), + content_type: headers + .get(http::header::CONTENT_TYPE) + .and_then(|value| value.to_str().ok()) + .map(str::to_owned), + body: body.to_vec(), + }); + let response_correlation = if state.unknown_submit.load(Ordering::SeqCst) { + "unmatched-correlation".to_owned() + } else { + correlation + }; + ( + http::StatusCode::ACCEPTED, + axum::Json(json!({"receipt":"beta-transfer-7","correlation":response_correlation})), + ) +} + +async fn second_provider_status( + axum::extract::State(state): axum::extract::State, + headers: http::HeaderMap, + uri: http::Uri, +) -> impl axum::response::IntoResponse { + state.requests.lock().unwrap().push(WireRequest { + method: http::Method::GET, + path: uri.path().to_owned(), + query: uri.query().map(str::to_owned), + authorization: headers + .get(http::header::AUTHORIZATION) + .and_then(|value| value.to_str().ok()) + .map(str::to_owned), + tenant: headers + .get("x-provider-tenant") + .and_then(|value| value.to_str().ok()) + .map(str::to_owned), + content_type: headers + .get(http::header::CONTENT_TYPE) + .and_then(|value| value.to_str().ok()) + .map(str::to_owned), + body: Vec::new(), + }); + let mismatch = state.mismatched_observation.load(Ordering::SeqCst); + let correlation = state.correlation.lock().unwrap().clone().unwrap(); + axum::Json(json!({ + "receipt":"beta-transfer-7", + "correlation":correlation, + "state":"complete", + "total":{"minorUnits":if mismatch { "2501" } else { "2500" },"currency":"KES","scale":2}, + "debtor":{"account":if mismatch { "other-payer" } else { "payer-account-1" },"address":"254700000001"} + })) +} + +fn generic_provider_config(origin: &str, pack_bytes: &[u8], id: &str) -> PaymentsConfig { + serde_json::from_value(json!({"connections":[{ + "id":"fees","institutionId":"ministry","serviceId":"permit", + "allowedClients":["coordinator"],"requiredScope":"payments:collections", + "binding":{ + "providerPack":{"id":id,"version":"1","digest":registry_platform_config::sha256_uri(pack_bytes)}, + "simulation":false,"currency":"KES","currencyScale":2, + "providerCredentialRef":"secret:file/provider-token","providerCredentialIdentity":"second-provider-operator", + "replayWindowSeconds":3600, + "provider":{"type":"http","submitBaseUrl":origin,"statusBaseUrl":origin,"settings":{"tenant":"pilot-beta"}}, + "registry":{"baseUrl":"http://127.0.0.1:8080/","recordType":"service-fee-bill","recordRoute":"service-fee-bills","readProfile":"reporter","bindProfile":"binder","receiptProfile":"reporter","bindAction":"bind-payment-attempt","receiptAction":"record-payment-receipt","credentialRef":"secret:env/UNUSED_REGISTRY_TOKEN","credentialIdentity":"payment-adapter"} + }}]})).unwrap() +} + +fn second_provider_config(origin: &str, pack_bytes: &[u8]) -> PaymentsConfig { + generic_provider_config(origin, pack_bytes, "second-provider") +} + +async fn start_wire_provider() -> (String, WireProviderState, tokio::task::JoinHandle<()>) { + let state = WireProviderState { + requests: Arc::new(Mutex::new(Vec::new())), + correlation: Arc::new(Mutex::new(None)), + mismatched_observation: Arc::new(AtomicBool::new(true)), + unknown_submit: Arc::new(AtomicBool::new(false)), + }; + let router = axum::Router::new() + .route("/v2/payments", axum::routing::post(second_provider_submit)) + .route( + "/v2/payments/{payment}", + axum::routing::get(second_provider_status), + ) + .route( + "/v2/a/payments", + axum::routing::post(second_provider_submit), + ) + .route( + "/v2/a/payments/{payment}", + axum::routing::get(second_provider_status), + ) + .route( + "/v2/b/payments", + axum::routing::post(second_provider_submit), + ) + .route( + "/v2/b/payments/{payment}", + axum::routing::get(second_provider_status), + ) + .with_state(state.clone()); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let origin = format!("http://{}/", listener.local_addr().unwrap()); + let server = tokio::spawn(async move { + axum::serve(listener, router).await.unwrap(); + }); + (origin, state, server) +} + +#[tokio::test] +async fn generic_http_host_freezes_one_post_and_uses_read_only_status_for_a_second_provider() { + let (origin, state, server) = start_wire_provider().await; + + let pack_bytes = second_provider_pack(); + let program = compile_provider(&pack_bytes); + let secret_root = tempfile::tempdir().unwrap(); + let token_path = secret_root.path().join("provider-token"); + let resolver = + Arc::new(SecretResolver::new([SecretProvider::File], secret_root.path()).unwrap()); + + let (store, registry, _) = setup().await; + { + let mut bill = registry.bill.lock().unwrap(); + bill.snapshot.simulation = false; + bill.snapshot.money.currency = "KES".into(); + bill.snapshot.payer_financial_address = "254700000001".into(); + bill.snapshot.payer_id = "payer-account-1".into(); + } + let config = second_provider_config(&origin, &pack_bytes); + let mut mappings = PaymentMappingRegistry::default(); + mappings.insert(program).unwrap(); + let provider = Arc::new(SyntheticProvider::new(resolver, Some(Arc::new(mappings)))); + let service = PaymentService::new(config, store.clone(), registry.clone(), provider).unwrap(); + let request = RequestCollection { + bill_id: registry.bill.lock().unwrap().snapshot.bill_id, + bill_version: 1, + }; + assert_eq!( + service + .request("fees", &caller(), "second-provider-request", &request) + .await + .unwrap_err(), + Error::Unavailable, + "a local credential failure must not consume the one-send grant" + ); + let preflight_failed = store + .find_bill("ministry", "permit", request.bill_id, request.bill_version) + .await + .unwrap() + .unwrap(); + assert!(preflight_failed.bound); + assert!(preflight_failed.first_send_at.is_none()); + assert!(preflight_failed.transfer_id.is_none()); + assert!(state.requests.lock().unwrap().is_empty()); + + std::fs::write(&token_path, b"test-only-provider-token").unwrap(); + std::fs::set_permissions(&token_path, std::fs::Permissions::from_mode(0o600)).unwrap(); + let accepted = service + .request("fees", &caller(), "second-provider-request", &request) + .await + .unwrap(); + + let saved = store.get(accepted.collection_id).await.unwrap(); + let CollectionProviderCommand::Http(command) = &saved.provider_command else { + panic!("the generic provider must retain its exact prepared request"); + }; + assert_eq!( + saved.provider_command_digest.as_ref(), + Some(&digest(&saved.provider_command).unwrap()) + ); + assert_eq!(command.prepared_submit.path, "/v2/payments"); + assert_eq!(command.prepared_submit.query["mode"], "direct"); + assert_eq!( + command.prepared_submit.headers["x-provider-tenant"], + "pilot-beta" + ); + let expected_body = registry_platform_canonical_json::canonicalize_json(&json!({ + "command":{"id":command.intent["correlationId"]}, + "debtor":{"account":"payer-account-1","address":"254700000001"}, + "total":{"minorUnits":2500,"currency":"KES","scale":2} + })) + .unwrap(); + assert_eq!(command.prepared_submit.body.as_ref(), Some(&expected_body)); + + { + let requests = state.requests.lock().unwrap(); + assert_eq!(requests.len(), 1); + let post = &requests[0]; + assert_eq!(post.method, http::Method::POST); + assert_eq!(post.path, "/v2/payments"); + assert_eq!(post.query.as_deref(), Some("mode=direct")); + assert!(post.authorization.as_deref() == Some("Bearer test-only-provider-token")); + assert_eq!(post.tenant.as_deref(), Some("pilot-beta")); + assert_eq!(post.content_type.as_deref(), Some("application/json")); + assert_eq!(post.body, expected_body); + } + + assert_eq!( + service + .read("fees", &caller(), accepted.collection_id) + .await + .unwrap_err(), + Error::ProviderProtocol, + "provider money or payer mismatch must fail closed" + ); + assert!(store + .get(accepted.collection_id) + .await + .unwrap() + .observation + .is_none()); + state.mismatched_observation.store(false, Ordering::SeqCst); + assert_eq!( + service + .read("fees", &caller(), accepted.collection_id) + .await + .unwrap() + .state, + CollectionState::Confirmed + ); + assert_eq!( + service + .record_receipt( + "fees", + &caller(), + "second-provider-receipt", + accepted.collection_id, + ) + .await + .unwrap_err(), + Error::RecoveryHeld + ); + assert_eq!(registry.reports.load(Ordering::SeqCst), 0); + assert_eq!(registry.bill.lock().unwrap().state, BillState::AttemptBound); + + let requests = state.requests.lock().unwrap(); + assert_eq!(requests.len(), 3); + assert_eq!( + requests + .iter() + .filter(|request| request.method == http::Method::POST) + .count(), + 1, + "status reads and receipt refusal must not repeat the provider effect" + ); + for get in requests + .iter() + .filter(|request| request.method == http::Method::GET) + { + assert_eq!(get.path, "/v2/payments/beta-transfer-7"); + assert_eq!(get.query.as_deref(), Some("view=full")); + assert!(get.authorization.as_deref() == Some("Bearer test-only-provider-token")); + assert_eq!(get.tenant.as_deref(), Some("pilot-beta")); + assert!(get.content_type.is_none()); + assert!(get.body.is_empty()); + } + drop(requests); + server.abort(); +} + +fn mapping_registry( + programs: impl IntoIterator, +) -> Arc { + let mut registry = PaymentMappingRegistry::default(); + for program in programs { + registry.insert(program).unwrap(); + } + Arc::new(registry) +} + +fn install_test_token(root: &std::path::Path) { + let path = root.join("provider-token"); + std::fs::write(&path, b"test-only-provider-token").unwrap(); + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600)).unwrap(); +} + +fn make_live_bill(registry: &Registry) { + let mut bill = registry.bill.lock().unwrap(); + bill.snapshot.simulation = false; + bill.snapshot.money.currency = "KES".into(); + bill.snapshot.payer_financial_address = "254700000001".into(); + bill.snapshot.payer_id = "payer-account-1".into(); +} + +#[tokio::test] +async fn retained_collection_selects_its_exact_pack_before_post_or_get() { + let (origin, state, server) = start_wire_provider().await; + state.mismatched_observation.store(false, Ordering::SeqCst); + let pack_a = + generic_provider_pack("provider-a", "/v2/a/payments", "/v2/a/payments/{{payment}}"); + let pack_b = + generic_provider_pack("provider-b", "/v2/b/payments", "/v2/b/payments/{{payment}}"); + let config_a = generic_provider_config(&origin, &pack_a, "provider-a"); + let config_b = generic_provider_config(&origin, &pack_b, "provider-b"); + + let secret_root = tempfile::tempdir().unwrap(); + install_test_token(secret_root.path()); + let resolver = + Arc::new(SecretResolver::new([SecretProvider::File], secret_root.path()).unwrap()); + let only_a = mapping_registry([compile_provider(&pack_a)]); + let only_b = mapping_registry([compile_provider(&pack_b)]); + let both = mapping_registry([compile_provider(&pack_a), compile_provider(&pack_b)]); + + let (accepted_store, accepted_registry, _) = setup().await; + make_live_bill(&accepted_registry); + let accepted_request = RequestCollection { + bill_id: accepted_registry.bill.lock().unwrap().snapshot.bill_id, + bill_version: 1, + }; + let service_a = PaymentService::new( + config_a.clone(), + accepted_store.clone(), + accepted_registry.clone(), + Arc::new(SyntheticProvider::new(resolver.clone(), Some(only_a))), + ) + .unwrap(); + let accepted_a = service_a + .request("fees", &caller(), "accepted-a", &accepted_request) + .await + .unwrap(); + assert_eq!(state.requests.lock().unwrap()[0].path, "/v2/a/payments"); + + let service_only_b = PaymentService::new( + config_b.clone(), + accepted_store.clone(), + accepted_registry.clone(), + Arc::new(SyntheticProvider::new( + resolver.clone(), + Some(only_b.clone()), + )), + ) + .unwrap(); + assert_eq!( + service_only_b + .read("fees", &caller(), accepted_a.collection_id) + .await + .unwrap_err(), + Error::Unavailable + ); + assert_eq!( + state.requests.lock().unwrap().len(), + 1, + "missing A must not GET" + ); + + let missing_secret_root = tempfile::tempdir().unwrap(); + let missing_resolver = + Arc::new(SecretResolver::new([SecretProvider::File], missing_secret_root.path()).unwrap()); + let (unsent_store, unsent_registry, _) = setup().await; + make_live_bill(&unsent_registry); + let unsent_request = RequestCollection { + bill_id: unsent_registry.bill.lock().unwrap().snapshot.bill_id, + bill_version: 1, + }; + let unsent_a = PaymentService::new( + config_a.clone(), + unsent_store.clone(), + unsent_registry.clone(), + Arc::new(SyntheticProvider::new( + missing_resolver.clone(), + Some(mapping_registry([compile_provider(&pack_a)])), + )), + ) + .unwrap(); + assert_eq!( + unsent_a + .request("fees", &caller(), "unsent-a", &unsent_request) + .await + .unwrap_err(), + Error::Unavailable + ); + install_test_token(missing_secret_root.path()); + let unsent_only_b = PaymentService::new( + config_b.clone(), + unsent_store, + unsent_registry, + Arc::new(SyntheticProvider::new(missing_resolver, Some(only_b))), + ) + .unwrap(); + assert_eq!( + unsent_only_b + .request("fees", &caller(), "unsent-a", &unsent_request) + .await + .unwrap_err(), + Error::Unavailable + ); + assert_eq!( + state.requests.lock().unwrap().len(), + 1, + "missing A must not POST" + ); + + let service_both = PaymentService::new( + config_b.clone(), + accepted_store, + accepted_registry, + Arc::new(SyntheticProvider::new(resolver.clone(), Some(both.clone()))), + ) + .unwrap(); + assert_eq!( + service_both + .read("fees", &caller(), accepted_a.collection_id) + .await + .unwrap() + .state, + CollectionState::Confirmed + ); + assert_eq!( + state.requests.lock().unwrap()[1].path, + "/v2/a/payments/beta-transfer-7" + ); + + let (new_store, new_registry, _) = setup().await; + make_live_bill(&new_registry); + let new_request = RequestCollection { + bill_id: new_registry.bill.lock().unwrap().snapshot.bill_id, + bill_version: 1, + }; + let new_b = PaymentService::new( + config_b, + new_store, + new_registry, + Arc::new(SyntheticProvider::new(resolver, Some(both))), + ) + .unwrap(); + new_b + .request("fees", &caller(), "new-b", &new_request) + .await + .unwrap(); + assert_eq!(state.requests.lock().unwrap()[2].path, "/v2/b/payments"); + server.abort(); +} + +#[tokio::test] +async fn unknown_generic_send_never_reauthorizes_the_retained_command() { + let (origin, state, server) = start_wire_provider().await; + state.unknown_submit.store(true, Ordering::SeqCst); + let pack = generic_provider_pack("provider-b", "/v2/b/payments", "/v2/b/payments/{{payment}}"); + let config = generic_provider_config(&origin, &pack, "provider-b"); + let secret_root = tempfile::tempdir().unwrap(); + install_test_token(secret_root.path()); + let resolver = + Arc::new(SecretResolver::new([SecretProvider::File], secret_root.path()).unwrap()); + let (store, registry, _) = setup().await; + make_live_bill(®istry); + let request = RequestCollection { + bill_id: registry.bill.lock().unwrap().snapshot.bill_id, + bill_version: 1, + }; + let service = PaymentService::new( + config, + store, + registry, + Arc::new(SyntheticProvider::new( + resolver, + Some(mapping_registry([compile_provider(&pack)])), + )), + ) + .unwrap(); + assert_eq!( + service + .request("fees", &caller(), "unknown-b", &request) + .await + .unwrap_err(), + Error::OutcomeUnknown + ); + state.unknown_submit.store(false, Ordering::SeqCst); + assert_eq!( + service + .request("fees", &caller(), "unknown-b", &request) + .await + .unwrap_err(), + Error::RecoveryHeld + ); + assert_eq!( + state + .requests + .lock() + .unwrap() + .iter() + .filter(|request| request.method == http::Method::POST) + .count(), + 1 + ); + server.abort(); +} diff --git a/crates/registry-adapterctl/Cargo.toml b/crates/registry-adapterctl/Cargo.toml index c57382f2c1..ea6fa6f302 100644 --- a/crates/registry-adapterctl/Cargo.toml +++ b/crates/registry-adapterctl/Cargo.toml @@ -33,6 +33,7 @@ graphql-parser.workspace = true # lane that tests the gates off must build registry-adapter alone. registry-adapter = { workspace = true, features = ["job-file", "job-postgres", "schema"] } registry-adapter-core = { workspace = true, features = ["schema"] } +registry-payment-mifos-connector.workspace = true registry-platform-buildinfo.workspace = true registry-platform-config = { workspace = true, features = ["schema"] } registry-platform-httputil.workspace = true diff --git a/crates/registry-adapterctl/src/lib.rs b/crates/registry-adapterctl/src/lib.rs index 53e0299a93..97bf7ce62c 100644 --- a/crates/registry-adapterctl/src/lib.rs +++ b/crates/registry-adapterctl/src/lib.rs @@ -22,6 +22,7 @@ mod fixtures; mod job; mod job_runtime; mod mapping; +mod payment_fixtures; mod payments; mod project; mod report; diff --git a/crates/registry-adapterctl/src/payment_fixtures.rs b/crates/registry-adapterctl/src/payment_fixtures.rs new file mode 100644 index 0000000000..4c4f03daaf --- /dev/null +++ b/crates/registry-adapterctl/src/payment_fixtures.rs @@ -0,0 +1,599 @@ +// SPDX-License-Identifier: Apache-2.0 +//! Offline replay of pinned provider request and response mappings. + +use registry_adapter::payments::{ + pack::{ConnectorKind, PaymentProviderPack}, + provider_mapping::{ + MappedProviderResponse, PaymentEndpointRole, PaymentMappingProgram, + PreparedProviderRequest, ProviderAcceptance, ProviderHttpResponse, + }, +}; +use registry_payment_mifos_connector::{ + build_batch_request, build_collection_request, parse_batch_acceptance, parse_batch_status, + parse_collection_acceptance, parse_collection_status, BatchAccepted, BatchCommand, + BatchObservation, CollectionAccepted, CollectionCommand, CollectionObservation, + CONNECTOR_PROFILE, +}; +use registry_platform_yaml::{ + ApiVersion, BoundedU32, EnvelopeRule, Expect, FormatSpec, LocalId, Reader, +}; +use serde::Deserialize; +use serde_json::Value; +use std::{collections::BTreeMap, path::Path}; + +pub(crate) const VERSION: &str = + "id.registrystack.org/formats/adapter/payment-provider-fixture/v1alpha1"; +pub(crate) const KIND: &str = "AdapterPaymentProviderFixture"; +pub(crate) const SCHEMA_ID: &str = "https://id.registrystack.org/schemas/adapter/payment-provider-fixture/payment-provider-fixture.v1alpha1.schema.json"; +const FORMAT: FormatSpec<'static> = FormatSpec { + kind: KIND, + envelope: EnvelopeRule::ApiVersionKind { + api_versions: &[ApiVersion::current(VERSION)], + retired_api_versions: &[], + }, + removed_keys: &[], +}; +const MAXIMUM_PROVIDER_RESPONSE_BYTES: usize = 65_536; + +struct Fixture { + connector_profile: String, + direction: Direction, + command: Value, + expected_request: Value, + acceptance: Exchange, + status: Exchange, +} + +/// Both the compiled legacy fixture and the reviewed pure-mapping fixture +/// share one authored envelope during the migration to generic providers. +#[derive(Deserialize, schemars::JsonSchema)] +#[serde( + remote = "Self", + rename_all = "kebab-case", + rename_all_fields = "camelCase", + deny_unknown_fields +)] +#[schemars(!remote, tag = "type")] +pub(crate) enum FixtureDocument { + Compiled { + connector_profile: String, + direction: Direction, + command: Value, + expected_request: Value, + acceptance: Exchange, + status: Exchange, + }, + Mapped { + direction: Direction, + intent: Value, + settings: Value, + submit: MappedExchange, + status: MappedExchange, + }, +} +registry_platform_yaml::tagged_union!(FixtureDocument); + +#[derive(Deserialize, schemars::JsonSchema)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub(crate) struct Exchange { + response: ProviderResponse, + expected: Value, +} + +#[derive(Deserialize, schemars::JsonSchema)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct ProviderResponse { + http_status: BoundedU32<100, 599>, + body: Value, +} + +#[derive(Deserialize, schemars::JsonSchema)] +#[serde(rename_all = "kebab-case")] +pub(crate) enum Direction { + P2gCollection, + G2pDisbursement, +} + +/// All errors are value-free so authored provider payloads never enter ctl reports. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum FixtureError { + Unavailable, + Refused, +} + +struct MappedFixture { + direction: Direction, + intent: Value, + settings: Value, + submit: MappedExchange, + status: MappedExchange, +} + +#[derive(Deserialize, schemars::JsonSchema)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub(crate) struct MappedExchange { + #[serde(default)] + acceptance: Option, + expected_request: Value, + response: MappedResponse, + expected: Value, +} + +#[derive(Deserialize, schemars::JsonSchema)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct FixtureAcceptance { + correlation_id: String, + #[schemars(schema_with = "local_id_string_map_schema")] + references: BTreeMap, +} + +fn local_id_string_map_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema { + let names = generator.subschema_for::(); + schemars::json_schema!({ + "type": "object", + "propertyNames": names, + "additionalProperties": generator.subschema_for::(), + }) +} + +impl From for ProviderAcceptance { + fn from(value: FixtureAcceptance) -> Self { + Self { + correlation_id: value.correlation_id, + references: value + .references + .into_iter() + .map(|(key, value)| (key.into_string(), value)) + .collect(), + } + } +} + +#[derive(Deserialize, schemars::JsonSchema)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct MappedResponse { + status: BoundedU32<100, 599>, + #[schemars(length(min = 1, max = 65_536))] + body_json: String, +} + +/// Compile the exact pack closure and replay a provider-neutral fixture. +pub(crate) fn replay_mapped( + fixture_path: &Path, + pack_path: &Path, + pack: &PaymentProviderPack, + pack_bytes: &[u8], +) -> Result<(), FixtureError> { + let program = compile_mapped_pack(pack_path, pack, pack_bytes)?; + let bytes = std::fs::read(fixture_path).map_err(|_| FixtureError::Unavailable)?; + let document = Reader::new(fixture_path.display().to_string()) + .decode::(&bytes, &Expect::one(&FORMAT)) + .map_err(|_| FixtureError::Refused)? + .value; + let FixtureDocument::Mapped { + direction, + intent, + settings, + submit, + status, + } = document + else { + return Err(FixtureError::Refused); + }; + let fixture = MappedFixture { + direction, + intent, + settings, + submit, + status, + }; + if fixture.submit.acceptance.is_some() || fixture.status.acceptance.is_none() { + return Err(FixtureError::Refused); + } + let (submit_role, status_role) = match fixture.direction { + Direction::P2gCollection => ( + PaymentEndpointRole::CollectionSubmit, + PaymentEndpointRole::CollectionStatus, + ), + Direction::G2pDisbursement => ( + PaymentEndpointRole::DisbursementSubmit, + PaymentEndpointRole::DisbursementStatus, + ), + }; + let submitted = program + .prepare(submit_role, &fixture.intent, &fixture.settings, None) + .map_err(|_| FixtureError::Refused)?; + compare_request(&submitted, fixture.submit.expected_request)?; + let response = provider_response(fixture.submit.response)?; + let accepted = program + .interpret( + submit_role, + &fixture.intent, + &fixture.settings, + None, + &response, + ) + .map_err(|_| FixtureError::Refused)?; + let MappedProviderResponse::Acceptance(accepted) = accepted else { + return Err(FixtureError::Refused); + }; + matches_expected(&accepted, fixture.submit.expected)?; + let retained: ProviderAcceptance = fixture + .status + .acceptance + .ok_or(FixtureError::Refused)? + .into(); + if retained != accepted { + return Err(FixtureError::Refused); + } + let status_request = program + .prepare( + status_role, + &fixture.intent, + &fixture.settings, + Some(&retained), + ) + .map_err(|_| FixtureError::Refused)?; + compare_request(&status_request, fixture.status.expected_request)?; + let response = provider_response(fixture.status.response)?; + let observed = program + .interpret( + status_role, + &fixture.intent, + &fixture.settings, + Some(&retained), + &response, + ) + .map_err(|_| FixtureError::Refused)?; + let MappedProviderResponse::Observation(observed) = observed else { + return Err(FixtureError::Refused); + }; + matches_expected(&observed, fixture.status.expected) +} + +/// Check every reviewed script even when no fixture is supplied. +pub(crate) fn compile_mapped_pack( + pack_path: &Path, + pack: &PaymentProviderPack, + pack_bytes: &[u8], +) -> Result { + if pack.connector != ConnectorKind::AdapterPaymentHttpV1 { + return Err(FixtureError::Refused); + } + let root = canonical_pack_root(pack_path)?; + let scripts = pack + .mapping + .as_ref() + .ok_or(FixtureError::Refused)? + .scripts + .iter() + .map(|entry| { + let path = std::fs::canonicalize(root.join(&entry.path)) + .map_err(|_| FixtureError::Unavailable)?; + if !path.starts_with(&root) || !path.is_file() { + return Err(FixtureError::Refused); + } + let bytes = std::fs::read(path).map_err(|_| FixtureError::Unavailable)?; + Ok((entry.path.clone(), bytes)) + }) + .collect::, FixtureError>>()?; + PaymentMappingProgram::compile(pack, pack_bytes, &scripts).map_err(|_| FixtureError::Refused) +} + +fn canonical_pack_root(pack_path: &Path) -> Result { + let pack_path = std::fs::canonicalize(pack_path).map_err(|_| FixtureError::Unavailable)?; + pack_path + .parent() + .map(Path::to_path_buf) + .ok_or(FixtureError::Unavailable) +} + +fn provider_response(response: MappedResponse) -> Result { + if response.body_json.is_empty() || response.body_json.len() > MAXIMUM_PROVIDER_RESPONSE_BYTES { + return Err(FixtureError::Refused); + } + Ok(ProviderHttpResponse { + status: response.status.get() as u16, + body: response.body_json.into_bytes(), + }) +} + +fn compare_request(actual: &PreparedProviderRequest, expected: Value) -> Result<(), FixtureError> { + let mut plan = serde_json::json!({ + "method": actual.method, + "path": actual.path, + "query": actual.query, + "headers": actual.headers, + }); + if let Some(bytes) = &actual.body { + plan["body"] = serde_json::from_slice(bytes).map_err(|_| FixtureError::Refused)?; + } + if plan == expected { + Ok(()) + } else { + Err(FixtureError::Refused) + } +} + +pub(crate) fn replay(path: &Path, connector: ConnectorKind) -> Result<(), FixtureError> { + if connector != ConnectorKind::MifosPhEeLegacyV1 { + return Err(FixtureError::Refused); + } + let bytes = std::fs::read(path).map_err(|_| FixtureError::Unavailable)?; + let decoded = Reader::new(path.display().to_string()) + .decode::(&bytes, &Expect::one(&FORMAT)) + .map_err(|_| FixtureError::Refused)?; + let FixtureDocument::Compiled { + connector_profile, + direction, + command, + expected_request, + acceptance, + status, + } = decoded.value + else { + return Err(FixtureError::Refused); + }; + let fixture = Fixture { + connector_profile, + direction, + command, + expected_request, + acceptance, + status, + }; + if fixture.connector_profile != CONNECTOR_PROFILE + || fixture.acceptance.response.http_status.get() != 200 + || fixture.status.response.http_status.get() != 200 + { + return Err(FixtureError::Refused); + } + let expected_request = fixture.expected_request; + let acceptance_body = + serde_json::to_vec(&fixture.acceptance.response.body).map_err(|_| FixtureError::Refused)?; + let status_body = + serde_json::to_vec(&fixture.status.response.body).map_err(|_| FixtureError::Refused)?; + match fixture.direction { + Direction::P2gCollection => { + let command: CollectionCommand = + serde_json::from_value(fixture.command).map_err(|_| FixtureError::Refused)?; + let request = build_collection_request(&command).map_err(|_| FixtureError::Refused)?; + let request: Value = + serde_json::from_slice(&request).map_err(|_| FixtureError::Refused)?; + let accepted = + parse_collection_acceptance(&acceptance_body).map_err(|_| FixtureError::Refused)?; + let observed = parse_collection_status(&command, &accepted, &status_body) + .map_err(|_| FixtureError::Refused)?; + matches_expected::(&accepted, fixture.acceptance.expected)?; + matches_expected::(&observed, fixture.status.expected)?; + if request != expected_request { + return Err(FixtureError::Refused); + } + } + Direction::G2pDisbursement => { + let command: BatchCommand = + serde_json::from_value(fixture.command).map_err(|_| FixtureError::Refused)?; + let request = build_batch_request(&command).map_err(|_| FixtureError::Refused)?; + let request: Value = + serde_json::from_slice(&request).map_err(|_| FixtureError::Refused)?; + let accepted = parse_batch_acceptance( + &command, + fixture.acceptance.response.http_status.get() as u16, + &acceptance_body, + ) + .map_err(|_| FixtureError::Refused)?; + let observed = parse_batch_status(&command, &accepted, &status_body) + .map_err(|_| FixtureError::Refused)?; + matches_expected::(&accepted, fixture.acceptance.expected)?; + matches_expected::(&observed, fixture.status.expected)?; + if request != expected_request { + return Err(FixtureError::Refused); + } + } + } + Ok(()) +} + +fn matches_expected(actual: &T, expected: Value) -> Result<(), FixtureError> { + let actual = serde_json::to_value(actual).map_err(|_| FixtureError::Refused)?; + if actual == expected { + Ok(()) + } else { + Err(FixtureError::Refused) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + const COLLECTION: &str = r#"apiVersion: id.registrystack.org/formats/adapter/payment-provider-fixture/v1alpha1 +kind: AdapterPaymentProviderFixture +type: compiled +connectorProfile: mifos-ph-ee-legacy/channel-v1.12.2+bulk-v1.12.1+operations-v1.17.1 +direction: p2g-collection +command: + correlationId: collection-1 + payer: [{key: MSISDN, value: '254700000001'}, {key: ACCOUNTID, value: bill-1}] + money: {amount: '25.50', currency: KES} + transactionType: {scenario: MPESA, subScenario: BUYGOODS, initiator: PAYEE, initiatorType: BUSINESS} +expectedRequest: + payer: [{key: MSISDN, value: '254700000001'}, {key: ACCOUNTID, value: bill-1}] + amount: {amount: '25.50', currency: KES} + transactionType: {scenario: MPESA, subScenario: BUYGOODS, initiator: PAYEE, initiatorType: BUSINESS} + customData: [] +acceptance: + response: {httpStatus: 200, body: {transactionId: tx-1}} + expected: {transactionId: tx-1, state: accepted} +status: + response: + httpStatus: 200 + body: {content: [{transactionId: tx-1, state: SUCCESS, amount: '25.50', currency: KES, clientCorrelationId: collection-1}]} + expected: {transactionId: tx-1, state: providerConfirmed, money: {amount: '25.50', currency: KES}} +"#; + + #[test] + fn replay_proves_exact_request_and_status_and_refuses_changed_money() { + let file = tempfile::NamedTempFile::new().unwrap(); + std::fs::write(file.path(), COLLECTION).unwrap(); + assert_eq!( + replay(file.path(), ConnectorKind::MifosPhEeLegacyV1), + Ok(()) + ); + let changed = COLLECTION.replace( + "amount: '25.50', currency: KES, clientCorrelationId", + "amount: '25.51', currency: KES, clientCorrelationId", + ); + std::fs::write(file.path(), changed).unwrap(); + assert_eq!( + replay(file.path(), ConnectorKind::MifosPhEeLegacyV1), + Err(FixtureError::Refused) + ); + } + + #[test] + fn replay_refuses_unknown_members_and_wrong_connector() { + let file = tempfile::NamedTempFile::new().unwrap(); + std::fs::write( + file.path(), + COLLECTION.replace( + "direction: p2g-collection", + "direction: p2g-collection\nsecret: exposed", + ), + ) + .unwrap(); + assert_eq!( + replay(file.path(), ConnectorKind::MifosPhEeLegacyV1), + Err(FixtureError::Refused) + ); + std::fs::write(file.path(), COLLECTION).unwrap(); + assert_eq!( + replay(file.path(), ConnectorKind::SimulatorP2gV1), + Err(FixtureError::Refused) + ); + std::fs::write(file.path(), COLLECTION.replace("type: compiled\n", "")).unwrap(); + assert_eq!( + replay(file.path(), ConnectorKind::MifosPhEeLegacyV1), + Err(FixtureError::Refused) + ); + } + + #[test] + fn mapped_fixture_checks_both_http_roles_and_observed_money() { + let directory = tempfile::tempdir().unwrap(); + let scripts = directory.path().join("scripts"); + std::fs::create_dir(&scripts).unwrap(); + let script = r#" +fn submit_request(intent, settings, acceptance) { + if settings == () || acceptance != () { throw "invalid submit"; } + #{pathParameters: #{}, query: #{}, headers: #{}, body: #{id: intent.correlationId}} +} +fn submit_response(intent, settings, acceptance, response) { + if settings == () || acceptance != () || response.status != 202 { throw "invalid response"; } + #{correlationId: intent.correlationId, references: #{transfer: response.body.id}} +} +fn status_request(intent, settings, acceptance) { + if intent == () || settings == () || acceptance == () { throw "invalid status"; } + #{pathParameters: #{}, query: #{id: acceptance.references.transfer}, headers: #{}, body: ()} +} +fn status_response(intent, settings, acceptance, response) { + if settings == () || acceptance == () { throw "invalid status"; } + #{correlationId: intent.correlationId, providerReference: response.body.id, + state: "provider-confirmed", + money: #{minorUnits: if response.body.amount == "100.00" { "10000" } else { "1" }, currency: intent.money.currency, scale: 2}, + parties: [#{role: "funding", key: "account", value: intent.funding}, + #{role: "recipient", key: "phone", value: intent.recipient}]} +} +"#; + std::fs::write(scripts.join("provider.rhai"), script).unwrap(); + let pack = format!( + "apiVersion: {api}\nkind: {kind}\nid: mapped-pay\nversion: '1'\nconnector: adapter-payment-http/v1\ncapabilities: [disbursement]\nmapping:\n disbursement:\n auth: bearer\n submit:\n path: /send\n request: {{file: scripts/provider.rhai, entrypoint: submit_request}}\n response: {{file: scripts/provider.rhai, entrypoint: submit_response}}\n status:\n path: /read\n request: {{file: scripts/provider.rhai, entrypoint: status_request}}\n response: {{file: scripts/provider.rhai, entrypoint: status_response}}\n scripts:\n - path: scripts/provider.rhai\n digest: {}\n", + registry_platform_config::sha256_uri(script.as_bytes()), + api = registry_adapter::payments::pack::API_VERSION, + kind = registry_adapter::payments::pack::KIND, + ); + let pack_path = directory.path().join("pack.yaml"); + std::fs::write(&pack_path, &pack).unwrap(); + let parsed = PaymentProviderPack::from_yaml(pack.as_bytes()).unwrap(); + let fixture = format!( + "apiVersion: {VERSION}\nkind: {KIND}\ntype: mapped\ndirection: g2p-disbursement\nintent:\n correlationId: transfer-1\n funding: account-1\n recipient: phone-1\n money: {{minorUnits: 10000, currency: USD, scale: 2}}\nsettings: {{tenant: pilot}}\nsubmit:\n expectedRequest:\n method: POST\n path: /send\n query: {{}}\n headers: {{}}\n body: {{id: transfer-1}}\n response: {{status: 202, bodyJson: '{{\"id\":\"tx-1\"}}'}}\n expected: {{correlationId: transfer-1, references: {{transfer: tx-1}}}}\nstatus:\n acceptance: {{correlationId: transfer-1, references: {{transfer: tx-1}}}}\n expectedRequest:\n method: GET\n path: /read\n query: {{id: tx-1}}\n headers: {{}}\n response: {{status: 200, bodyJson: '{{\"id\":\"tx-1\",\"amount\":100.00}}'}}\n expected:\n correlationId: transfer-1\n providerReference: tx-1\n state: provider-confirmed\n money: {{minorUnits: '10000', currency: USD, scale: 2}}\n parties:\n - {{role: funding, key: account, value: account-1}}\n - {{role: recipient, key: phone, value: phone-1}}\n" + ); + let fixture_path = directory.path().join("fixture.yaml"); + std::fs::write(&fixture_path, &fixture).unwrap(); + assert_eq!( + replay_mapped(&fixture_path, &pack_path, &parsed, pack.as_bytes()), + Ok(()) + ); + for invalid_status in [99, 600] { + std::fs::write( + &fixture_path, + fixture.replacen("status: 202", &format!("status: {invalid_status}"), 1), + ) + .unwrap(); + assert_eq!( + replay_mapped(&fixture_path, &pack_path, &parsed, pack.as_bytes()), + Err(FixtureError::Refused) + ); + } + std::fs::write( + &fixture_path, + fixture.replace("\"amount\":100.00", "\"amount\":100.01"), + ) + .unwrap(); + assert_eq!( + replay_mapped(&fixture_path, &pack_path, &parsed, pack.as_bytes()), + Err(FixtureError::Refused) + ); + std::fs::write( + &fixture_path, + fixture.replace( + "references: {transfer: tx-1}", + "references: {Transfer.ID: tx-1}", + ), + ) + .unwrap(); + assert_eq!( + replay_mapped(&fixture_path, &pack_path, &parsed, pack.as_bytes()), + Err(FixtureError::Refused) + ); + std::fs::write( + scripts.join("provider.rhai"), + format!("{script}\n// changed"), + ) + .unwrap(); + assert!(compile_mapped_pack(&pack_path, &parsed, pack.as_bytes()).is_err()); + } + + #[test] + fn mapped_response_body_and_bare_pack_path_are_bounded_without_normalization() { + let raw = r#"{"amount":100.00}"#; + let exact = provider_response(MappedResponse { + status: BoundedU32::<100, 599>::new(200).unwrap(), + body_json: raw.to_owned(), + }) + .unwrap(); + assert_eq!(exact.body, raw.as_bytes()); + + for body_json in [ + String::new(), + "x".repeat(MAXIMUM_PROVIDER_RESPONSE_BYTES + 1), + ] { + let response = MappedResponse { + status: BoundedU32::<100, 599>::new(200).unwrap(), + body_json, + }; + assert_eq!(provider_response(response), Err(FixtureError::Refused)); + } + + let file = tempfile::Builder::new() + .prefix("mapped-payment-pack-") + .suffix(".yaml") + .tempfile_in(".") + .unwrap(); + let bare = Path::new(file.path().file_name().unwrap()); + assert_eq!( + canonical_pack_root(bare).unwrap(), + std::fs::canonicalize(".").unwrap() + ); + } +} diff --git a/crates/registry-adapterctl/src/payments.rs b/crates/registry-adapterctl/src/payments.rs index a2dac6a3f0..84a7431f02 100644 --- a/crates/registry-adapterctl/src/payments.rs +++ b/crates/registry-adapterctl/src/payments.rs @@ -1,7 +1,11 @@ // SPDX-License-Identifier: Apache-2.0 //! Offline payment configuration checks; neither command resolves credentials. +use crate::payment_fixtures::{self, FixtureError}; use clap::{Args, Subcommand}; use registry_adapter::payments::config::{PaymentsConfig, API_VERSION, KIND}; +use registry_adapter::payments::pack::{ + ConnectorKind, PaymentCapability, PaymentProviderAuth, PaymentProviderPack, +}; use registry_platform_config::{RuntimeConfigLoader, RuntimeEnvelope, DEFAULT_STAND_IN}; use registry_platform_yaml::{Diagnostic, Report}; use serde_json::{json, Value}; @@ -14,11 +18,23 @@ pub struct PaymentsArgs { } #[derive(Debug, Subcommand)] pub enum PaymentsCommand { + /// Validate one reviewed payment provider pack without a deployment. + CheckPack { + /// Provider pack file to validate. + #[arg(value_name = "FILE")] + file: PathBuf, + }, /// Validate one AdapterPayments file without fetching credentials or services. Check { /// AdapterPayments configuration file to validate. #[arg(value_name = "FILE")] file: PathBuf, + /// Exact provider pack pinned by the payment connections. + #[arg(long, value_name = "FILE")] + provider_pack: Option, + /// Offline provider request and response fixtures to check. + #[arg(long, value_name = "FILE")] + fixtures: Vec, /// Refuse warnings as well as errors. #[arg(long)] deny_warnings: bool, @@ -28,12 +44,35 @@ pub enum PaymentsCommand { /// AdapterPayments configuration file whose contract is exported. #[arg(value_name = "FILE")] file: PathBuf, + /// Exact provider pack pinned by the payment connections. + #[arg(long, value_name = "FILE")] + provider_pack: Option, + }, + /// Replay provider mappings without connecting to Mifos or BReg. + Fixtures { + #[command(subcommand)] + command: PaymentsFixturesCommand, + }, +} + +#[derive(Debug, Subcommand)] +pub enum PaymentsFixturesCommand { + /// Compare the pinned provider request and response mappings with fixtures. + Replay { + #[arg(value_name = "FILE")] + file: PathBuf, + #[arg(long, value_name = "FILE")] + provider_pack: PathBuf, + #[arg(long, value_name = "FILE", required = true)] + fixtures: Vec, }, } pub fn command_name(command: &PaymentsCommand) -> &'static str { match command { + PaymentsCommand::CheckPack { .. } => "payments check-pack", PaymentsCommand::Check { .. } => "payments check", PaymentsCommand::Contract { .. } => "payments contract", + PaymentsCommand::Fixtures { .. } => "payments fixtures replay", } } pub struct PaymentCheck { @@ -44,12 +83,39 @@ pub struct PaymentCheck { } pub fn run(command: &PaymentsCommand) -> PaymentCheck { - let (file, deny_warnings) = match command { + if let PaymentsCommand::CheckPack { file } = command { + return check_pack(file); + } + let (file, provider_pack, fixtures, deny_warnings) = match command { PaymentsCommand::Check { file, + provider_pack, + fixtures, deny_warnings, - } => (file, *deny_warnings), - PaymentsCommand::Contract { file } => (file, false), + } => ( + file, + provider_pack.as_deref(), + fixtures.as_slice(), + *deny_warnings, + ), + PaymentsCommand::Contract { + file, + provider_pack, + } => (file, provider_pack.as_deref(), &[][..], false), + PaymentsCommand::Fixtures { + command: + PaymentsFixturesCommand::Replay { + file, + provider_pack, + fixtures, + }, + } => ( + file, + Some(provider_pack.as_path()), + fixtures.as_slice(), + false, + ), + PaymentsCommand::CheckPack { .. } => unreachable!("handled above"), }; let absolute = match std::fs::canonicalize(file) { Ok(path) => path, @@ -80,7 +146,150 @@ pub fn run(command: &PaymentsCommand) -> PaymentCheck { "The payment connections were refused.", "Check connection scopes, unique caller identities, currency and synthetic provider bindings; then retry.")); } else { + match provider_pack { + Some(path) => match std::fs::read(path) { + Ok(bytes) => match PaymentProviderPack::from_yaml(&bytes) { + Ok(pack) => { + if pack.validate().is_err() { + additional.push(check.error_at( + KIND, + "adapter.payment.provider-pack-refused", + "/connections", + "The payment provider pack was refused.", + "Correct the provider pack and retry.", + )); + } + if pack.connector == ConnectorKind::AdapterPaymentHttpV1 + && payment_fixtures::compile_mapped_pack(path, &pack, &bytes) + .is_err() + { + additional.push(check.error_at( + KIND, + "adapter.payment.provider-pack-script-refused", + "/connections", + "The payment provider scripts were refused.", + "Check the complete script inventory, digests and entrypoints.", + )); + } + for connection in &loaded.config.connections { + if pack.connector != connection.binding.connector_kind() + || !pack.capabilities.contains(&PaymentCapability::Collection) + || connection + .binding + .provider_pack + .as_ref() + .is_none_or(|pin| pack.check_pin(pin, &bytes).is_err()) + { + additional.push(check.error_at(KIND, "adapter.payment.provider-pack-pin", "/connections", + "The payment provider pack pin was refused.", + "Pin the exact reviewed provider pack bytes for every connection.")); + } + if pack.connector == ConnectorKind::AdapterPaymentHttpV1 + && pack + .mapping + .as_ref() + .and_then(|mapping| mapping.collection.as_ref()) + .is_none_or(|operation| { + operation.auth != PaymentProviderAuth::Bearer + }) + { + additional.push(check.error_at( + KIND, + "adapter.payment.provider-pack-auth", + "/connections", + "The collection authentication profile was refused.", + "Use a bearer collection pack supported by the HTTP host.", + )); + } + } + for connection in &loaded.config.disbursements { + if pack.connector != ConnectorKind::AdapterPaymentHttpV1 + || !pack.capabilities.contains(&PaymentCapability::Disbursement) + || pack + .check_pin(&connection.binding.provider_pack, &bytes) + .is_err() + { + additional.push(check.error_at(KIND, "adapter.payment.provider-pack-pin", "/disbursements", + "The G2P provider pack pin, connector, or capability was refused.", + "Pin the exact mapped provider pack with disbursement capability.")); + } + if pack.connector == ConnectorKind::AdapterPaymentHttpV1 + && pack + .mapping + .as_ref() + .and_then(|mapping| mapping.disbursement.as_ref()) + .is_none_or(|operation| { + operation.auth + != connection.binding.provider.auth_profile() + }) + { + additional.push(check.error_at( + KIND, + "adapter.payment.provider-pack-auth", + "/disbursements", + "The disbursement authentication profile differs from the pinned pack.", + "Select the host authentication profile required by the reviewed pack.", + )); + } + } + for fixture in fixtures { + let replay = if pack.connector + == ConnectorKind::AdapterPaymentHttpV1 + { + payment_fixtures::replay_mapped(fixture, path, &pack, &bytes) + } else { + payment_fixtures::replay(fixture, pack.connector) + }; + if let Err(error) = replay { + let (code, message, action) = match error { + FixtureError::Unavailable => ("adapter.payment.fixture-unavailable", "A payment provider fixture could not be read.", "Correct the fixture path and retry."), + FixtureError::Refused => ("adapter.payment.fixture-refused", "A payment provider fixture did not match the pinned connector mapping.", "Correct the fixture or provider pack and retry."), + }; + additional.push(check.error_at( + KIND, + code, + "/fixtures", + message, + action, + )); + } + } + } + Err(report) => additional.extend(report.into_diagnostics()), + }, + Err(_) => additional.push(check.error_at( + KIND, + "adapter.payment.provider-pack-unavailable", + "/connections", + "The payment provider pack could not be read.", + "Correct the provider pack path and retry.", + )), + }, + None if loaded.config.connections.iter().any(|connection| { + connection.binding.provider_pack.is_some() || !connection.binding.simulation + }) || !loaded.config.disbursements.is_empty() => + { + additional.push(check.error_at( + KIND, + "adapter.payment.provider-pack-required", + "/connections", + "A pinned payment provider pack was not supplied.", + "Pass --provider-pack with the exact pinned pack file.", + )); + } + None => {} + } + if !fixtures.is_empty() && provider_pack.is_none() { + additional.push(check.error_at( + KIND, + "adapter.payment.fixture-pack-required", + "/fixtures", + "Payment provider fixtures require a provider pack.", + "Pass --provider-pack with the exact pinned pack file.", + )); + } value["connectionCount"] = json!(loaded.config.connections.len()); + value["fixturesChecked"] = json!(fixtures.len()); if matches!(command, PaymentsCommand::Contract { .. }) { value["contract"] = registry_adapter::payments::http::contract(&loaded.config); } @@ -93,3 +302,51 @@ pub fn run(command: &PaymentsCommand) -> PaymentCheck { deny_warnings, } } + +fn check_pack(file: &PathBuf) -> PaymentCheck { + let bytes = match std::fs::read(file) { + Ok(bytes) => bytes, + Err(_) => { + return PaymentCheck { + value: json!({}), + checked: Report::new(vec![Diagnostic::error( + "adapterctl.io-failure", + "", + "The payment provider pack could not be read.", + "Correct the file path or permissions, then retry.", + )]), + unavailable: true, + deny_warnings: false, + } + } + }; + let (value, checked) = match PaymentProviderPack::from_yaml(&bytes) { + Ok(pack) + if pack.validate().is_ok() + && (pack.connector != ConnectorKind::AdapterPaymentHttpV1 + || payment_fixtures::compile_mapped_pack(file, &pack, &bytes).is_ok()) => + { + ( + json!({"packId": pack.id, "version": pack.version, "capabilities": pack.capabilities, + "digest": registry_platform_config::sha256_uri(&bytes)}), + Report::new(vec![]), + ) + } + Ok(_) => ( + json!({}), + Report::new(vec![Diagnostic::error( + "adapter.payment.provider-pack-refused", + "", + "The payment provider pack was refused.", + "Check its id, version, connector and capabilities.", + )]), + ), + Err(report) => (json!({}), report), + }; + PaymentCheck { + value, + checked, + unavailable: false, + deny_warnings: false, + } +} diff --git a/crates/registry-adapterctl/src/schemas.rs b/crates/registry-adapterctl/src/schemas.rs index c68e2c7073..5d2c32d423 100644 --- a/crates/registry-adapterctl/src/schemas.rs +++ b/crates/registry-adapterctl/src/schemas.rs @@ -76,6 +76,26 @@ fn entries() -> Result, serde_json::Error> { AdapterProject, AdapterRuntimeConfig, }; Ok(vec![ + Entry { + file: "payment-provider-fixture.v1alpha1.schema.json", + derived: serde_json::to_value(schemars::schema_for!( + crate::payment_fixtures::FixtureDocument + ))?, + title: "Registry Adapter payment provider fixture", + schema_id: crate::payment_fixtures::SCHEMA_ID, + api_version: crate::payment_fixtures::VERSION, + kind: crate::payment_fixtures::KIND, + }, + Entry { + file: "payment-provider-pack.v1alpha1.schema.json", + derived: serde_json::to_value(schemars::schema_for!( + registry_adapter::payments::pack::PaymentProviderPack + ))?, + title: "Registry Adapter payment provider pack", + schema_id: registry_adapter::payments::pack::SCHEMA_ID, + api_version: registry_adapter::payments::pack::API_VERSION, + kind: registry_adapter::payments::pack::KIND, + }, Entry { file: "payments.v1alpha1.schema.json", derived: serde_json::to_value(schemars::schema_for!( @@ -180,8 +200,25 @@ pub fn documents() -> Result, serde_json::Error> // so drop the `null` schemars adds to optional members; the platform // shared blocks keep the exact definitions the platform publishes. refuse_null_outside_shared_blocks(&mut derived, &shared); - set_const(&mut derived, "apiVersion", entry.api_version); - set_const(&mut derived, "kind", entry.kind); + if entry.file == "payment-provider-fixture.v1alpha1.schema.json" { + set_const(&mut derived, "apiVersion", entry.api_version); + set_const(&mut derived, "kind", entry.kind); + derived + .as_object_mut() + .expect("the fixture schema is an object") + .insert("unevaluatedProperties".to_owned(), Value::Bool(false)); + for variant in derived + .get_mut("oneOf") + .and_then(Value::as_array_mut) + .expect("the fixture schema is a tagged union") + { + set_const(variant, "apiVersion", entry.api_version); + set_const(variant, "kind", entry.kind); + } + } else { + set_const(&mut derived, "apiVersion", entry.api_version); + set_const(&mut derived, "kind", entry.kind); + } apply_manual_wire_forms(&mut derived, entry.file); let mut object = match derived { Value::Object(object) => object, @@ -592,7 +629,7 @@ mod tests { fn documents_are_deterministic_and_versioned() { let first = documents().unwrap(); assert_eq!(documents().unwrap(), first); - assert_eq!(first.len(), 11); + assert_eq!(first.len(), 13); let effective: Value = serde_json::from_str(&first["effective-contract.v1alpha1.schema.json"]) .expect("the effective contract schema is JSON"); @@ -677,6 +714,129 @@ mod tests { assert_eq!(drifted, vec!["profile.v1alpha1.schema.json"]); } + #[test] + fn payment_provider_schemas_accept_mapped_pack_and_raw_response_fixture() { + let generated = documents().unwrap(); + let pack: Value = + serde_json::from_str(&generated["payment-provider-pack.v1alpha1.schema.json"]).unwrap(); + let pack_validator = jsonschema::JSONSchema::options() + .with_draft(jsonschema::Draft::Draft202012) + .compile(&pack) + .unwrap(); + let mut mapped_pack = serde_json::json!({ + "apiVersion": registry_adapter::payments::pack::API_VERSION, + "kind": registry_adapter::payments::pack::KIND, + "id": "sample-payments", + "version": "1", + "connector": "adapter-payment-http/v1", + "capabilities": ["collection"], + "mapping": { + "collection": { + "auth": "bearer", + "submit": { + "path": "/send", + "request": {"file": "scripts/payment.rhai", "entrypoint": "send_request"}, + "response": {"file": "scripts/payment.rhai", "entrypoint": "send_response"} + } + }, + "scripts": [{"path": "scripts/payment.rhai", "digest": format!("sha256:{}", "a".repeat(64))}] + } + }); + assert!(pack_validator.validate(&mapped_pack).is_ok()); + mapped_pack["mapping"]["collection"]["auth"] = serde_json::json!("unknown"); + assert!(pack_validator.validate(&mapped_pack).is_err()); + + let fixture: Value = + serde_json::from_str(&generated["payment-provider-fixture.v1alpha1.schema.json"]) + .unwrap(); + let fixture_validator = jsonschema::JSONSchema::options() + .with_draft(jsonschema::Draft::Draft202012) + .compile(&fixture) + .unwrap(); + let mut mapped_fixture = serde_json::json!({ + "apiVersion": crate::payment_fixtures::VERSION, + "kind": crate::payment_fixtures::KIND, + "type": "mapped", + "direction": "p2g-collection", + "intent": {}, + "settings": {}, + "submit": { + "expectedRequest": {}, + "response": {"status": 200, "bodyJson": "{\"id\":1.00}"}, + "expected": {} + }, + "status": { + "acceptance": {"correlationId": "payment-1", "references": {"transaction": "tx-1"}}, + "expectedRequest": {}, + "response": {"status": 200, "bodyJson": "{\"amount\":25.50}"}, + "expected": {} + } + }); + assert!(fixture_validator.validate(&mapped_fixture).is_ok()); + let variants = fixture["oneOf"].as_array().unwrap(); + assert_eq!(variants.len(), 2); + assert_eq!( + fixture["properties"]["apiVersion"]["const"], + crate::payment_fixtures::VERSION + ); + assert_eq!( + fixture["properties"]["kind"]["const"], + crate::payment_fixtures::KIND + ); + assert_eq!(fixture["unevaluatedProperties"], false); + for variant in variants { + assert_eq!(variant["additionalProperties"], false); + assert!(variant["required"] + .as_array() + .unwrap() + .iter() + .any(|member| member == "type")); + assert_eq!( + variant["properties"]["apiVersion"]["const"], + crate::payment_fixtures::VERSION + ); + assert_eq!( + variant["properties"]["kind"]["const"], + crate::payment_fixtures::KIND + ); + } + let mut compiled_fixture = serde_json::json!({ + "apiVersion": crate::payment_fixtures::VERSION, + "kind": crate::payment_fixtures::KIND, + "type": "compiled", + "connectorProfile": "mifos-ph-ee-legacy/channel-v1.12.2+bulk-v1.12.1+operations-v1.17.1", + "direction": "p2g-collection", + "command": {}, + "expectedRequest": {}, + "acceptance": { + "response": {"httpStatus": 200, "body": {}}, + "expected": {} + }, + "status": { + "response": {"httpStatus": 200, "body": {}}, + "expected": {} + } + }); + assert!(fixture_validator.validate(&compiled_fixture).is_ok()); + compiled_fixture["intent"] = serde_json::json!({}); + assert!(fixture_validator.validate(&compiled_fixture).is_err()); + let mut missing_type = mapped_fixture.clone(); + missing_type.as_object_mut().unwrap().remove("type"); + assert!(fixture_validator.validate(&missing_type).is_err()); + mapped_fixture["connectorProfile"] = serde_json::json!("not-valid-on-mapped"); + assert!(fixture_validator.validate(&mapped_fixture).is_err()); + mapped_fixture + .as_object_mut() + .unwrap() + .remove("connectorProfile"); + let mut invalid_reference = mapped_fixture.clone(); + invalid_reference["status"]["acceptance"]["references"] = + serde_json::json!({"Transfer.ID": "tx-1"}); + assert!(fixture_validator.validate(&invalid_reference).is_err()); + mapped_fixture["status"]["response"]["status"] = serde_json::json!(99); + assert!(fixture_validator.validate(&mapped_fixture).is_err()); + } + /// The manual wire forms the generator rewrites stay pinned to the /// reader: `SendUri` accepts exactly the URIs its parser accepts, and /// the error classes carry the hierarchy's dotted strings. diff --git a/crates/registry-adapterctl/tests/check.rs b/crates/registry-adapterctl/tests/check.rs index eb3c83015c..c497ca977e 100644 --- a/crates/registry-adapterctl/tests/check.rs +++ b/crates/registry-adapterctl/tests/check.rs @@ -713,10 +713,10 @@ fn check_refuses_a_missing_explicit_fixture_path() { ); } -/// `schemas` writes the closed set of eleven generated files into any +/// `schemas` writes the closed set of thirteen generated files into any /// directory it is given. #[test] -fn schemas_writes_eleven_files_into_the_given_directory() { +fn schemas_writes_thirteen_files_into_the_given_directory() { let root = tempfile::tempdir().unwrap(); let output = root.path().join("schemas").to_str().unwrap().to_owned(); let (exit, report, stderr) = run_json(&["schemas", "--output-dir", &output]); @@ -731,6 +731,8 @@ fn schemas_writes_eleven_files_into_the_given_directory() { "effective-contract.v1alpha1.schema.json".to_owned(), "fixture.v1alpha1.schema.json".to_owned(), "pack.v1alpha1.schema.json".to_owned(), + "payment-provider-fixture.v1alpha1.schema.json".to_owned(), + "payment-provider-pack.v1alpha1.schema.json".to_owned(), "payments.v1alpha1.schema.json".to_owned(), "profile.v1alpha1.schema.json".to_owned(), "project.v1alpha1.schema.json".to_owned(), diff --git a/crates/registry-adapterctl/tests/payments.rs b/crates/registry-adapterctl/tests/payments.rs index 7ff0913971..ce96fdf58f 100644 --- a/crates/registry-adapterctl/tests/payments.rs +++ b/crates/registry-adapterctl/tests/payments.rs @@ -63,3 +63,106 @@ fn payment_check_keeps_the_shared_reader_diagnostic_and_position() { assert!(report["diagnostics"][0]["source"]["line"].is_number()); assert!(stderr.is_empty()); } + +#[test] +fn payment_provider_variants_keep_nested_source_positions() { + let directory = tempfile::tempdir().unwrap(); + let file = directory.path().join("payments.yaml"); + let example = std::fs::read_to_string( + PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("../../products/adapter/examples/payment-collections/payments.example.yaml"), + ) + .unwrap(); + let marker = " tenant: pilot\n"; + let marker_end = example.find(marker).unwrap() + marker.len(); + let line = example[..marker_end].lines().count() as u64 + 1; + std::fs::write( + &file, + example.replacen( + marker, + &format!("{marker} conformanceUnknown: true\n"), + 1, + ), + ) + .unwrap(); + let mut stdout = Vec::new(); + let mut stderr = Vec::new(); + let code = registry_adapterctl::main_entry_from( + [ + "adapterctl", + "--format", + "json", + "payments", + "check", + file.to_str().unwrap(), + ], + &mut stdout, + &mut stderr, + ); + assert_eq!(code, ExitCode::from(1)); + let report: serde_json::Value = serde_json::from_slice(&stdout).unwrap(); + assert_eq!(report["diagnostics"][0]["code"], "config.unknown-key"); + assert_eq!( + report["diagnostics"][0]["path"], + "/connections/0/binding/provider/connection/conformanceUnknown" + ); + assert_eq!(report["diagnostics"][0]["source"]["line"], line); + assert!(report["diagnostics"][0]["source"]["column"].is_number()); + assert!(stderr.is_empty()); +} + +#[test] +fn payment_check_consumes_the_exact_pinned_provider_pack() { + let directory = tempfile::tempdir().unwrap(); + let pack_file = directory.path().join("pack.yaml"); + let pack = "apiVersion: id.registrystack.org/formats/adapter/payment-provider-pack/v1alpha1\nkind: AdapterPaymentProviderPack\nid: simulator\nversion: '1'\nconnector: simulator-p2g/v1\ncapabilities: [collection]\n"; + std::fs::write(&pack_file, pack).unwrap(); + let example = std::fs::read_to_string( + PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("../../products/adapter/examples/payment-collections/payments.example.yaml"), + ) + .unwrap(); + let pin = format!( + " binding:\n providerPack: {{id: simulator, version: '1', digest: {}}}\n", + registry_platform_config::sha256_uri(pack.as_bytes()) + ); + let file = directory.path().join("payments.yaml"); + std::fs::write(&file, example.replacen(" binding:\n", &pin, 1)).unwrap(); + + let check = |pack: &std::path::Path| { + let mut stdout = Vec::new(); + let mut stderr = Vec::new(); + let code = registry_adapterctl::main_entry_from( + [ + "adapterctl", + "--format", + "json", + "payments", + "check", + file.to_str().unwrap(), + "--provider-pack", + pack.to_str().unwrap(), + ], + &mut stdout, + &mut stderr, + ); + assert!(stderr.is_empty()); + ( + code, + serde_json::from_slice::(&stdout).unwrap(), + ) + }; + let (code, report) = check(&pack_file); + assert_eq!(code, ExitCode::SUCCESS, "{report}"); + std::fs::write( + &pack_file, + pack.replace("simulator-p2g/v1", "mifos-ph-ee-legacy/v1"), + ) + .unwrap(); + let (code, report) = check(&pack_file); + assert_eq!(code, ExitCode::from(1)); + assert_eq!( + report["diagnostics"][0]["code"], + "adapter.payment.provider-pack-pin" + ); +} diff --git a/crates/registry-coordinator/src/adapters.rs b/crates/registry-coordinator/src/adapters.rs index 6277ae3a8c..a22bc778a8 100644 --- a/crates/registry-coordinator/src/adapters.rs +++ b/crates/registry-coordinator/src/adapters.rs @@ -13,9 +13,10 @@ use registry_messaging_client::{ MessagingClient, MessagingClientConfig, MessagingClientError, ProblemCode, SubmitMessageRequest, }; use registry_payment_client::{ - CollectionAccepted, CollectionState, CollectionStatus, PaymentClient, PaymentClientConfig, - PaymentClientError, PaymentProblemCode, PaymentProtocolFailure, ReadCollection, RecordReceipt, - RequestCollection, + CollectionAccepted, CollectionState, CollectionStatus, DisbursementAccepted, DisbursementState, + DisbursementStatus, PaymentClient, PaymentClientConfig, PaymentClientError, PaymentProblemCode, + PaymentProtocolFailure, ReadCollection, ReadDisbursement, RecordProviderConfirmation, + RecordReceipt, RequestCollection, RequestDisbursement, }; use registry_platform_crypto::PrivateJwk; use registry_platform_httputil::{ @@ -441,8 +442,10 @@ fn payment_failure(error: PaymentClientError, operation: Operation) -> CallOutco code: PaymentProblemCode::ReceiptExpired, .. } - ) && operation == Operation::RequestCollection - { + ) && matches!( + operation, + Operation::RequestCollection | Operation::RequestDisbursement + ) { return CallOutcome::ReceiptExpired; } if operation.has_dispatch_risk() && error.is_outcome_unknown() { @@ -574,10 +577,151 @@ async fn payment_call(connection: &PaymentConnection, request: &CallRequest) -> Err(error) => payment_failure(error, request.operation), } } + Operation::RequestDisbursement => { + let input: RequestDisbursement = match serde_json::from_value(request.input.clone()) { + Ok(input) => input, + Err(_) => return refused("invalid-command"), + }; + let Some(key) = request.idempotency_key.as_deref() else { + return refused("invalid-command"); + }; + match connection + .client + .request_disbursement(&token, key, &input) + .await + { + Ok(answer) => payment_success(answer.value, request.operation), + Err(error) => payment_failure(error, request.operation), + } + } + Operation::ReadDisbursement => { + let input: ReadDisbursement = match serde_json::from_value(request.input.clone()) { + Ok(input) => input, + Err(_) => return refused("invalid-command"), + }; + if request.idempotency_key.is_some() { + return refused("invalid-command"); + } + match connection.client.read_disbursement(&token, &input).await { + Ok(answer) => payment_success(answer.value, request.operation), + Err(error) => payment_failure(error, request.operation), + } + } + Operation::RecordProviderConfirmation => { + let input: RecordProviderConfirmation = + match serde_json::from_value(request.input.clone()) { + Ok(input) => input, + Err(_) => return refused("invalid-command"), + }; + let Some(key) = request.idempotency_key.as_deref() else { + return refused("invalid-command"); + }; + match connection + .client + .record_provider_confirmation(&token, key, &input) + .await + { + Ok(answer) => payment_success(answer.value, request.operation), + Err(error) => payment_failure(error, request.operation), + } + } _ => refused("operation-unbound"), } } +fn disbursement_acceptance(status: &DisbursementStatus) -> DisbursementAccepted { + DisbursementAccepted { + disbursement_id: status.disbursement_id, + instruction_record_id: status.instruction_record_id, + instruction_id: status.instruction_id, + instruction_version: status.instruction_version, + binding_revision: status.binding_revision.clone(), + simulation: status.simulation, + } +} + +fn payment_disbursement_accepted( + operation: Operation, + value: &serde_json::Value, +) -> Option { + match operation { + Operation::RequestDisbursement => serde_json::from_value(value.clone()).ok(), + Operation::ReadDisbursement => serde_json::from_value::(value.clone()) + .ok() + .map(|status| disbursement_acceptance(&status)), + _ => None, + } +} + +async fn payment_disbursement_observe( + connection: &PaymentConnection, + request: &CallRequest, + accepted: &serde_json::Value, +) -> CompletionObservation { + let Some(expected) = payment_disbursement_accepted(request.operation, accepted) + .filter(|accepted| accepted.validate().is_ok()) + else { + return CompletionObservation::Hold { + code: "payment-invalid-response".into(), + }; + }; + let token = match connection.tokens.bearer_token().await { + Ok(token) => token, + Err(_) => { + return CompletionObservation::Retryable { + code: "completion-unavailable".into(), + retry_after: None, + } + } + }; + match connection + .client + .read_disbursement( + &token, + &ReadDisbursement { + disbursement_id: expected.disbursement_id, + }, + ) + .await + { + Ok(answer) if disbursement_acceptance(&answer.value) != expected => { + CompletionObservation::Hold { + code: "payment-correlation-mismatch".into(), + } + } + Ok(answer) => match answer.value.state { + DisbursementState::Accepted + | DisbursementState::Pending + | DisbursementState::Unknown => CompletionObservation::Pending { retry_after: None }, + DisbursementState::ProviderConfirmed | DisbursementState::Failed => { + match serde_json::to_value(answer.value) { + Ok(value) => CompletionObservation::Settled(value), + Err(_) => CompletionObservation::Hold { + code: "payment-invalid-response".into(), + }, + } + } + }, + Err(PaymentClientError::Transport { .. }) + | Err(PaymentClientError::Problem { + code: PaymentProblemCode::Unavailable, + .. + }) => CompletionObservation::Retryable { + code: "completion-unavailable".into(), + retry_after: None, + }, + Err(PaymentClientError::Protocol { + failure: PaymentProtocolFailure::Correlation, + .. + }) => CompletionObservation::Hold { + code: "payment-correlation-mismatch".into(), + }, + Err(_) => CompletionObservation::Hold { + code: "payment-unknown".into(), + }, + } +} + fn payment_accepted(operation: Operation, value: &serde_json::Value) -> Option { match operation { Operation::RequestCollection => serde_json::from_value(value.clone()).ok(), @@ -1107,6 +1251,11 @@ impl AdapterSet for HttpAdapters { { payment_observe(connection, request, accepted).await } + (CompletionKind::PaymentDisbursement {}, Some(Connection::Payments(connection))) + if request.operation.follows_disbursement() => + { + payment_disbursement_observe(connection, request, accepted).await + } _ => CompletionObservation::Hold { code: "operation-unbound".into(), }, @@ -1145,6 +1294,7 @@ impl AdapterSet for HttpAdapters { crate::definition::CompletionKind::CaseworkResult {} | crate::definition::CompletionKind::BregProposal {} | crate::definition::CompletionKind::PaymentCollection {} + | crate::definition::CompletionKind::PaymentDisbursement {} ) { self.config.minimum_observation_interval_seconds.get() } else { @@ -1239,6 +1389,36 @@ impl AdapterSet for HttpAdapters { Err(_) => unresolved("observation-unavailable"), } } + (Some(Connection::Payments(connection)), Operation::RequestDisbursement) => { + let input: RequestDisbursement = match serde_json::from_value(request.input.clone()) + { + Ok(input) => input, + Err(_) => return unresolved("invalid-command"), + }; + let token = match connection.tokens.bearer_token().await { + Ok(token) => token, + Err(_) => return unresolved("observation-unavailable"), + }; + match connection + .client + .disbursement_receipt(&token, idempotency_key, &input) + .await + { + Ok(answer) => match serde_json::to_value(answer.value) { + Ok(value) => ReconciliationOutcome::Confirmed(value), + Err(_) => unresolved("invalid-observation"), + }, + Err(PaymentClientError::Problem { + code: + PaymentProblemCode::ReceiptUnresolved + | PaymentProblemCode::ReceiptExpired + | PaymentProblemCode::RecoveryHeld + | PaymentProblemCode::OutcomeUnknown, + .. + }) => unresolved("receipt-unresolved"), + Err(_) => unresolved("observation-unavailable"), + } + } ( Some(Connection::Scheduling(connection)), Operation::CreateAppointment | Operation::ConfirmHold, diff --git a/crates/registry-coordinator/src/authoring.rs b/crates/registry-coordinator/src/authoring.rs index 04f331d3f8..5ecc377b5f 100644 --- a/crates/registry-coordinator/src/authoring.rs +++ b/crates/registry-coordinator/src/authoring.rs @@ -1335,6 +1335,16 @@ fn compile(project: CoordinatorProject, path: &Path) -> Result { }, ); } + if uses.follows_disbursement() { + completions.insert( + "disbursement".into(), + CompletionDefinition { + kind: CompletionKind::PaymentDisbursement {}, + output: crate::contracts::payment_disbursement_completion_schema().clone(), + revision: String::new(), + }, + ); + } authored_completions.insert(id.clone(), operation.completions); operations.insert( id, diff --git a/crates/registry-coordinator/src/contracts.rs b/crates/registry-coordinator/src/contracts.rs index 4d489bf82c..9ae210c75c 100644 --- a/crates/registry-coordinator/src/contracts.rs +++ b/crates/registry-coordinator/src/contracts.rs @@ -845,6 +845,28 @@ pub fn payment_completion_schema() -> &'static Value { }) } +/// Authoritative state observed for the exact disbursement instruction a +/// call accepted. Pending and unknown values remain observations, not proof +/// that a replacement submission is safe. +pub fn payment_disbursement_completion_schema() -> &'static Value { + static SCHEMA: OnceLock = OnceLock::new(); + SCHEMA.get_or_init(|| { + #[cfg(feature = "schema")] + { + let mut schema = derived::output::(); + derived::finish(&mut schema, "Payment disbursement completion"); + schema + } + #[cfg(not(feature = "schema"))] + { + serde_json::from_str(include_str!( + "../../../products/coordinator/generated/operations/payments.disbursement.completion.schema.json" + )) + .expect("generated payment disbursement completion schema") + } + }) +} + /// Shared Review and event wire schemas, generated from their owning types. pub fn admission_schemas() -> &'static Value { static SCHEMAS: OnceLock = OnceLock::new(); @@ -1008,6 +1030,11 @@ pub fn generate() -> Result, serde_json::Error> { let mut text = serde_json::to_string_pretty(&payment)?; text.push('\n'); files.insert("payments.collection.completion.schema.json".into(), text); + let mut disbursement = derived::output::(); + derived::finish(&mut disbursement, "Payment disbursement completion"); + let mut text = serde_json::to_string_pretty(&disbursement)?; + text.push('\n'); + files.insert("payments.disbursement.completion.schema.json".into(), text); for descriptor in crate::operations::descriptors() { let Some(refusal) = derived_declared_refusal(descriptor) else { continue; @@ -1288,6 +1315,27 @@ mod derived { ) } + pub(super) fn request_disbursement() -> (Value, Value) { + ( + input::(), + output::(), + ) + } + + pub(super) fn read_disbursement() -> (Value, Value) { + ( + input::(), + output::(), + ) + } + + pub(super) fn record_provider_confirmation() -> (Value, Value) { + ( + input::(), + output::(), + ) + } + /// What the adapter accepts: the deserialization contract of its input type. pub(super) fn input() -> Value { let generator = SchemaSettings::draft2020_12() diff --git a/crates/registry-coordinator/src/definition.rs b/crates/registry-coordinator/src/definition.rs index cfcafcbc1c..e7eccda973 100644 --- a/crates/registry-coordinator/src/definition.rs +++ b/crates/registry-coordinator/src/definition.rs @@ -412,6 +412,8 @@ pub enum CompletionKind { BregProposal {}, /// The authoritative status of the exact collection this call accepted. PaymentCollection {}, + /// The authoritative status of the exact disbursement this call accepted. + PaymentDisbursement {}, BoundedPoll { interpret: String, interval_seconds: u32, @@ -1767,6 +1769,11 @@ fn workflow_findings(flow: &Workflow) -> Vec { operation.uses.follows_collection() && completion.output == *crate::contracts::payment_completion_schema() } + CompletionKind::PaymentDisbursement {} => { + operation.uses.follows_disbursement() + && completion.output + == *crate::contracts::payment_disbursement_completion_schema() + } CompletionKind::BoundedPoll { interpret, interval_seconds, diff --git a/crates/registry-coordinator/src/operations.rs b/crates/registry-coordinator/src/operations.rs index 88582f0f86..d671f9d3f1 100644 --- a/crates/registry-coordinator/src/operations.rs +++ b/crates/registry-coordinator/src/operations.rs @@ -112,6 +112,17 @@ impl OperationDescriptor { "authenticatedWake":false, "defaultIntervalSeconds":crate::runtime::DEFAULT_RESULT_CHECK_SECONDS }), + id if Operation::parse(id).is_some_and(Operation::follows_disbursement) => json!({ + "name":"disbursement", "profile":"payment-disbursement", + "acceptedBinding":["disbursementId","instructionRecordId","instructionId","instructionVersion","bindingRevision","simulation"], + "authority":"current-bound-payment-connection", + "terminalEvidence":"validated-authoritative-disbursement-read", + "pendingStates":["accepted","pending","unknown"], + "settledStates":["provider-confirmed","failed"], + "paymentSuccessState":"provider-confirmed", + "authenticatedWake":false, + "defaultIntervalSeconds":crate::runtime::DEFAULT_RESULT_CHECK_SECONDS + }), _ => serde_json::Value::Null, }; if let Some(fields) = observation.as_object_mut() { @@ -236,6 +247,25 @@ const fn mutation( } } +/// A provider submission that can be reconciled through an authoritative +/// original-command read, but must never be sent again after uncertainty. +const fn receipt_reconciled_mutation( + id: &'static str, + product: &'static str, +) -> OperationDescriptor { + OperationDescriptor { + id, + version: 1, + product, + effect: EffectKind::Mutation, + key_requirement: KeyRequirement::Required, + requires_preparation: false, + recovery: RecoverySemantics::HoldAfterDispatch, + read_receipt: true, + declared_refusal: false, + } +} + const fn declared_read(id: &'static str, product: &'static str) -> OperationDescriptor { OperationDescriptor { declared_refusal: true, @@ -325,6 +355,9 @@ macro_rules! operation_catalog { RequestCollection => "payments.request-collection/v1", mutation("payments", true, false), request_collection; ReadCollection => "payments.read-collection/v1", read("payments"), read_collection; RecordReceipt => "payments.record-receipt/v1", mutation("payments", false, false), record_receipt; + RequestDisbursement => "payments.request-disbursement/v1", receipt_reconciled_mutation("payments"), request_disbursement; + ReadDisbursement => "payments.read-disbursement/v1", read("payments"), read_disbursement; + RecordProviderConfirmation => "payments.record-provider-confirmation/v1", mutation("payments", false, false), record_provider_confirmation; } }; } @@ -452,6 +485,15 @@ mod tests { ), (Operation::ReadCollection, "payments.read-collection/v1"), (Operation::RecordReceipt, "payments.record-receipt/v1"), + ( + Operation::RequestDisbursement, + "payments.request-disbursement/v1", + ), + (Operation::ReadDisbursement, "payments.read-disbursement/v1"), + ( + Operation::RecordProviderConfirmation, + "payments.record-provider-confirmation/v1", + ), ]; assert_eq!( descriptors() @@ -603,6 +645,8 @@ mod tests { Operation::ExternalCommand, Operation::RequestCollection, Operation::RecordReceipt, + Operation::RequestDisbursement, + Operation::RecordProviderConfirmation, ]; let allowed_mutations = [ Operation::SubmitMessage, @@ -686,6 +730,35 @@ mod tests { RecoverySemantics::SameCommand ); assert!(!Operation::RecordReceipt.follows_collection()); + assert_eq!(Operation::RequestDisbursement.product(), "payments"); + assert!(Operation::RequestDisbursement.requires_key()); + assert!(Operation::RequestDisbursement.supports_read_receipt()); + assert_eq!( + Operation::RequestDisbursement.recovery(), + RecoverySemantics::HoldAfterDispatch + ); + assert!(!Operation::RequestDisbursement.can_retry_after_unknown()); + assert!(Operation::RequestDisbursement.follows_disbursement()); + let completion = + &Operation::RequestDisbursement.descriptor().host_contract()["completionObservation"]; + assert_eq!( + completion["pendingStates"], + serde_json::json!(["accepted", "pending", "unknown"]) + ); + assert_eq!( + completion["settledStates"], + serde_json::json!(["provider-confirmed", "failed"]) + ); + assert_eq!(completion["paymentSuccessState"], "provider-confirmed"); + assert!(Operation::ReadDisbursement.is_read()); + assert!(Operation::ReadDisbursement.follows_disbursement()); + assert!(Operation::RecordProviderConfirmation.requires_key()); + assert_eq!( + Operation::RecordProviderConfirmation.recovery(), + RecoverySemantics::SameCommand + ); + assert!(Operation::RecordProviderConfirmation.can_retry_after_unknown()); + assert!(!Operation::RecordProviderConfirmation.follows_disbursement()); } #[test] diff --git a/crates/registry-coordinator/src/protocol.rs b/crates/registry-coordinator/src/protocol.rs index fd370d5fd4..af94d38dce 100644 --- a/crates/registry-coordinator/src/protocol.rs +++ b/crates/registry-coordinator/src/protocol.rs @@ -73,6 +73,8 @@ impl Operation { | Self::ExternalCommand | Self::RequestCollection | Self::RecordReceipt + | Self::RequestDisbursement + | Self::RecordProviderConfirmation ) } @@ -139,6 +141,12 @@ impl Operation { pub fn follows_collection(self) -> bool { matches!(self, Self::RequestCollection | Self::ReadCollection) } + + /// Payment operations whose accepted output fixes the authoritative + /// disbursement read a named completion observes. + pub fn follows_disbursement(self) -> bool { + matches!(self, Self::RequestDisbursement | Self::ReadDisbursement) + } } impl Serialize for Operation { @@ -443,6 +451,7 @@ pub trait AdapterSet: Send + Sync { crate::definition::CompletionKind::CaseworkResult {} | crate::definition::CompletionKind::BregProposal {} | crate::definition::CompletionKind::PaymentCollection {} + | crate::definition::CompletionKind::PaymentDisbursement {} ) { crate::store::WAIT_READ_SPACING_SECONDS } else { diff --git a/crates/registry-coordinator/src/scenarios.rs b/crates/registry-coordinator/src/scenarios.rs index 4671de3a57..f3facadddb 100644 --- a/crates/registry-coordinator/src/scenarios.rs +++ b/crates/registry-coordinator/src/scenarios.rs @@ -1179,12 +1179,16 @@ fn execute(definition: &Definition, scenario: &Scenario) -> Result 0 && prior_unknown && !command.operation.can_retry_after_unknown() { + if index > 0 + && prior_unknown + && !command.operation.can_retry_after_unknown() + && !matches!(recovery, Some(Recovery::Reconcile)) + { return Err(error( "scenario.recovery", at, - format!("step {step} calls {operation}, which holds the run after an uncertain reply, so no later reply is consumed"), - "End the replies at the uncertain one, as a held run would.", + format!("step {step} calls {operation}, which holds the run after an uncertain reply, so no later command reply is consumed"), + "End the replies at the uncertain one, or use reconcile when the operation exposes an authoritative original-command receipt.", )); } // Receipt observation can resolve an unknown mutation, @@ -1463,6 +1467,36 @@ fn check_event( )); } } + if matches!(completion.kind, CompletionKind::PaymentDisbursement {}) { + let parsed = + serde_json::from_value::(value.clone()); + let status = parsed.map_err(|_| { + error( + "scenario.wait-event", + pointer.clone(), + format!("the disbursement status stated for step {step} is malformed"), + "Correct the stated disbursement status so the payment protocol accepts it.", + ) + })?; + status.validate().map_err(|_| { + error( + "scenario.wait-event", + pointer.clone(), + format!( + "the disbursement status stated for step {step} carries inconsistent evidence" + ), + "Keep providerReference only on provider-confirmed and failureReason only on failed status.", + ) + })?; + if !disbursement_completion_settles(status.state) { + return Err(error( + "scenario.wait-event", + pointer, + format!("the disbursement status stated for step {step} is not terminal"), + "Use provider-confirmed or failed for an event that settles the wait, or state an explicit timeout.", + )); + } + } Ok(()) } @@ -1474,6 +1508,14 @@ fn payment_completion_settles(state: registry_payment_client::CollectionState) - ) } +fn disbursement_completion_settles(state: registry_payment_client::DisbursementState) -> bool { + matches!( + state, + registry_payment_client::DisbursementState::ProviderConfirmed + | registry_payment_client::DisbursementState::Failed + ) +} + /// A stated event belongs to the request its wait names. A review result /// carries the request identifier, subject, policy and submission digest /// the request step accepted, as the producer client requires of every @@ -1561,6 +1603,39 @@ fn correlate( )) } } + CompletionKind::PaymentDisbursement {} => { + let accepted = outputs.get(request).and_then(disbursement_acceptance); + let observed = serde_json::from_value::( + value.clone(), + ) + .ok() + .map(|status| registry_payment_client::DisbursementAccepted { + disbursement_id: status.disbursement_id, + instruction_record_id: status.instruction_record_id, + instruction_id: status.instruction_id, + instruction_version: status.instruction_version, + binding_revision: status.binding_revision, + simulation: status.simulation, + }); + let (Some(accepted), Some(observed)) = (accepted, observed) else { + return Err(error( + "scenario.wait-event", + format!("/waits/{step}/value"), + format!("the disbursement status stated for step {step} cannot be matched to step {request}"), + format!("Give step {request} a success reply that satisfies its payment operation output."), + )); + }; + if observed == accepted { + Ok(()) + } else { + Err(error( + "scenario.wait-event", + format!("/waits/{step}/value/disbursementId"), + format!("the disbursement status stated for step {step} does not retain the exact instruction binding step {request} accepted"), + format!("Copy disbursementId, instructionRecordId, instructionId, instructionVersion, bindingRevision and simulation from step {request}."), + )) + } + } CompletionKind::BoundedPoll { .. } => Ok(()), } } @@ -1575,6 +1650,23 @@ fn payment_acceptance(value: &Value) -> Option Option { + serde_json::from_value::(value.clone()) + .ok() + .or_else(|| { + serde_json::from_value::(value.clone()) + .ok() + .map(|status| registry_payment_client::DisbursementAccepted { + disbursement_id: status.disbursement_id, + instruction_record_id: status.instruction_record_id, + instruction_id: status.instruction_id, + instruction_version: status.instruction_version, + binding_revision: status.binding_revision, + simulation: status.simulation, + }) + }) +} + /// The differences one case lists before it counts the rest. const MISMATCHES_LISTED: usize = 20; @@ -2066,4 +2158,23 @@ mod payment_tests { assert!(payment_completion_settles(state)); } } + + #[test] + fn only_terminal_disbursement_states_settle_a_scenario_wait() { + use registry_payment_client::DisbursementState; + + for state in [ + DisbursementState::Accepted, + DisbursementState::Pending, + DisbursementState::Unknown, + ] { + assert!(!disbursement_completion_settles(state)); + } + for state in [ + DisbursementState::ProviderConfirmed, + DisbursementState::Failed, + ] { + assert!(disbursement_completion_settles(state)); + } + } } diff --git a/crates/registry-coordinator/tests/payment_adapter.rs b/crates/registry-coordinator/tests/payment_adapter.rs index c37f0d96db..51f6f6e9d7 100644 --- a/crates/registry-coordinator/tests/payment_adapter.rs +++ b/crates/registry-coordinator/tests/payment_adapter.rs @@ -51,6 +51,30 @@ fn status(collection_id: Uuid, bill_id: Uuid, state: &str) -> Value { value } +fn disbursement_accepted(disbursement_id: Uuid, instruction_record_id: Uuid) -> Value { + json!({ + "disbursementId": disbursement_id, + "instructionRecordId": instruction_record_id, + "instructionId": "00000000-0000-4000-8000-000000000301", + "instructionVersion": 7, + "bindingRevision": "sha256:synthetic-g2p-binding", + "simulation": true + }) +} + +fn disbursement_status(disbursement_id: Uuid, instruction_record_id: Uuid, state: &str) -> Value { + let mut value = disbursement_accepted(disbursement_id, instruction_record_id); + value["state"] = json!(state); + value["money"] = json!({"value": "125.00", "currency": "USD", "scale": 2}); + if state == "provider-confirmed" { + value["providerReference"] = json!("MIFOS-G2P-001"); + } + if state == "failed" { + value["failureReason"] = json!("provider-rejected"); + } + value +} + fn json_answer(status: u16, body: Value) -> ResponseTemplate { ResponseTemplate::new(status) .insert_header("traceparent", support::TRACE) @@ -90,6 +114,27 @@ fn completion() -> CompletionDefinition { } } +fn disbursement_request(instruction_record_id: Uuid) -> CallRequest { + CallRequest { + connection: "payments".into(), + operation: Operation::RequestDisbursement, + input: json!({ + "instructionRecordId": instruction_record_id, + "instructionVersion": 7 + }), + idempotency_key: Some(KEY.into()), + operation_contract: None, + } +} + +fn disbursement_completion() -> CompletionDefinition { + CompletionDefinition { + kind: CompletionKind::PaymentDisbursement {}, + output: registry_coordinator::contracts::payment_disbursement_completion_schema().clone(), + revision: String::new(), + } +} + struct Fixture { adapters: HttpAdapters, payment: MockServer, @@ -283,3 +328,185 @@ async fn payment_completion_settles_only_terminal_exactly_bound_state() { CompletionObservation::Hold { code } if code == "payment-correlation-mismatch" )); } + +#[tokio::test] +async fn disbursement_request_and_recovery_use_the_exact_original_command() { + let fixture = fixture().await; + let disbursement_id = Uuid::new_v4(); + let instruction_record_id = Uuid::new_v4(); + let command = disbursement_request(instruction_record_id); + let acceptance = disbursement_accepted(disbursement_id, instruction_record_id); + let body = json!({ + "instructionRecordId": instruction_record_id, + "instructionVersion": 7 + }); + Mock::given(method("POST")) + .and(path("/v1/payments/service-fees/disbursements")) + .and(header("authorization", "Bearer fixture-token")) + .and(header("idempotency-key", KEY)) + .and(body_json(body.clone())) + .respond_with(json_answer(202, acceptance.clone())) + .expect(1) + .mount(&fixture.payment) + .await; + Mock::given(method("POST")) + .and(path("/v1/payments/service-fees/disbursements/receipt")) + .and(header("authorization", "Bearer fixture-token")) + .and(header("idempotency-key", KEY)) + .and(body_json(body)) + .respond_with(json_answer(200, acceptance.clone())) + .expect(1) + .mount(&fixture.payment) + .await; + + assert!(matches!( + fixture.adapters.call(&command).await, + CallOutcome::Success(value) if value == acceptance + )); + assert!(matches!( + fixture.adapters.reconcile(&command, None).await, + ReconciliationOutcome::Confirmed(value) if value == acceptance + )); +} + +#[tokio::test] +async fn uncertain_disbursement_submission_never_becomes_a_fresh_send() { + let fixture = fixture().await; + let command = disbursement_request(Uuid::new_v4()); + Mock::given(method("POST")) + .and(path("/v1/payments/service-fees/disbursements")) + .respond_with(problem(PaymentProblemCode::ProviderProtocol)) + .expect(1) + .mount(&fixture.payment) + .await; + Mock::given(method("POST")) + .and(path("/v1/payments/service-fees/disbursements/receipt")) + .respond_with(problem(PaymentProblemCode::ReceiptUnresolved)) + .expect(1) + .mount(&fixture.payment) + .await; + + assert!(matches!( + fixture.adapters.call(&command).await, + CallOutcome::Uncertain { code } if code == "payment-invalid-response" + )); + assert!(matches!( + fixture.adapters.reconcile(&command, None).await, + ReconciliationOutcome::Unresolved { code } if code == "receipt-unresolved" + )); + assert!(!Operation::RequestDisbursement.can_retry_after_unknown()); +} + +#[tokio::test] +async fn provider_confirmation_report_is_one_exact_keyed_command() { + let fixture = fixture().await; + let disbursement_id = Uuid::new_v4(); + let instruction_record_id = Uuid::new_v4(); + let confirmation = json!({ + "disbursementId": disbursement_id, + "instructionRecordId": instruction_record_id, + "instructionId": "00000000-0000-4000-8000-000000000301", + "instructionVersion": 7, + "bindingRevision": "sha256:synthetic-g2p-binding", + "simulation": true, + "money": {"value": "125.00", "currency": "USD", "scale": 2}, + "providerReference": "MIFOS-G2P-001", + "providerResultDigest": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + }); + Mock::given(method("POST")) + .and(path(format!( + "/v1/payments/service-fees/disbursements/{disbursement_id}/record-provider-confirmation" + ))) + .and(header("authorization", "Bearer fixture-token")) + .and(header("idempotency-key", KEY)) + .and(body_json(json!({"disbursementId": disbursement_id}))) + .respond_with(json_answer(200, confirmation.clone())) + .expect(1) + .mount(&fixture.payment) + .await; + let command = CallRequest { + connection: "payments".into(), + operation: Operation::RecordProviderConfirmation, + input: json!({"disbursementId": disbursement_id}), + idempotency_key: Some(KEY.into()), + operation_contract: None, + }; + + assert!(matches!( + fixture.adapters.call(&command).await, + CallOutcome::Success(value) if value == confirmation + )); + assert!(Operation::RecordProviderConfirmation.can_retry_after_unknown()); +} + +#[tokio::test] +async fn disbursement_completion_settles_only_terminal_exactly_bound_state() { + for (state, settles) in [ + ("accepted", false), + ("pending", false), + ("unknown", false), + ("provider-confirmed", true), + ("failed", true), + ] { + let fixture = fixture().await; + let disbursement_id = Uuid::new_v4(); + let instruction_record_id = Uuid::new_v4(); + let command = disbursement_request(instruction_record_id); + let acceptance = disbursement_accepted(disbursement_id, instruction_record_id); + Mock::given(method("GET")) + .and(path(format!( + "/v1/payments/service-fees/disbursements/{disbursement_id}" + ))) + .respond_with(json_answer( + 200, + disbursement_status(disbursement_id, instruction_record_id, state), + )) + .expect(1) + .mount(&fixture.payment) + .await; + + let observed = fixture + .adapters + .observe_completion(&command, &acceptance, &disbursement_completion()) + .await; + assert_eq!( + matches!(&observed, CompletionObservation::Settled(_)), + settles + ); + if !settles { + assert!(matches!(&observed, CompletionObservation::Pending { .. })); + } + } + + let fixture = fixture().await; + let disbursement_id = Uuid::new_v4(); + let instruction_record_id = Uuid::new_v4(); + let other_instruction_record_id = Uuid::new_v4(); + Mock::given(method("GET")) + .and(path(format!( + "/v1/payments/service-fees/disbursements/{disbursement_id}" + ))) + .respond_with(json_answer( + 200, + disbursement_status( + disbursement_id, + other_instruction_record_id, + "provider-confirmed", + ), + )) + .expect(1) + .mount(&fixture.payment) + .await; + let observed = fixture + .adapters + .observe_completion( + &disbursement_request(instruction_record_id), + &disbursement_accepted(disbursement_id, instruction_record_id), + &disbursement_completion(), + ) + .await; + assert!(matches!( + observed, + CompletionObservation::Hold { code } if code == "payment-correlation-mismatch" + )); +} diff --git a/crates/registry-payment-client/src/client.rs b/crates/registry-payment-client/src/client.rs index 65c0459225..37c2303fe0 100644 --- a/crates/registry-payment-client/src/client.rs +++ b/crates/registry-payment-client/src/client.rs @@ -3,8 +3,9 @@ use std::fmt; use registry_payment_protocol::{ - CollectionAccepted, CollectionStatus, PaymentProblem, ReadCollection, RecordReceipt, - RegistryReceipt, RequestCollection, + CollectionAccepted, CollectionStatus, DisbursementAccepted, DisbursementStatus, PaymentProblem, + ProviderConfirmation, ReadCollection, ReadDisbursement, RecordProviderConfirmation, + RecordReceipt, RegistryReceipt, RequestCollection, RequestDisbursement, }; use registry_platform_httpsec::response_trace_id; use registry_platform_httputil::client::{ @@ -186,6 +187,118 @@ impl PaymentClient { Ok(answer) } + /// Submit one authoritative instruction. This sends once: the released + /// Mifos bulk profile does not prove provider deduplication on replay. + pub async fn request_disbursement( + &self, + token: &BearerToken, + idempotency_key: &str, + request: &RequestDisbursement, + ) -> Result, PaymentClientError> { + validate_key(idempotency_key)?; + request.validate().map_err(|_| { + PaymentClientError::invalid_request("the instruction identity is invalid") + })?; + let builder = self + .http + .post(self.path_url(&["disbursements"])?) + .header(AUTHORIZATION, token.authorization_header_value()) + .header(ACCEPT, JSON_MEDIA_TYPE) + .header(CONTENT_TYPE, JSON_MEDIA_TYPE) + .header(IDEMPOTENCY_KEY_HEADER, idempotency_key) + .json(request); + let answer: PaymentComplete = + self.json_answer(builder, StatusCode::ACCEPTED).await?; + validate_disbursement_acceptance( + &answer.value, + request, + StatusCode::ACCEPTED, + &answer.trace_id, + )?; + Ok(answer) + } + + /// Recover only a known original request, without another provider send. + pub async fn disbursement_receipt( + &self, + token: &BearerToken, + idempotency_key: &str, + request: &RequestDisbursement, + ) -> Result, PaymentClientError> { + validate_key(idempotency_key)?; + request.validate().map_err(|_| { + PaymentClientError::invalid_request("the instruction identity is invalid") + })?; + let builder = self + .http + .post(self.path_url(&["disbursements", "receipt"])?) + .header(AUTHORIZATION, token.authorization_header_value()) + .header(ACCEPT, JSON_MEDIA_TYPE) + .header(CONTENT_TYPE, JSON_MEDIA_TYPE) + .header(IDEMPOTENCY_KEY_HEADER, idempotency_key) + .json(request); + let answer = self.json_answer(builder, StatusCode::OK).await?; + validate_disbursement_acceptance(&answer.value, request, StatusCode::OK, &answer.trace_id)?; + Ok(answer) + } + + /// Observe one saved payout without initiating a new instruction. + pub async fn read_disbursement( + &self, + token: &BearerToken, + request: &ReadDisbursement, + ) -> Result, PaymentClientError> { + validate_collection_id(request.disbursement_id)?; + let builder = self + .http + .get(self.path_url(&["disbursements", &request.disbursement_id.to_string()])?) + .header(AUTHORIZATION, token.authorization_header_value()) + .header(ACCEPT, JSON_MEDIA_TYPE); + let answer: PaymentComplete = + self.json_answer(builder, StatusCode::OK).await?; + answer + .value + .validate() + .map_err(|_| body_protocol(StatusCode::OK, Some(answer.trace_id.clone())))?; + if answer.value.disbursement_id != request.disbursement_id { + return Err(correlation_protocol(StatusCode::OK, Some(answer.trace_id))); + } + Ok(answer) + } + + /// Report exact provider confirmation using the saved Adapter evidence. + pub async fn record_provider_confirmation( + &self, + token: &BearerToken, + idempotency_key: &str, + request: &RecordProviderConfirmation, + ) -> Result, PaymentClientError> { + validate_key(idempotency_key)?; + validate_collection_id(request.disbursement_id)?; + let builder = self + .http + .post(self.path_url(&[ + "disbursements", + &request.disbursement_id.to_string(), + "record-provider-confirmation", + ])?) + .header(AUTHORIZATION, token.authorization_header_value()) + .header(ACCEPT, JSON_MEDIA_TYPE) + .header(CONTENT_TYPE, JSON_MEDIA_TYPE) + .header(IDEMPOTENCY_KEY_HEADER, idempotency_key) + .json(request); + let answer: PaymentComplete = + self.send_keyed_json(builder, StatusCode::OK).await?; + answer + .value + .validate() + .map_err(|_| body_protocol(StatusCode::OK, Some(answer.trace_id.clone())))?; + if answer.value.disbursement_id != request.disbursement_id { + return Err(correlation_protocol(StatusCode::OK, Some(answer.trace_id))); + } + Ok(answer) + } + fn collections_url(&self) -> Result { self.path_url(&["collections"]) } @@ -321,6 +434,23 @@ fn validate_acceptance( Ok(()) } +fn validate_disbursement_acceptance( + answer: &DisbursementAccepted, + request: &RequestDisbursement, + status: StatusCode, + trace_id: &str, +) -> Result<(), PaymentClientError> { + answer + .validate() + .map_err(|_| body_protocol(status, Some(trace_id.to_owned())))?; + if answer.instruction_record_id != request.instruction_record_id + || answer.instruction_version != request.instruction_version + { + return Err(correlation_protocol(status, Some(trace_id.to_owned()))); + } + Ok(()) +} + fn validate_collection_id(value: Uuid) -> Result<(), PaymentClientError> { if value.is_nil() { Err(PaymentClientError::invalid_request( diff --git a/crates/registry-payment-client/src/lib.rs b/crates/registry-payment-client/src/lib.rs index 04747289fd..c2d2aa9bbc 100644 --- a/crates/registry-payment-client/src/lib.rs +++ b/crates/registry-payment-client/src/lib.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: Apache-2.0 -//! Bounded client for the Adapter payment collection capability. +//! Bounded client for Adapter collection and disbursement capabilities. //! //! The client sends only the authoritative bill identifier and version a //! service workflow supplies. Amount, provider state, and receipt evidence @@ -19,7 +19,9 @@ pub use client::{PaymentClient, PaymentComplete}; pub use config::PaymentClientConfig; pub use error::{PaymentClientError, PaymentProtocolFailure}; pub use registry_payment_protocol::{ - CollectionAccepted, CollectionState, CollectionStatus, Money, PaymentProblem, - PaymentProblemCode, ReadCollection, RecordReceipt, RegistryReceipt, RequestCollection, + CollectionAccepted, CollectionState, CollectionStatus, DisbursementAccepted, DisbursementState, + DisbursementStatus, Money, PaymentProblem, PaymentProblemCode, ProviderConfirmation, + ReadCollection, ReadDisbursement, RecordProviderConfirmation, RecordReceipt, RegistryReceipt, + RequestCollection, RequestDisbursement, }; pub use registry_platform_httputil::client::{BearerToken, TransportKind}; diff --git a/crates/registry-payment-client/tests/http_boundary.rs b/crates/registry-payment-client/tests/http_boundary.rs index 8150aef5b9..6e1f4aa089 100644 --- a/crates/registry-payment-client/tests/http_boundary.rs +++ b/crates/registry-payment-client/tests/http_boundary.rs @@ -10,7 +10,8 @@ use axum::routing::{get, post}; use axum::Router; use registry_payment_client::{ BearerToken, CollectionState, PaymentClient, PaymentClientConfig, PaymentClientError, - PaymentProblemCode, PaymentProtocolFailure, ReadCollection, RecordReceipt, RequestCollection, + PaymentProblemCode, PaymentProtocolFailure, ReadCollection, RecordProviderConfirmation, + RecordReceipt, RequestCollection, RequestDisbursement, }; use serde_json::json; use url::Url; @@ -108,6 +109,14 @@ async fn serve_fixture( "/adapter/v1/payments/bill-payments/collections/{collection_id}/record-receipt", post(answer), ) + .route( + "/adapter/v1/payments/bill-payments/disbursements", + post(answer), + ) + .route( + "/adapter/v1/payments/bill-payments/disbursements/{disbursement_id}/record-provider-confirmation", + post(answer), + ) .with_state(fixture.clone()); let listener = tokio::net::TcpListener::bind("127.0.0.1:0") .await @@ -136,6 +145,80 @@ fn token() -> BearerToken { BearerToken::new("synthetic-payment-token").expect("fixture token") } +#[tokio::test] +async fn g2p_submission_sends_once_when_the_provider_outcome_is_unknown() { + let (client, fixture) = serve_problem( + StatusCode::SERVICE_UNAVAILABLE, + PaymentProblemCode::OutcomeUnknown, + ) + .await; + let request = RequestDisbursement { + instruction_record_id: Uuid::new_v4(), + instruction_version: 1, + }; + let error = client + .request_disbursement(&token(), KEY, &request) + .await + .unwrap_err(); + assert!(matches!( + error, + PaymentClientError::Problem { + code: PaymentProblemCode::OutcomeUnknown, + .. + } + )); + let captured = fixture.observations.lock().unwrap(); + assert_eq!(captured.len(), 1); + assert_eq!( + captured[0].uri.path(), + "/adapter/v1/payments/bill-payments/disbursements" + ); + let body: serde_json::Value = serde_json::from_slice(&captured[0].body).unwrap(); + assert_eq!( + body["instructionRecordId"], + json!(request.instruction_record_id) + ); + assert_eq!(body["instructionVersion"], 1); + assert!(body.get("amount").is_none()); +} + +#[tokio::test] +async fn g2p_confirmation_uses_the_adapter_provider_confirmation_route() { + let (client, fixture) = serve_problem( + StatusCode::UNPROCESSABLE_ENTITY, + PaymentProblemCode::InvalidRequest, + ) + .await; + let request = RecordProviderConfirmation { + disbursement_id: Uuid::new_v4(), + }; + let error = client + .record_provider_confirmation(&token(), KEY, &request) + .await + .unwrap_err(); + assert!(matches!( + error, + PaymentClientError::Problem { + code: PaymentProblemCode::InvalidRequest, + .. + } + )); + let captured = fixture.observations.lock().unwrap(); + assert_eq!(captured.len(), 1); + assert_eq!( + captured[0].uri.path(), + format!( + "/adapter/v1/payments/bill-payments/disbursements/{}/record-provider-confirmation", + request.disbursement_id + ) + ); + assert_eq!(captured[0].method, Method::POST); + assert_eq!( + serde_json::from_slice::(&captured[0].body).unwrap(), + json!({"disbursementId": request.disbursement_id}) + ); +} + fn acceptance(collection_id: Uuid, bill_id: Uuid) -> serde_json::Value { json!({ "collectionId": collection_id, diff --git a/crates/registry-payment-mifos-connector/Cargo.toml b/crates/registry-payment-mifos-connector/Cargo.toml new file mode 100644 index 0000000000..dc3421f6a8 --- /dev/null +++ b/crates/registry-payment-mifos-connector/Cargo.toml @@ -0,0 +1,30 @@ +[package] +name = "registry-payment-mifos-connector" +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +repository.workspace = true +description = "Bounded connector for released Mifos Payment Hub EE payment APIs." +publish = false + +[lints] +workspace = true + +[features] +schema = ["dep:schemars", "registry-platform-yaml/schema"] + +[dependencies] +registry-platform-httputil.workspace = true +registry-platform-crypto.workspace = true +registry-platform-yaml.workspace = true +reqwest.workspace = true +schemars = { workspace = true, optional = true } +serde.workspace = true +serde_json = { workspace = true, features = ["raw_value"] } +thiserror.workspace = true +url.workspace = true +zeroize.workspace = true + +[dev-dependencies] +tokio.workspace = true diff --git a/crates/registry-payment-mifos-connector/README.md b/crates/registry-payment-mifos-connector/README.md new file mode 100644 index 0000000000..9869c195c4 --- /dev/null +++ b/crates/registry-payment-mifos-connector/README.md @@ -0,0 +1,157 @@ +# Mifos Payment Hub EE legacy connector + +This crate is a bounded HTTP client for one explicit legacy Payment Hub EE +profile: + +- P2G collection: `ph-ee-connector-channel` v1.12.2 +- G2P raw batch submission: `ph-ee-bulk-processor` v1.12.1 +- authoritative provider observations: `ph-ee-operations-app` v1.17.1 + +These components are independently versioned. The profile does not mean that a +deployment called “PH-EE 2.0” implements the same wire contract. In particular, +the unreleased `paymenthub-ee-*` development branches changed bulk fields from +`subType` to `paymentMode` and added other fields. Operators must pin and verify +the deployed component images or source commits. + +## Boundary + +The public client supports: + +- `POST /channel/collection`, with the released two-payer collection body; +- `GET /api/v1/transactionRequests`, read directly from operations rather than + the channel `txnState` adapter that collapses most states to `RECEIVED`; +- `POST /batchtransactions` with `Type: raw` and exactly one v1.12.1 + instruction; +- `GET /api/v1/batch/detail` with a page size of two, requiring exactly one + operation whose batch, correlation, funding party, recipient, exact amount, + and currency match the submitted instruction. + +Amounts remain decimal strings. Comparisons normalize only decimal spelling, +without binary floating-point conversion. A future or unrecognized provider +state becomes `PaymentState::Unknown`, never success or failure. Missing or +changed identity, amount, currency, or G2P destination fails closed as a +protocol error. + +Submission is asynchronous. `SubmissionState::Accepted` means only that the +provider returned the pinned acknowledgement. `PaymentState::ProviderConfirmed` +means only that operations reported `SUCCESS` for a collection or `COMPLETED` +for a transfer. The inspected source does not prove inter-provider settlement, +beneficiary credit, or end-to-end reconciliation, so this crate makes none of +those claims. + +Every mutation is attempted once. A timeout, connection failure, oversized +answer, unexpected status, or malformed acknowledgement after dispatch returns +`ConnectorError::OutcomeUnknown`. The connector never automatically submits a +replacement. PH-EE's optional bulk deduplication worker removes duplicate +instructions within a batch. It is not strong request-level idempotency for a +repeated `X-CorrelationID`, and the inspected operations schema does not impose +a uniqueness constraint on client correlation. + +## Offline fixture replay + +The crate exposes pure `build_*` and `parse_*` functions for an operator CLI to +replay provider-pack fixtures without making a network call: + +- `build_collection_request` and `parse_collection_acceptance`; +- `parse_collection_status`; +- `build_batch_request` and `parse_batch_acceptance`; +- `parse_batch_status`. + +A fixture should pin `CONNECTOR_PROFILE`, name direction as `p2gCollection` or +`g2pDisbursement`, carry the typed command, provider HTTP status where the +acknowledgement has multiple released forms, provider body, and exact expected +request body and state. Replay should compare request JSON structurally, reject +another profile rather than guessing a compatible version, and compare the +closed `PaymentState`. Fixture bodies are provider data and must remain +synthetic and non-secret. + +## Authentication and deployment inputs + +Released PH-EE deployments differ: + +- channel and operations have authorization disabled by default in their + released configuration, but can be placed behind bearer-JWT authorization; +- bulk uses connector-common JWS in the released configuration and receives a + tenant-specific `X-SIGNATURE`; +- ingress TLS, tenant routing, BPMN workflows, scheme connectors, and internal + component authorization are deployment configuration. + +The crate therefore accepts only a bounded bearer token and/or precomputed +`X-SIGNATURE` at the individual send boundary. It does not hold signing keys, +mint tokens, accept arbitrary headers, persist credentials, or infer that +header presence proves authentication. Production endpoints must use HTTPS; +cleartext HTTP is allowed only for loopback protocol doubles. Response bodies +are limited to 64 KiB, redirects are disabled by the shared outbound client, +and errors contain no response, credential, party, or endpoint values. + +The released bulk processor v1.12.1 depends on connector-common +`1.8.1-SNAPSHOT`; the matching connector-common v1.8.1 source is pinned here +as the `ph-ee-connector-common/v1.8.1:rsa-cipher-sha3-256/v1` profile. Despite +the upstream “JWS” name, this is not JOSE, compact JWS, or RS256. The released +code joins the values of present headers in configured order with `:`, appends +the exact UTF-8 body, hashes that string with SHA3-256, renders lowercase hex, +then passes those 64 ASCII bytes to Java's default RSA cipher with a private +PKCS#8 key. Its configured header order is `X-BatchID`, `X-CorrelationID`, +`Platform-TenantId`. This connector's raw batch request has no `X-BatchID`, so +the request input is correlation, tenant, and exact request body in that order. + +`legacy_signature_preimage`, `legacy_signature_digest`, and +`legacy_batch_request_signature_digest` expose that exact pure boundary. +`LegacyWebSignatureSigner` and `LegacyWebSignatureVerifier` let the host bind +an audited secret-backed raw-RSA implementation without giving this connector +key custody. A normal Registry Stack `SigningProvider` is not compatible: it +produces standards-based signatures with a named digest and encoding. The +legacy provider must perform the exact released private-key operation and emit +standard padded Base64. A signer must sign the digest derived from the same +bytes sent on the wire. A verifier must derive the response digest from the +exact bounded response bytes and only the response headers actually present, +then require exactly one `X-SIGNATURE` and a matching tenant header. + +The built-in client presents a request signature but does not verify PH-EE's +optional response `X-SIGNATURE`. HTTPS server authentication is therefore part +of this profile's trust boundary. A deployment that requires application-layer +response-signature verification must verify the exact response bytes and its +configured signed-header order before calling the pure parsers. This limitation +must not be described as end-to-end JWS protection. + +The released response filter catches signing failures and still copies the +body to the response. A deployment configured to require response signatures +must therefore fail closed on an absent, repeated, malformed, or mismatched +signature. The pure verifier interface does not change the current client's +request-only behavior until the embedding host wires such a required verifier. + +## Primary sources and evidence limits + +Pinned interfaces and models: + +- [channel collection API v1.12.2](https://github.com/openMF/ph-ee-connector-channel/blob/v1.12.2/src/main/java/org/mifos/connector/channel/api/definition/CollectionApi.java) +- [channel collection DTO v1.12.2](https://github.com/openMF/ph-ee-connector-channel/blob/v1.12.2/src/main/java/org/mifos/connector/channel/model/CollectionRequestDTO.java) +- [channel workflow route v1.12.2](https://github.com/openMF/ph-ee-connector-channel/blob/v1.12.2/src/main/java/org/mifos/connector/channel/camel/routes/ChannelRouteBuilder.java) +- [bulk API v1.12.1](https://github.com/openMF/ph-ee-bulk-processor/blob/v1.12.1/src/main/java/org/mifos/processor/bulk/api/definition/BatchTransactions.java) +- [bulk raw request DTO v1.12.1](https://github.com/openMF/ph-ee-bulk-processor/blob/v1.12.1/src/main/java/org/mifos/processor/bulk/schema/BatchRequestDTO.java) +- [operations transaction requests v1.17.1](https://github.com/openMF/ph-ee-operations-app/blob/v1.17.1/src/main/java/org/apache/fineract/api/OperationsDetailedApi.java) +- [operations batch detail v1.17.1](https://github.com/openMF/ph-ee-operations-app/blob/v1.17.1/src/main/java/org/apache/fineract/api/BatchApi.java) +- [operations transfer entity v1.17.1](https://github.com/openMF/ph-ee-operations-app/blob/v1.17.1/src/main/java/org/apache/fineract/operations/Transfer.java) +- [operations transaction-request states v1.17.1](https://github.com/openMF/ph-ee-operations-app/blob/v1.17.1/src/main/java/org/apache/fineract/operations/TransactionRequestState.java) +- [connector-common v1.8.1 request interceptor](https://github.com/openMF/ph-ee-connector-common/blob/v1.8.1/src/main/java/org/mifos/connector/common/interceptor/WebSignatureInterceptor.java) +- [connector-common v1.8.1 signing input](https://github.com/openMF/ph-ee-connector-common/blob/v1.8.1/src/main/java/org/mifos/connector/common/interceptor/JWSUtil.java) +- [connector-common v1.8.1 hash and RSA cipher](https://github.com/openMF/ph-ee-connector-common/blob/v1.8.1/src/main/java/org/mifos/connector/common/util/SecurityUtil.java) +- [connector-common v1.8.1 signer/verifier service](https://github.com/openMF/ph-ee-connector-common/blob/v1.8.1/src/main/java/org/mifos/connector/common/interceptor/service/JsonWebSignatureService.java) +- [connector-common v1.8.1 response filter](https://github.com/openMF/ph-ee-connector-common/blob/v1.8.1/src/main/java/org/mifos/connector/common/interceptor/JWSFilterStrategy.java) +- [bulk processor v1.12.1 dependency pin](https://github.com/openMF/ph-ee-bulk-processor/blob/v1.12.1/build.gradle) +- [bulk processor v1.12.1 signature enablement](https://github.com/openMF/ph-ee-bulk-processor/blob/v1.12.1/src/main/resources/application.yaml) + +The crate tests protocol mapping with loopback doubles only. They do not call a +money-moving provider, execute BPMN, prove a deployed image matches its claimed +source, prove an ingress or certificate configuration, or prove beneficiary +credit. Before operating a deployment, verify its exact image digests, enabled +authentication and JWS rules, tenant and workflow configuration, scheme +connector, operations ingestion, and status behavior with synthetic accounts. + +The v1.12.1 build uses the mutable Maven coordinate +`ph-ee-connector-common:1.8.1-SNAPSHOT`, and connector-common calls +`Cipher.getInstance("RSA")` without naming the transformation. The v1.8.1 tag +and a Temurin Java 17 synthetic vector pin source-compatible behavior, but they +do not prove which connector-common artifact or JVM provider a particular +deployment ran. Verify one synthetic signed request and response against the +exact deployed image before enabling this legacy profile. diff --git a/crates/registry-payment-mifos-connector/src/legacy_web_signature.rs b/crates/registry-payment-mifos-connector/src/legacy_web_signature.rs new file mode 100644 index 0000000000..77ea8c296e --- /dev/null +++ b/crates/registry-payment-mifos-connector/src/legacy_web_signature.rs @@ -0,0 +1,224 @@ +// SPDX-License-Identifier: Apache-2.0 + +//! Exact input construction for connector-common v1.8.1's legacy web +//! signature mechanism. +//! +//! Despite the upstream `JWS` name, this is not JOSE or an RS256 signature. +//! The released Java code hashes a colon-joined UTF-8 string with SHA3-256, +//! renders the digest as lowercase hexadecimal, then passes those ASCII bytes +//! to the JVM's default RSA cipher with a private key. Key custody and that +//! legacy raw-RSA operation remain host responsibilities. + +use crate::{build_batch_request, header_text, BatchCommand, ConnectorError, SecretHeader}; +use std::{future::Future, pin::Pin}; +use zeroize::Zeroizing; + +/// Exact released connector-common source profile implemented by this module. +pub const LEGACY_WEB_SIGNATURE_PROFILE: &str = + "ph-ee-connector-common/v1.8.1:rsa-cipher-sha3-256/v1"; + +const MAX_BODY_BYTES: usize = 65_536; +const MAX_HEADER_BYTES: usize = 128; + +/// Values selected by connector-common's released fixed header order. +/// +/// Missing values are skipped. Present values are included in this exact +/// order: `X-BatchID`, `X-CorrelationID`, `Platform-TenantId`. +#[derive(Clone, Copy)] +pub struct LegacySignatureHeaders<'a> { + batch_id: Option<&'a str>, + correlation_id: Option<&'a str>, + tenant: Option<&'a str>, +} + +impl<'a> LegacySignatureHeaders<'a> { + /// Headers emitted by Registry Stack's released raw batch request. + #[must_use] + pub const fn bulk_request(correlation_id: &'a str, tenant: &'a str) -> Self { + Self { + batch_id: None, + correlation_id: Some(correlation_id), + tenant: Some(tenant), + } + } + + /// Headers observed on one released bulk response. + /// + /// Callers must pass only values actually present exactly once on the + /// bounded HTTP response. They must not derive them from a request or body. + #[must_use] + pub const fn response( + batch_id: Option<&'a str>, + correlation_id: Option<&'a str>, + tenant: &'a str, + ) -> Self { + Self { + batch_id, + correlation_id, + tenant: Some(tenant), + } + } + + /// No selected headers, for exact compatibility and negative tests. + #[must_use] + pub const fn empty() -> Self { + Self { + batch_id: None, + correlation_id: None, + tenant: None, + } + } + + fn ordered(self) -> [Option<&'a str>; 3] { + [self.batch_id, self.correlation_id, self.tenant] + } +} + +/// The exact UTF-8 bytes connector-common hashes. +/// +/// This type intentionally implements neither `Debug` nor `Clone`: it can +/// contain party identifiers and payment details and must not enter logs. +pub struct LegacySignaturePreimage(Zeroizing>); + +impl LegacySignaturePreimage { + #[must_use] + pub fn as_bytes(&self) -> &[u8] { + self.0.as_slice() + } +} + +/// The lowercase 64-byte ASCII SHA3-256 digest passed to the raw-RSA provider. +/// +/// This type intentionally implements neither `Debug` nor `Clone`. Although +/// it is not a key, it is a stable correlate of the signed payment request. +pub struct LegacySignatureDigest(Zeroizing<[u8; 64]>); + +impl LegacySignatureDigest { + #[must_use] + pub fn as_bytes(&self) -> &[u8; 64] { + &self.0 + } + + #[must_use] + pub fn as_str(&self) -> &str { + std::str::from_utf8(self.0.as_slice()) + .expect("legacy digest construction emits lowercase ASCII hex") + } +} + +/// Build connector-common v1.8.1's exact colon-joined UTF-8 signing input. +/// +/// The Java implementation removes the final separator when the body is +/// empty. It fails when both the selected headers and body are empty; this +/// helper returns a value-free error for that malformed input. +pub fn legacy_signature_preimage( + headers: LegacySignatureHeaders<'_>, + body: &[u8], +) -> Result { + if body.len() > MAX_BODY_BYTES || std::str::from_utf8(body).is_err() { + return Err(ConnectorError::Command); + } + + let mut output = Zeroizing::new(Vec::with_capacity(body.len() + 3 * (MAX_HEADER_BYTES + 1))); + let mut selected = false; + for value in headers.ordered().into_iter().flatten() { + if !header_text(value, MAX_HEADER_BYTES) { + return Err(ConnectorError::Command); + } + output.extend_from_slice(value.as_bytes()); + output.push(b':'); + selected = true; + } + + if body.is_empty() { + if !selected { + return Err(ConnectorError::Command); + } + output.pop(); + } else { + output.extend_from_slice(body); + } + Ok(LegacySignaturePreimage(output)) +} + +/// Hash an exact legacy preimage as lowercase SHA3-256 hexadecimal. +pub fn legacy_signature_digest( + headers: LegacySignatureHeaders<'_>, + body: &[u8], +) -> Result { + let preimage = legacy_signature_preimage(headers, body)?; + let digest = registry_platform_crypto::sha3_256(preimage.as_bytes()); + let mut encoded = Zeroizing::new([0u8; 64]); + for (index, byte) in digest.iter().copied().enumerate() { + encoded[index * 2] = hex(byte >> 4); + encoded[index * 2 + 1] = hex(byte & 0x0f); + } + Ok(LegacySignatureDigest(encoded)) +} + +/// Hash the exact bytes of a validated one-instruction raw batch request. +/// +/// The supplied body must equal this connector's encoding of `command`. This +/// prevents a host from signing one representation and dispatching another. +pub fn legacy_batch_request_signature_digest( + command: &BatchCommand, + tenant: &str, + body: &[u8], +) -> Result { + let expected = Zeroizing::new(build_batch_request(command)?); + if expected.as_slice() != body { + return Err(ConnectorError::Command); + } + legacy_signature_digest( + LegacySignatureHeaders::bulk_request(&command.correlation_id, tenant), + body, + ) +} + +const fn hex(value: u8) -> u8 { + match value { + 0..=9 => b'0' + value, + 10..=15 => b'a' + value - 10, + _ => unreachable!(), + } +} + +/// Value-free refusal from a host-side legacy raw-RSA provider. +#[derive(Clone, Copy, Debug, Eq, PartialEq, thiserror::Error)] +pub enum LegacySignatureError { + #[error("the Mifos legacy signature provider refused the operation")] + Refused, + #[error("the Mifos legacy signature did not verify")] + Mismatch, + #[error("the Mifos legacy signature provider is unavailable")] + Unavailable, +} + +/// A bounded asynchronous host-side legacy signature operation. +pub type LegacySignatureFuture<'a, T> = + Pin> + Send + 'a>>; + +/// Secret-backed host implementation of connector-common's raw-RSA private +/// operation over the exact 64 lowercase ASCII digest bytes. +/// +/// Implementations must produce standard padded Base64 for `X-SIGNATURE`. +/// A standards-based JOSE or RS256 signer is not compatible. +pub trait LegacyWebSignatureSigner: Send + Sync { + fn sign_digest_hex<'a>( + &'a self, + digest: &'a LegacySignatureDigest, + ) -> LegacySignatureFuture<'a, SecretHeader>; +} + +/// Host implementation of connector-common's matching public-key recovery +/// and constant-time digest comparison. +/// +/// Implementations must treat a missing, repeated, malformed, or mismatched +/// response signature as failure and must not log either input. +pub trait LegacyWebSignatureVerifier: Send + Sync { + fn verify_digest_hex<'a>( + &'a self, + digest: &'a LegacySignatureDigest, + signature: &'a [u8], + ) -> LegacySignatureFuture<'a, ()>; +} diff --git a/crates/registry-payment-mifos-connector/src/lib.rs b/crates/registry-payment-mifos-connector/src/lib.rs new file mode 100644 index 0000000000..6f7ee659b2 --- /dev/null +++ b/crates/registry-payment-mifos-connector/src/lib.rs @@ -0,0 +1,996 @@ +// SPDX-License-Identifier: Apache-2.0 +//! Bounded client for the released Mifos Payment Hub EE legacy contracts. +//! +//! Provider acceptance and provider-reported completion are observations, not +//! proof that a beneficiary was credited. Mutation calls are attempted once. + +mod legacy_web_signature; + +pub use legacy_web_signature::{ + legacy_batch_request_signature_digest, legacy_signature_digest, legacy_signature_preimage, + LegacySignatureDigest, LegacySignatureError, LegacySignatureFuture, LegacySignatureHeaders, + LegacySignaturePreimage, LegacyWebSignatureSigner, LegacyWebSignatureVerifier, + LEGACY_WEB_SIGNATURE_PROFILE, +}; + +use registry_platform_httputil::client::{ + build_client, transport_protects_the_credential, BearerToken, OutboundOptions, +}; +use reqwest::header::{HeaderValue, AUTHORIZATION, CONTENT_TYPE}; +use serde::{Deserialize, Serialize}; +use serde_json::value::RawValue; +use std::{borrow::Cow, time::Duration}; +use url::Url; +use zeroize::Zeroizing; + +pub const CONNECTOR_PROFILE: &str = + "mifos-ph-ee-legacy/channel-v1.12.2+bulk-v1.12.1+operations-v1.17.1"; +const RESPONSE_LIMIT: u64 = 65_536; +const MAX_TEXT: usize = 128; + +/// Value-free failures. No provider body, header, credential, or caller value +/// is retained in the error. +#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)] +pub enum ConnectorError { + #[error("mifos connector configuration is invalid")] + Configuration, + #[error("mifos connector command is invalid")] + Command, + #[error("mifos provider authentication failed")] + Authentication, + #[error("mifos provider authorization failed")] + Forbidden, + #[error("mifos provider rejected the command")] + Rejected, + #[error("mifos provider response did not satisfy the pinned contract")] + Protocol, + #[error("mifos provider is unavailable")] + Unavailable, + #[error("mifos provider mutation outcome is unknown; do not submit a replacement")] + OutcomeUnknown, +} + +/// An exact positive decimal string and ISO-style uppercase currency code. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct ExactMoney { + pub amount: String, + pub currency: String, +} + +impl ExactMoney { + pub fn validate(&self) -> Result<(), ConnectorError> { + if !valid_decimal(&self.amount) + || self.currency.len() != 3 + || !self.currency.bytes().all(|byte| byte.is_ascii_uppercase()) + { + return Err(ConnectorError::Command); + } + Ok(()) + } +} + +/// One provider party selector. PH-EE calls these key/value pairs. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct PartyIdentifier { + pub key: String, + pub value: String, +} + +impl PartyIdentifier { + fn validate(&self) -> Result<(), ConnectorError> { + if !header_text(&self.key, 32) || !header_text(&self.value, MAX_TEXT) { + return Err(ConnectorError::Command); + } + Ok(()) + } +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct TransactionType { + pub scenario: String, + pub sub_scenario: String, + pub initiator: String, + pub initiator_type: String, +} + +impl TransactionType { + fn validate(&self) -> Result<(), ConnectorError> { + for value in [ + &self.scenario, + &self.sub_scenario, + &self.initiator, + &self.initiator_type, + ] { + if !header_text(value, 32) { + return Err(ConnectorError::Command); + } + } + Ok(()) + } +} + +/// Durable input for one P2G collection attempt. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct CollectionCommand { + pub correlation_id: String, + pub payer: [PartyIdentifier; 2], + pub money: ExactMoney, + pub transaction_type: TransactionType, +} + +impl CollectionCommand { + pub fn validate(&self) -> Result<(), ConnectorError> { + if !identifier(&self.correlation_id, MAX_TEXT) { + return Err(ConnectorError::Command); + } + self.payer[0].validate()?; + self.payer[1].validate()?; + self.money.validate()?; + self.transaction_type.validate() + } + + /// Encode the channel v1.12.2 collection body. + pub fn encode(&self) -> Result, ConnectorError> { + build_collection_request(self) + } + + pub fn decode_status( + &self, + accepted: &CollectionAccepted, + bytes: &[u8], + ) -> Result { + parse_collection_status(self, accepted, bytes) + } +} + +/// Durable input for one G2P instruction submitted through the raw batch API. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct BatchCommand { + /// Stable instruction correlation, sent as `X-CorrelationID`. The released + /// raw item has no separate per-item request identifier. + pub correlation_id: String, + pub purpose: String, + pub credit_party: Vec, + pub debit_party: Vec, + pub sub_type: String, + pub money: ExactMoney, + pub description_text: String, + pub registering_institution_id: Option, + pub program_id: Option, + pub callback_url: Option, +} + +impl BatchCommand { + pub fn validate(&self) -> Result<(), ConnectorError> { + if !identifier(&self.correlation_id, MAX_TEXT) + || !header_text(&self.purpose, MAX_TEXT) + || self.credit_party.len() != 1 + || self.debit_party.len() != 1 + || !header_text(&self.sub_type, 32) + || !bounded_text(&self.description_text, 256) + { + return Err(ConnectorError::Command); + } + for party in self.credit_party.iter().chain(&self.debit_party) { + party.validate()?; + } + self.money.validate()?; + for optional in [ + self.registering_institution_id.as_deref(), + self.program_id.as_deref(), + ] { + if optional.is_some_and(|value| !header_text(value, MAX_TEXT)) { + return Err(ConnectorError::Command); + } + } + if let Some(callback) = &self.callback_url { + validate_callback(callback)?; + } + Ok(()) + } + + /// Encode an array containing exactly one bulk v1.12.1 instruction. + pub fn encode(&self) -> Result, ConnectorError> { + build_batch_request(self) + } + + /// Decode the operations v1.17.1 batch detail page for one instruction. + /// `COMPLETED` becomes provider-confirmed, never settled or credited. + pub fn decode_status( + &self, + accepted: &BatchAccepted, + bytes: &[u8], + ) -> Result { + parse_batch_status(self, accepted, bytes) + } +} + +/// Build the exact channel v1.12.2 request body for fixture replay or sending. +pub fn build_collection_request(command: &CollectionCommand) -> Result, ConnectorError> { + command.validate()?; + #[derive(Serialize)] + #[serde(rename_all = "camelCase")] + struct Body<'a> { + payer: &'a [PartyIdentifier; 2], + amount: Amount<'a>, + transaction_type: &'a TransactionType, + custom_data: [(); 0], + } + #[derive(Serialize)] + struct Amount<'a> { + amount: &'a str, + currency: &'a str, + } + serde_json::to_vec(&Body { + payer: &command.payer, + amount: Amount { + amount: &command.money.amount, + currency: &command.money.currency, + }, + transaction_type: &command.transaction_type, + custom_data: [], + }) + .map_err(|_| ConnectorError::Command) +} + +/// Parse the exact channel acknowledgement without performing an HTTP call. +pub fn parse_collection_acceptance(bytes: &[u8]) -> Result { + check_body_bound(bytes)?; + #[derive(Deserialize)] + #[serde(rename_all = "camelCase", deny_unknown_fields)] + struct Accepted { + transaction_id: String, + } + let response: Accepted = serde_json::from_slice(bytes).map_err(|_| ConnectorError::Protocol)?; + let accepted = CollectionAccepted { + transaction_id: response.transaction_id, + state: SubmissionState::Accepted, + }; + accepted.validate().map_err(|_| ConnectorError::Protocol)?; + Ok(accepted) +} + +/// Parse and correlate an operations transaction-request page without I/O. +pub fn parse_collection_status( + command: &CollectionCommand, + accepted: &CollectionAccepted, + bytes: &[u8], +) -> Result { + command.validate()?; + accepted.validate()?; + check_body_bound(bytes)?; + #[derive(Deserialize)] + #[serde(rename_all = "camelCase")] + struct Page { + content: Vec, + } + #[derive(Deserialize)] + #[serde(rename_all = "camelCase")] + struct Transaction { + transaction_id: String, + state: String, + amount: Box, + currency: String, + client_correlation_id: String, + } + let mut page: Page = serde_json::from_slice(bytes).map_err(|_| ConnectorError::Protocol)?; + if page.content.is_empty() { + return Ok(CollectionObservation { + transaction_id: accepted.transaction_id.clone(), + state: PaymentState::Unknown, + money: command.money.clone(), + }); + } + if page.content.len() != 1 { + return Err(ConnectorError::Protocol); + } + let transaction = page.content.remove(0); + if transaction.transaction_id != accepted.transaction_id + || transaction.client_correlation_id != command.correlation_id + || transaction.currency != command.money.currency + || !decimal_matches(&transaction.amount, &command.money.amount) + { + return Err(ConnectorError::Protocol); + } + let state = match transaction.state.as_str() { + "INITIATED" | "IN_PROGRESS" | "RECEIVED" | "REQUEST_ACCEPTED" | "ACCEPTED" => { + PaymentState::Pending + } + "SUCCESS" => PaymentState::ProviderConfirmed, + "FAILED" | "REJECTED" => PaymentState::Failed, + _ => PaymentState::Unknown, + }; + Ok(CollectionObservation { + transaction_id: transaction.transaction_id, + state, + money: command.money.clone(), + }) +} + +/// Build the exact one-instruction bulk v1.12.1 request body. +pub fn build_batch_request(command: &BatchCommand) -> Result, ConnectorError> { + command.validate()?; + #[derive(Serialize)] + #[serde(rename_all = "camelCase")] + struct Instruction<'a> { + credit_party: &'a [PartyIdentifier], + debit_party: &'a [PartyIdentifier], + sub_type: &'a str, + amount: &'a str, + currency: &'a str, + description_text: &'a str, + } + serde_json::to_vec(&[Instruction { + credit_party: &command.credit_party, + debit_party: &command.debit_party, + sub_type: &command.sub_type, + amount: &command.money.amount, + currency: &command.money.currency, + description_text: &command.description_text, + }]) + .map_err(|_| ConnectorError::Command) +} + +/// Parse either released bulk acknowledgement form without performing I/O. +pub fn parse_batch_acceptance( + command: &BatchCommand, + http_status: u16, + bytes: &[u8], +) -> Result { + command.validate()?; + if !matches!(http_status, 200 | 202) { + return Err(ConnectorError::Protocol); + } + decode_batch_accepted(command, http_status, bytes) +} + +/// Parse and correlate one operations batch-detail entry without I/O. +pub fn parse_batch_status( + command: &BatchCommand, + accepted: &BatchAccepted, + bytes: &[u8], +) -> Result { + command.validate()?; + accepted.validate()?; + if accepted.request_id != command.correlation_id { + return Err(ConnectorError::Protocol); + } + check_body_bound(bytes)?; + #[derive(Deserialize)] + struct Page { + content: Vec, + } + #[derive(Deserialize)] + #[serde(rename_all = "camelCase")] + struct Transfer { + transaction_id: String, + status: String, + payee_party_id: String, + payee_party_id_type: String, + payer_party_id: String, + payer_party_id_type: String, + amount: Box, + currency: String, + batch_id: String, + client_correlation_id: String, + } + let mut page: Page = serde_json::from_slice(bytes).map_err(|_| ConnectorError::Protocol)?; + if page.content.is_empty() { + return Ok(BatchObservation { + batch_id: accepted.batch_id.clone(), + instruction_correlation_id: command.correlation_id.clone(), + provider_reference: None, + state: PaymentState::Unknown, + funding: command.debit_party[0].clone(), + recipient: command.credit_party[0].clone(), + money: command.money.clone(), + }); + } + if page.content.len() != 1 { + return Err(ConnectorError::Protocol); + } + let transfer = page.content.remove(0); + let recipient = &command.credit_party[0]; + let funding = &command.debit_party[0]; + if !identifier(&transfer.transaction_id, MAX_TEXT) + || transfer.batch_id != accepted.batch_id + || transfer.client_correlation_id != command.correlation_id + || transfer.payee_party_id != recipient.value + || transfer.payee_party_id_type != recipient.key + || transfer.payer_party_id != funding.value + || transfer.payer_party_id_type != funding.key + || transfer.currency != command.money.currency + || !decimal_matches(&transfer.amount, &command.money.amount) + { + return Err(ConnectorError::Protocol); + } + let state = match transfer.status.as_str() { + "IN_PROGRESS" => PaymentState::Pending, + "COMPLETED" => PaymentState::ProviderConfirmed, + "FAILED" | "EXCEPTION" => PaymentState::Failed, + "UNKNOWN" => PaymentState::Unknown, + _ => PaymentState::Unknown, + }; + Ok(BatchObservation { + batch_id: accepted.batch_id.clone(), + instruction_correlation_id: command.correlation_id.clone(), + provider_reference: Some(transfer.transaction_id), + state, + funding: funding.clone(), + recipient: recipient.clone(), + money: command.money.clone(), + }) +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum SubmissionState { + Accepted, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum PaymentState { + Pending, + /// The pinned operations API reports its terminal success state. This is + /// not proof of beneficiary credit or inter-provider settlement. + ProviderConfirmed, + Failed, + Unknown, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct CollectionAccepted { + pub transaction_id: String, + pub state: SubmissionState, +} + +impl CollectionAccepted { + fn validate(&self) -> Result<(), ConnectorError> { + if self.state != SubmissionState::Accepted || !identifier(&self.transaction_id, MAX_TEXT) { + return Err(ConnectorError::Command); + } + Ok(()) + } +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct BatchAccepted { + pub batch_id: String, + pub request_id: String, + pub state: SubmissionState, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub suggested_poll_after_seconds: Option, +} + +impl BatchAccepted { + fn validate(&self) -> Result<(), ConnectorError> { + if self.state != SubmissionState::Accepted + || !identifier(&self.batch_id, MAX_TEXT) + || !identifier(&self.request_id, MAX_TEXT) + || self + .suggested_poll_after_seconds + .is_some_and(|value| value > 86_400) + { + return Err(ConnectorError::Command); + } + Ok(()) + } +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct CollectionObservation { + pub transaction_id: String, + pub state: PaymentState, + pub money: ExactMoney, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct BatchObservation { + pub batch_id: String, + pub instruction_correlation_id: String, + pub provider_reference: Option, + pub state: PaymentState, + pub funding: PartyIdentifier, + pub recipient: PartyIdentifier, + pub money: ExactMoney, +} + +/// Deployment-owned endpoints and non-secret routing headers. Each component +/// has its own URL because released PH-EE is not a monolith. +#[derive(Clone, Serialize, Deserialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct MifosConnection { + #[cfg_attr(feature = "schema", schemars(with = "registry_platform_yaml::Url"))] + pub channel_base_url: String, + #[cfg_attr(feature = "schema", schemars(with = "registry_platform_yaml::Url"))] + pub bulk_base_url: String, + #[cfg_attr(feature = "schema", schemars(with = "registry_platform_yaml::Url"))] + pub operations_base_url: String, + #[cfg_attr( + feature = "schema", + schemars(length(min = 1, max = 128), pattern(r"^[\x20-\x7e]+$")) + )] + pub tenant: String, + #[cfg_attr( + feature = "schema", + schemars(length(min = 1, max = 32), pattern(r"^[\x20-\x7e]+$")) + )] + pub payment_scheme: String, +} + +impl MifosConnection { + pub fn validate(&self) -> Result<(), ConnectorError> { + for base in [ + &self.channel_base_url, + &self.bulk_base_url, + &self.operations_base_url, + ] { + parse_base(base)?; + } + if !header_text(&self.tenant, 128) || !header_text(&self.payment_scheme, 32) { + return Err(ConnectorError::Configuration); + } + Ok(()) + } +} + +/// A precomputed PH-EE `X-SIGNATURE` value. Signature construction and key +/// custody remain with the operator's JWS implementation. +pub struct SecretHeader(Zeroizing); + +impl SecretHeader { + pub fn new(value: impl Into) -> Result { + let value = value.into(); + if value.is_empty() + || value.len() > 16 * 1024 + || !value.bytes().all(|byte| byte.is_ascii_graphic()) + { + return Err(ConnectorError::Configuration); + } + Ok(Self(Zeroizing::new(value))) + } + + fn header_value(&self) -> HeaderValue { + let mut value = HeaderValue::from_bytes(self.0.as_bytes()) + .expect("SecretHeader construction guarantees a valid header value"); + value.set_sensitive(true); + value + } + + /// Borrow the validated ASCII signature bytes for a host-side verifier. + /// + /// The value is authentication material. Callers must not log it or place + /// it in diagnostics, metrics, persisted attempts, or public problems. + #[must_use] + pub fn as_bytes(&self) -> &[u8] { + self.0.as_bytes() + } +} + +/// Credentials supplied only at one send boundary. The connector does not +/// persist or refresh them and accepts no arbitrary caller-authored headers. +#[derive(Clone, Copy, Default)] +pub struct RequestAuth<'a> { + bearer: Option<&'a BearerToken>, + signature: Option<&'a SecretHeader>, +} + +impl<'a> RequestAuth<'a> { + #[must_use] + pub const fn none() -> Self { + Self { + bearer: None, + signature: None, + } + } + + #[must_use] + pub const fn bearer(token: &'a BearerToken) -> Self { + Self { + bearer: Some(token), + signature: None, + } + } + + #[must_use] + pub const fn signature(signature: &'a SecretHeader) -> Self { + Self { + bearer: None, + signature: Some(signature), + } + } + + #[must_use] + pub const fn bearer_and_signature(token: &'a BearerToken, signature: &'a SecretHeader) -> Self { + Self { + bearer: Some(token), + signature: Some(signature), + } + } +} + +/// One-attempt HTTP client. It never retries a mutation, including connection +/// errors, timeouts, oversized responses, or malformed acknowledgements. +pub struct MifosClient { + connection: MifosConnection, + channel: Url, + bulk: Url, + operations: Url, + http: reqwest::Client, +} + +impl MifosClient { + pub fn new(connection: MifosConnection) -> Result { + connection.validate()?; + let channel = parse_base(&connection.channel_base_url)?; + let bulk = parse_base(&connection.bulk_base_url)?; + let operations = parse_base(&connection.operations_base_url)?; + let http = build_client(OutboundOptions { + request_timeout: Duration::from_secs(15), + connect_timeout: Duration::from_secs(5), + user_agent: Some(CONNECTOR_PROFILE), + trusted_root_certificates: None, + }) + .map_err(|_| ConnectorError::Configuration)?; + Ok(Self { + connection, + channel, + bulk, + operations, + http, + }) + } + + pub async fn submit_collection( + &self, + command: &CollectionCommand, + auth: &RequestAuth<'_>, + ) -> Result { + let body = command.encode()?; + let request = self + .http + .post(endpoint(&self.channel, "channel/collection")?) + .header("Platform-TenantId", &self.connection.tenant) + .header("X-CorrelationID", &command.correlation_id) + .header("X-Payment-Scheme", &self.connection.payment_scheme) + .header(CONTENT_TYPE, "application/json") + .body(body); + let response = apply_auth(request, auth) + .send() + .await + .map_err(|_| ConnectorError::OutcomeUnknown)?; + let bytes = mutation_response(response, &[200]).await?; + parse_collection_acceptance(&bytes).map_err(|_| ConnectorError::OutcomeUnknown) + } + + pub async fn collection_status( + &self, + command: &CollectionCommand, + accepted: &CollectionAccepted, + auth: &RequestAuth<'_>, + ) -> Result { + command.validate()?; + accepted.validate()?; + let mut url = endpoint(&self.operations, "api/v1/transactionRequests")?; + url.query_pairs_mut() + .append_pair("page", "0") + .append_pair("size", "2") + .append_pair("clientCorrelationId", &command.correlation_id); + let request = self + .http + .get(url) + .header("Platform-TenantId", &self.connection.tenant); + let Some(bytes) = observation_response(apply_auth(request, auth).send().await).await? + else { + return Ok(CollectionObservation { + transaction_id: accepted.transaction_id.clone(), + state: PaymentState::Unknown, + money: command.money.clone(), + }); + }; + command.decode_status(accepted, &bytes) + } + + pub async fn submit_batch( + &self, + command: &BatchCommand, + auth: &RequestAuth<'_>, + ) -> Result { + let body = command.encode()?; + let mut request = self + .http + .post(endpoint(&self.bulk, "batchtransactions")?) + .header("Platform-TenantId", &self.connection.tenant) + .header("X-CorrelationID", &command.correlation_id) + .header("Purpose", &command.purpose) + .header("Type", "raw") + .header(CONTENT_TYPE, "application/json") + .body(body); + if let Some(value) = &command.registering_institution_id { + request = request.header("X-Registering-Institution-ID", value); + } + if let Some(value) = &command.program_id { + request = request.header("X-Program-ID", value); + } + if let Some(value) = &command.callback_url { + request = request.header("X-CallbackURL", value); + } + let response = apply_auth(request, auth) + .send() + .await + .map_err(|_| ConnectorError::OutcomeUnknown)?; + let status = response.status().as_u16(); + let bytes = mutation_response(response, &[200, 202]).await?; + parse_batch_acceptance(command, status, &bytes).map_err(|_| ConnectorError::OutcomeUnknown) + } + + pub async fn batch_status( + &self, + command: &BatchCommand, + accepted: &BatchAccepted, + auth: &RequestAuth<'_>, + ) -> Result { + command.validate()?; + accepted.validate()?; + let mut url = endpoint(&self.operations, "api/v1/batch/detail")?; + url.query_pairs_mut() + .append_pair("batchId", &accepted.batch_id) + .append_pair("status", "ALL") + .append_pair("pageNo", "0") + .append_pair("pageSize", "2") + .append_pair("command", "json"); + let request = self + .http + .get(url) + .header("Platform-TenantId", &self.connection.tenant); + let Some(bytes) = observation_response(apply_auth(request, auth).send().await).await? + else { + return Ok(BatchObservation { + batch_id: accepted.batch_id.clone(), + instruction_correlation_id: command.correlation_id.clone(), + provider_reference: None, + state: PaymentState::Unknown, + funding: command.debit_party[0].clone(), + recipient: command.credit_party[0].clone(), + money: command.money.clone(), + }); + }; + command.decode_status(accepted, &bytes) + } +} + +fn decode_batch_accepted( + command: &BatchCommand, + status: u16, + bytes: &[u8], +) -> Result { + check_body_bound(bytes)?; + let accepted = if status == 200 { + #[derive(Deserialize)] + #[serde(deny_unknown_fields)] + struct Queued { + batch_id: String, + request_id: String, + status: String, + } + let response: Queued = + serde_json::from_slice(bytes).map_err(|_| ConnectorError::Protocol)?; + if response.status != "queued" || response.request_id != command.correlation_id { + return Err(ConnectorError::Protocol); + } + BatchAccepted { + batch_id: response.batch_id, + request_id: response.request_id, + state: SubmissionState::Accepted, + suggested_poll_after_seconds: None, + } + } else { + #[derive(Deserialize)] + #[serde(rename_all = "PascalCase", deny_unknown_fields)] + struct Polling { + polling_path: String, + suggested_callback_seconds: StringOrNumber, + } + #[derive(Deserialize)] + #[serde(untagged)] + enum StringOrNumber { + String(String), + Number(u64), + } + let response: Polling = + serde_json::from_slice(bytes).map_err(|_| ConnectorError::Protocol)?; + let prefix = "/batch/Summary/"; + let batch_id = response + .polling_path + .strip_prefix(prefix) + .ok_or(ConnectorError::Protocol)? + .to_owned(); + let seconds = match response.suggested_callback_seconds { + StringOrNumber::String(value) => { + value.parse::().map_err(|_| ConnectorError::Protocol)? + } + StringOrNumber::Number(value) => value, + }; + BatchAccepted { + batch_id, + request_id: command.correlation_id.clone(), + state: SubmissionState::Accepted, + suggested_poll_after_seconds: Some(seconds), + } + }; + accepted.validate().map_err(|_| ConnectorError::Protocol)?; + Ok(accepted) +} + +fn apply_auth( + mut request: reqwest::RequestBuilder, + auth: &RequestAuth<'_>, +) -> reqwest::RequestBuilder { + if let Some(token) = auth.bearer { + request = request.header(AUTHORIZATION, token.authorization_header_value()); + } + if let Some(signature) = auth.signature { + request = request.header("X-SIGNATURE", signature.header_value()); + } + request +} + +async fn mutation_response( + response: reqwest::Response, + expected: &[u16], +) -> Result, ConnectorError> { + match response.status().as_u16() { + 401 => return Err(ConnectorError::Authentication), + 403 => return Err(ConnectorError::Forbidden), + status if (400..500).contains(&status) => return Err(ConnectorError::Rejected), + status if !expected.contains(&status) => return Err(ConnectorError::OutcomeUnknown), + _ => {} + } + if !json_content_type(&response) { + return Err(ConnectorError::OutcomeUnknown); + } + registry_platform_httputil::read_bounded(response, RESPONSE_LIMIT) + .await + .map_err(|_| ConnectorError::OutcomeUnknown) +} + +async fn observation_response( + response: Result, +) -> Result>, ConnectorError> { + let response = response.map_err(|_| ConnectorError::Unavailable)?; + match response.status().as_u16() { + 200 => {} + 401 => return Err(ConnectorError::Authentication), + 403 => return Err(ConnectorError::Forbidden), + 404 => return Ok(None), + _ => return Err(ConnectorError::Unavailable), + } + if !json_content_type(&response) { + return Err(ConnectorError::Protocol); + } + registry_platform_httputil::read_bounded(response, RESPONSE_LIMIT) + .await + .map(Some) + .map_err(|_| ConnectorError::Unavailable) +} + +fn json_content_type(response: &reqwest::Response) -> bool { + response + .headers() + .get(CONTENT_TYPE) + .and_then(|value| value.to_str().ok()) + .and_then(|value| value.split(';').next()) + == Some("application/json") +} + +fn endpoint(base: &Url, path: &str) -> Result { + base.join(path).map_err(|_| ConnectorError::Configuration) +} + +fn parse_base(value: &str) -> Result { + let url = Url::parse(value).map_err(|_| ConnectorError::Configuration)?; + if !transport_protects_the_credential(&url) + || !url.username().is_empty() + || url.password().is_some() + || url.query().is_some() + || url.fragment().is_some() + || !url.path().ends_with('/') + { + return Err(ConnectorError::Configuration); + } + Ok(url) +} + +fn validate_callback(value: &str) -> Result<(), ConnectorError> { + let url = Url::parse(value).map_err(|_| ConnectorError::Command)?; + if url.scheme() != "https" + || !url.username().is_empty() + || url.password().is_some() + || url.fragment().is_some() + { + return Err(ConnectorError::Command); + } + Ok(()) +} + +fn check_body_bound(bytes: &[u8]) -> Result<(), ConnectorError> { + if bytes.len() > RESPONSE_LIMIT as usize { + return Err(ConnectorError::Protocol); + } + Ok(()) +} + +fn decimal_matches(raw: &RawValue, expected: &str) -> bool { + let value: Cow<'_, str> = if raw.get().starts_with('"') { + match serde_json::from_str::(raw.get()) { + Ok(value) => Cow::Owned(value), + Err(_) => return false, + } + } else { + Cow::Borrowed(raw.get()) + }; + normalize_decimal(&value) == normalize_decimal(expected) +} + +fn normalize_decimal(value: &str) -> Option<(&str, &str)> { + if !valid_decimal(value) { + return None; + } + let (whole, fraction) = value.split_once('.').unwrap_or((value, "")); + let whole = whole.trim_start_matches('0'); + let whole = if whole.is_empty() { "0" } else { whole }; + let fraction = fraction.trim_end_matches('0'); + Some((whole, fraction)) +} + +fn valid_decimal(value: &str) -> bool { + if value.is_empty() || value.len() > 32 || value.starts_with('-') || value.starts_with('+') { + return false; + } + let mut parts = value.split('.'); + let whole = parts.next().unwrap_or_default(); + let fraction = parts.next(); + if parts.next().is_some() + || whole.is_empty() + || !whole.bytes().all(|byte| byte.is_ascii_digit()) + || (whole.len() > 1 && whole.starts_with('0')) + || fraction.is_some_and(|part| { + part.is_empty() || part.len() > 18 || !part.bytes().all(|byte| byte.is_ascii_digit()) + }) + { + return false; + } + whole.bytes().any(|byte| byte != b'0') + || fraction.is_some_and(|part| part.bytes().any(|byte| byte != b'0')) +} + +fn bounded_text(value: &str, max: usize) -> bool { + !value.is_empty() && value.len() <= max && !value.chars().any(char::is_control) +} + +fn header_text(value: &str, max: usize) -> bool { + !value.is_empty() + && value.len() <= max + && value + .bytes() + .all(|byte| byte == b' ' || (0x21..=0x7e).contains(&byte)) +} + +fn identifier(value: &str, max: usize) -> bool { + !value.is_empty() + && value.len() <= max + && value + .bytes() + .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.')) +} diff --git a/crates/registry-payment-mifos-connector/tests/legacy_contract.rs b/crates/registry-payment-mifos-connector/tests/legacy_contract.rs new file mode 100644 index 0000000000..8c4b1c429f --- /dev/null +++ b/crates/registry-payment-mifos-connector/tests/legacy_contract.rs @@ -0,0 +1,534 @@ +// SPDX-License-Identifier: Apache-2.0 + +use registry_payment_mifos_connector::{ + build_batch_request, build_collection_request, parse_batch_acceptance, + parse_collection_acceptance, BatchAccepted, BatchCommand, CollectionAccepted, + CollectionCommand, ConnectorError, ExactMoney, MifosClient, MifosConnection, PartyIdentifier, + PaymentState, RequestAuth, SecretHeader, SubmissionState, TransactionType, +}; +use registry_platform_httputil::client::BearerToken; +use serde_json::json; +use tokio::io::{AsyncReadExt, AsyncWriteExt}; + +fn connection(base: &str) -> MifosConnection { + MifosConnection { + channel_base_url: base.into(), + bulk_base_url: base.into(), + operations_base_url: base.into(), + tenant: "pilot".into(), + payment_scheme: "mpesa".into(), + } +} + +fn collection() -> CollectionCommand { + CollectionCommand { + correlation_id: "collection-1".into(), + payer: [ + PartyIdentifier { + key: "MSISDN".into(), + value: "254700000001".into(), + }, + PartyIdentifier { + key: "ACCOUNTID".into(), + value: "bill-account-1".into(), + }, + ], + money: ExactMoney { + amount: "25.50".into(), + currency: "USD".into(), + }, + transaction_type: TransactionType { + scenario: "MPESA".into(), + sub_scenario: "BUYGOODS".into(), + initiator: "PAYEE".into(), + initiator_type: "BUSINESS".into(), + }, + } +} + +fn batch() -> BatchCommand { + BatchCommand { + correlation_id: "batch-request-1".into(), + purpose: "social-transfer".into(), + credit_party: vec![PartyIdentifier { + key: "MSISDN".into(), + value: "254700000002".into(), + }], + debit_party: vec![PartyIdentifier { + key: "ACCOUNTID".into(), + value: "programme-account".into(), + }], + sub_type: "TRANSFER".into(), + money: ExactMoney { + amount: "1000.00".into(), + currency: "KES".into(), + }, + description_text: "cycle-2026-11".into(), + registering_institution_id: Some("ministry".into()), + program_id: Some("cash-programme".into()), + callback_url: Some("https://registry.example.test/payment-callback".into()), + } +} + +#[test] +fn collection_request_matches_channel_v1_12_2_and_keeps_decimal_text() { + let encoded = build_collection_request(&collection()).unwrap(); + assert_eq!( + serde_json::from_slice::(&encoded).unwrap(), + json!({ + "payer": [ + {"key": "MSISDN", "value": "254700000001"}, + {"key": "ACCOUNTID", "value": "bill-account-1"} + ], + "amount": {"amount": "25.50", "currency": "USD"}, + "transactionType": { + "scenario": "MPESA", + "subScenario": "BUYGOODS", + "initiator": "PAYEE", + "initiatorType": "BUSINESS" + }, + "customData": [] + }) + ); + assert!(String::from_utf8(encoded) + .unwrap() + .contains("\"amount\":\"25.50\"")); +} + +#[test] +fn pure_fixture_parsers_preserve_async_acceptance() { + let collection_accepted = + parse_collection_acceptance(br#"{"transactionId":"tx-fixture"}"#).unwrap(); + assert_eq!(collection_accepted.state, SubmissionState::Accepted); + assert_eq!(collection_accepted.transaction_id, "tx-fixture"); + + let batch_accepted = parse_batch_acceptance( + &batch(), + 200, + br#"{"batch_id":"batch-fixture","request_id":"batch-request-1","status":"queued"}"#, + ) + .unwrap(); + assert_eq!(batch_accepted.state, SubmissionState::Accepted); + assert_eq!(batch_accepted.batch_id, "batch-fixture"); +} + +#[test] +fn batch_acceptance_omits_and_defaults_absent_poll_delay() { + let accepted = BatchAccepted { + batch_id: "batch-1".into(), + request_id: "batch-request-1".into(), + state: SubmissionState::Accepted, + suggested_poll_after_seconds: None, + }; + assert_eq!( + serde_json::to_value(&accepted).unwrap(), + json!({ + "batchId": "batch-1", + "requestId": "batch-request-1", + "state": "accepted" + }) + ); + let decoded: BatchAccepted = serde_json::from_value(json!({ + "batchId": "batch-1", + "requestId": "batch-request-1", + "state": "accepted" + })) + .unwrap(); + assert_eq!(decoded, accepted); +} + +#[test] +fn transport_and_header_inputs_are_bounded_before_dispatch() { + assert!(connection("https://payment.example/").validate().is_ok()); + assert!(connection("http://payment.example/").validate().is_err()); + assert!(connection("http://127.0.0.1:8099/").validate().is_ok()); + + let mut invalid_tenant = connection("https://payment.example/"); + invalid_tenant.tenant = "pilot\r\nX-Injected: yes".into(); + assert_eq!( + invalid_tenant.validate().unwrap_err(), + ConnectorError::Configuration + ); + assert!(SecretHeader::new("signature\nX-Injected: yes").is_err()); + + let oversized = vec![b'x'; 65_537]; + assert_eq!( + parse_collection_acceptance(&oversized).unwrap_err(), + ConnectorError::Protocol + ); +} + +#[test] +fn collection_status_uses_operations_states_without_channel_flattening() { + let accepted = CollectionAccepted { + transaction_id: "tx-1".into(), + state: SubmissionState::Accepted, + }; + for (provider, expected) in [ + ("INITIATED", PaymentState::Pending), + ("IN_PROGRESS", PaymentState::Pending), + ("RECEIVED", PaymentState::Pending), + ("REQUEST_ACCEPTED", PaymentState::Pending), + ("ACCEPTED", PaymentState::Pending), + ("SUCCESS", PaymentState::ProviderConfirmed), + ("FAILED", PaymentState::Failed), + ("REJECTED", PaymentState::Failed), + ("SETTLED_BY_FUTURE_VERSION", PaymentState::Unknown), + ] { + let body = json!({ + "content": [{ + "transactionId": "tx-1", + "state": provider, + "amount": "25.50", + "currency": "USD", + "clientCorrelationId": "collection-1" + }] + }); + assert_eq!( + collection() + .decode_status(&accepted, body.to_string().as_bytes()) + .unwrap() + .state, + expected + ); + } + + assert_eq!( + collection() + .decode_status(&accepted, br#"{"content":[]}"#) + .unwrap() + .state, + PaymentState::Unknown + ); +} + +#[test] +fn collection_status_refuses_changed_identity_or_money() { + let accepted = CollectionAccepted { + transaction_id: "tx-1".into(), + state: SubmissionState::Accepted, + }; + let original = r#"{"content":[{"transactionId":"tx-1","state":"SUCCESS","amount":25.50,"currency":"USD","clientCorrelationId":"collection-1"}]}"#; + for changed in [ + original.replace("tx-1", "tx-2"), + original.replace("collection-1", "collection-2"), + original.replace("25.50", "25.51"), + original.replace("USD", "EUR"), + ] { + assert_eq!( + collection() + .decode_status(&accepted, changed.as_bytes()) + .unwrap_err(), + ConnectorError::Protocol + ); + } +} + +#[test] +fn one_instruction_batch_matches_bulk_v1_12_1_not_the_dev_contract() { + let encoded = build_batch_request(&batch()).unwrap(); + assert_eq!( + serde_json::from_slice::(&encoded).unwrap(), + json!([{ + "creditParty": [{"key": "MSISDN", "value": "254700000002"}], + "debitParty": [{"key": "ACCOUNTID", "value": "programme-account"}], + "subType": "TRANSFER", + "amount": "1000.00", + "currency": "KES", + "descriptionText": "cycle-2026-11" + }]) + ); + let text = String::from_utf8(encoded).unwrap(); + assert!(!text.contains("paymentMode")); + assert!(!text.contains("requestId")); +} + +#[test] +fn batch_status_requires_exact_one_instruction_detail() { + let accepted = BatchAccepted { + batch_id: "batch-1".into(), + request_id: "batch-request-1".into(), + state: SubmissionState::Accepted, + suggested_poll_after_seconds: None, + }; + let succeeded = br#"{"content":[{"transactionId":"transfer-1","status":"COMPLETED","payeePartyId":"254700000002","payeePartyIdType":"MSISDN","payerPartyId":"programme-account","payerPartyIdType":"ACCOUNTID","amount":"1000.00","currency":"KES","batchId":"batch-1","clientCorrelationId":"batch-request-1"}]}"#; + let observation = batch().decode_status(&accepted, succeeded).unwrap(); + assert_eq!(observation.state, PaymentState::ProviderConfirmed); + assert_eq!( + observation.provider_reference.as_deref(), + Some("transfer-1") + ); + assert_eq!(observation.instruction_correlation_id, "batch-request-1"); + assert_eq!(observation.funding, batch().debit_party[0]); + assert_eq!(observation.recipient, batch().credit_party[0]); + assert_eq!(observation.money, batch().money); + let failed = br#"{"content":[{"transactionId":"transfer-1","status":"FAILED","payeePartyId":"254700000002","payeePartyIdType":"MSISDN","payerPartyId":"programme-account","payerPartyIdType":"ACCOUNTID","amount":1000.00,"currency":"KES","batchId":"batch-1","clientCorrelationId":"batch-request-1"}]}"#; + assert_eq!( + batch().decode_status(&accepted, failed).unwrap().state, + PaymentState::Failed + ); + let drift = br#"{"content":[{"transactionId":"transfer-1","status":"RECONCILING","payeePartyId":"254700000002","payeePartyIdType":"MSISDN","payerPartyId":"programme-account","payerPartyIdType":"ACCOUNTID","amount":"1000.00","currency":"KES","batchId":"batch-1","clientCorrelationId":"batch-request-1"}]}"#; + assert_eq!( + batch().decode_status(&accepted, drift).unwrap().state, + PaymentState::Unknown + ); + let inconsistent = br#"{"content":[{"transactionId":"transfer-1","status":"COMPLETED","payeePartyId":"changed-recipient","payeePartyIdType":"MSISDN","payerPartyId":"programme-account","payerPartyIdType":"ACCOUNTID","amount":"1000.00","currency":"KES","batchId":"batch-1","clientCorrelationId":"batch-request-1"}]}"#; + assert_eq!( + batch().decode_status(&accepted, inconsistent).unwrap_err(), + ConnectorError::Protocol + ); + let changed_funding = String::from_utf8(succeeded.to_vec()) + .unwrap() + .replace("programme-account", "other-account"); + assert_eq!( + batch() + .decode_status(&accepted, changed_funding.as_bytes()) + .unwrap_err(), + ConnectorError::Protocol + ); + let missing_destination = br#"{"content":[{"transactionId":"transfer-1","status":"COMPLETED","payerPartyId":"programme-account","payerPartyIdType":"ACCOUNTID","amount":"1000.00","currency":"KES","batchId":"batch-1","clientCorrelationId":"batch-request-1"}]}"#; + assert_eq!( + batch() + .decode_status(&accepted, missing_destination) + .unwrap_err(), + ConnectorError::Protocol + ); +} + +#[tokio::test] +async fn clients_send_only_bounded_profile_headers_and_return_async_acceptance() { + 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 { + let collection_request = receive(&listener).await; + assert!(collection_request.starts_with("POST /channel/collection HTTP/1.1\r\n")); + assert_header(&collection_request, "platform-tenantid", "pilot"); + assert_header(&collection_request, "x-correlationid", "collection-1"); + assert_header(&collection_request, "x-payment-scheme", "mpesa"); + assert_header(&collection_request, "authorization", "Bearer canary-token"); + respond( + collection_request.socket, + 200, + r#"{"transactionId":"tx-1"}"#, + ) + .await; + + let batch_request = receive(&listener).await; + assert!(batch_request.starts_with("POST /batchtransactions HTTP/1.1\r\n")); + assert_header(&batch_request, "platform-tenantid", "pilot"); + assert_header(&batch_request, "x-correlationid", "batch-request-1"); + assert_header(&batch_request, "purpose", "social-transfer"); + assert_header(&batch_request, "type", "raw"); + assert_header(&batch_request, "x-signature", "canary-jws"); + assert_header(&batch_request, "x-registering-institution-id", "ministry"); + assert_header(&batch_request, "x-program-id", "cash-programme"); + assert_header( + &batch_request, + "x-callbackurl", + "https://registry.example.test/payment-callback", + ); + respond( + batch_request.socket, + 200, + r#"{"batch_id":"batch-1","request_id":"batch-request-1","status":"queued"}"#, + ) + .await; + }); + + let client = MifosClient::new(connection(&format!("http://{address}/"))).unwrap(); + let bearer = BearerToken::new("canary-token").unwrap(); + let signature = SecretHeader::new("canary-jws").unwrap(); + let collection_accepted = client + .submit_collection(&collection(), &RequestAuth::bearer(&bearer)) + .await + .unwrap(); + assert_eq!(collection_accepted.state, SubmissionState::Accepted); + let batch_accepted = client + .submit_batch(&batch(), &RequestAuth::signature(&signature)) + .await + .unwrap(); + assert_eq!(batch_accepted.state, SubmissionState::Accepted); + server.await.unwrap(); +} + +#[tokio::test] +async fn status_reads_operations_detail_and_preserves_provider_only_semantics() { + 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 { + let collection_request = receive(&listener).await; + assert!(collection_request.starts_with( + "GET /api/v1/transactionRequests?page=0&size=2&clientCorrelationId=collection-1 HTTP/1.1\r\n" + )); + assert_header(&collection_request, "platform-tenantid", "pilot"); + respond( + collection_request.socket, + 200, + r#"{"content":[{"transactionId":"tx-1","state":"SUCCESS","amount":"25.50","currency":"USD","clientCorrelationId":"collection-1"}]}"#, + ) + .await; + + let batch_request = receive(&listener).await; + assert!(batch_request.starts_with( + "GET /api/v1/batch/detail?batchId=batch-1&status=ALL&pageNo=0&pageSize=2&command=json HTTP/1.1\r\n" + )); + assert_header(&batch_request, "platform-tenantid", "pilot"); + respond( + batch_request.socket, + 200, + r#"{"content":[{"transactionId":"transfer-1","status":"COMPLETED","payeePartyId":"254700000002","payeePartyIdType":"MSISDN","payerPartyId":"programme-account","payerPartyIdType":"ACCOUNTID","amount":"1000.00","currency":"KES","batchId":"batch-1","clientCorrelationId":"batch-request-1"}]}"#, + ) + .await; + }); + + let client = MifosClient::new(connection(&format!("http://{address}/"))).unwrap(); + let collection_observation = client + .collection_status( + &collection(), + &CollectionAccepted { + transaction_id: "tx-1".into(), + state: SubmissionState::Accepted, + }, + &RequestAuth::none(), + ) + .await + .unwrap(); + assert_eq!( + collection_observation.state, + PaymentState::ProviderConfirmed + ); + let batch_observation = client + .batch_status( + &batch(), + &BatchAccepted { + batch_id: "batch-1".into(), + request_id: "batch-request-1".into(), + state: SubmissionState::Accepted, + suggested_poll_after_seconds: None, + }, + &RequestAuth::none(), + ) + .await + .unwrap(); + assert_eq!(batch_observation.state, PaymentState::ProviderConfirmed); + assert_eq!( + batch_observation.recipient, + PartyIdentifier { + key: "MSISDN".into(), + value: "254700000002".into() + } + ); + server.await.unwrap(); +} + +#[tokio::test] +async fn polling_acknowledgement_is_still_only_async_acceptance() { + 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 { + let request = receive(&listener).await; + respond( + request.socket, + 202, + r#"{"PollingPath":"/batch/Summary/batch-2","SuggestedCallbackSeconds":"10"}"#, + ) + .await; + }); + let client = MifosClient::new(connection(&format!("http://{address}/"))).unwrap(); + let accepted = client + .submit_batch(&batch(), &RequestAuth::none()) + .await + .unwrap(); + assert_eq!(accepted.batch_id, "batch-2"); + assert_eq!(accepted.request_id, "batch-request-1"); + assert_eq!(accepted.state, SubmissionState::Accepted); + assert_eq!(accepted.suggested_poll_after_seconds, Some(10)); + server.await.unwrap(); +} + +#[tokio::test] +async fn uncertain_submit_is_not_retried_and_errors_do_not_disclose_secrets() { + 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 { + let request = receive(&listener).await; + respond(request.socket, 200, r#"{"transactionId":"wrong value"}"#).await; + assert!( + tokio::time::timeout(std::time::Duration::from_millis(150), listener.accept()) + .await + .is_err() + ); + }); + let client = MifosClient::new(connection(&format!("http://{address}/"))).unwrap(); + let token = BearerToken::new("secret-canary-never-disclose").unwrap(); + let error = client + .submit_collection(&collection(), &RequestAuth::bearer(&token)) + .await + .unwrap_err(); + assert_eq!(error, ConnectorError::OutcomeUnknown); + let rendered = format!("{error:?} {error}"); + assert!(!rendered.contains("secret-canary")); + assert!(!rendered.contains("wrong value")); + server.await.unwrap(); +} + +struct Received { + text: String, + socket: tokio::net::TcpStream, +} + +impl std::ops::Deref for Received { + type Target = str; + fn deref(&self) -> &Self::Target { + &self.text + } +} + +async fn receive(listener: &tokio::net::TcpListener) -> Received { + let (mut socket, _) = listener.accept().await.unwrap(); + let mut bytes = Vec::new(); + let mut chunk = [0_u8; 4096]; + loop { + let count = socket.read(&mut chunk).await.unwrap(); + assert!(count > 0); + bytes.extend_from_slice(&chunk[..count]); + if let Some(header_end) = bytes.windows(4).position(|window| window == b"\r\n\r\n") { + let headers = String::from_utf8_lossy(&bytes[..header_end + 4]); + let length = headers + .lines() + .find_map(|line| { + line.to_ascii_lowercase() + .strip_prefix("content-length:") + .map(str::trim) + .and_then(|value| value.parse::().ok()) + }) + .unwrap_or(0); + if bytes.len() >= header_end + 4 + length { + break; + } + } + } + Received { + text: String::from_utf8(bytes).unwrap(), + socket, + } +} + +fn assert_header(request: &str, name: &str, value: &str) { + let expected = format!("{}: {}", name.to_ascii_lowercase(), value); + assert!( + request + .lines() + .map(str::to_ascii_lowercase) + .any(|line| line == expected.to_ascii_lowercase()), + "missing header {name}" + ); +} + +async fn respond(mut socket: tokio::net::TcpStream, status: u16, body: &str) { + let response = format!( + "HTTP/1.1 {status} OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", + body.len() + ); + socket.write_all(response.as_bytes()).await.unwrap(); +} diff --git a/crates/registry-payment-mifos-connector/tests/legacy_web_signature.rs b/crates/registry-payment-mifos-connector/tests/legacy_web_signature.rs new file mode 100644 index 0000000000..79da38636e --- /dev/null +++ b/crates/registry-payment-mifos-connector/tests/legacy_web_signature.rs @@ -0,0 +1,182 @@ +// SPDX-License-Identifier: Apache-2.0 + +use registry_payment_mifos_connector::{ + build_batch_request, legacy_batch_request_signature_digest, legacy_signature_digest, + legacy_signature_preimage, BatchCommand, ExactMoney, LegacySignatureDigest, + LegacySignatureError, LegacySignatureFuture, LegacySignatureHeaders, LegacyWebSignatureSigner, + LegacyWebSignatureVerifier, PartyIdentifier, SecretHeader, LEGACY_WEB_SIGNATURE_PROFILE, +}; + +const JAVA_17_DIGEST: &str = "b87417754485eba4f5d1bb206f0e8358a6bc678ea75343d7baf25ecfd5187bff"; +const JAVA_17_SIGNATURE: &str = "nrNse2Cxxd0nvvTqHx9jWudZrS6SoZtBQom2nK4thmguBznaq0xv1Hi+4LJyt1USy1LM7NvJ3qPf+XASfsPYx1sR6jUhqvCaoEcAjrTBantFj94T0hpopuHLyaI+lO+ALct2okH4qsgcJt6tx7si3sgrQGBPy/vVzNE4XQNLgfFSlC7CJO2sgmW09RpdHiasJfOWuTIacLDwtU+TktCM+pbOkrhwyXddbw/9v7YJITGkLHKUXW63+Osw5vymXBgjZNzUELjUzlQHBscWqFeAwD3JOq7UlQGQ1mdAoNcJwNcbhrULXhjHdHg/JrMIofuiOzwj8Ixw0PGW+gQwlncLkg=="; +const JAVA_17_PUBLIC_KEY_DER_BASE64: &str = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAuN/Zn65A4aySYv8BsStT2cHbVJTuOZtyfHrplIhdtTp6jjFZ1KGsVvZpbih77yPukQS2nSdgUsyos/r/4DM28Dv6mnun1geQNySYFUwoqyUWoPxTjf1NTI/PDFGhWTxFiAydxS8GPswdLi6Hnaw+sskZFrsNh/9l/zUeUk6/7eFNZDPg0WQNLzpfQgJWm31p6yZuWq6Iv12x1EXeHaxqOL6rIZQm5lc95k2RZ0sZIlcI+8/kczx2OxdN2qYkrx4ZBa8Xt9mWvDMGIPOUGEtEVVRC32YarPZnShgFdDhRXL5eoSWC4nVUAseIuDnW1X8mLL5QkeQeFDqAWbWAVJY3swIDAQAB"; + +fn batch() -> BatchCommand { + BatchCommand { + correlation_id: "batch-request-1".into(), + purpose: "social-transfer".into(), + credit_party: vec![PartyIdentifier { + key: "MSISDN".into(), + value: "254700000002".into(), + }], + debit_party: vec![PartyIdentifier { + key: "ACCOUNTID".into(), + value: "programme-account".into(), + }], + sub_type: "TRANSFER".into(), + money: ExactMoney { + amount: "1000.00".into(), + currency: "KES".into(), + }, + description_text: "cycle-2026-11".into(), + registering_institution_id: None, + program_id: None, + callback_url: None, + } +} + +#[test] +fn released_header_order_skips_absent_values_and_preserves_exact_body() { + let body = br#"[{"amount":"1000.00"}]"#; + let request = legacy_signature_preimage( + LegacySignatureHeaders::bulk_request("batch-request-1", "pilot"), + body, + ) + .unwrap(); + assert_eq!( + request.as_bytes(), + br#"batch-request-1:pilot:[{"amount":"1000.00"}]"# + ); + + let with_batch = legacy_signature_preimage( + LegacySignatureHeaders::response( + Some("provider-batch-1"), + Some("batch-request-1"), + "pilot", + ), + body, + ) + .unwrap(); + assert_eq!( + with_batch.as_bytes(), + br#"provider-batch-1:batch-request-1:pilot:[{"amount":"1000.00"}]"# + ); +} + +#[test] +fn response_preimage_uses_only_headers_the_released_server_returned() { + let response = legacy_signature_preimage( + LegacySignatureHeaders::response(None, None, "pilot"), + br#"{"batch_id":"provider-batch-1"}"#, + ) + .unwrap(); + assert_eq!( + response.as_bytes(), + br#"pilot:{"batch_id":"provider-batch-1"}"# + ); +} + +#[test] +fn empty_body_removes_the_last_separator_like_connector_common_v1_8_1() { + let preimage = legacy_signature_preimage( + LegacySignatureHeaders::bulk_request("batch-request-1", "pilot"), + b"", + ) + .unwrap(); + assert_eq!(preimage.as_bytes(), b"batch-request-1:pilot"); +} + +#[test] +fn malformed_or_unbounded_inputs_fail_closed() { + assert!(legacy_signature_preimage(LegacySignatureHeaders::empty(), b"").is_err()); + assert!(legacy_signature_preimage( + LegacySignatureHeaders::response(None, None, "pilot"), + &[0xff] + ) + .is_err()); + assert!(legacy_signature_preimage( + LegacySignatureHeaders::response(None, None, "pilot\nforged"), + b"{}" + ) + .is_err()); + assert!(legacy_signature_preimage( + LegacySignatureHeaders::response(None, None, "pilot"), + &vec![b'x'; 65_537] + ) + .is_err()); +} + +#[test] +fn exact_body_bytes_are_part_of_the_digest() { + let headers = LegacySignatureHeaders::bulk_request("batch-request-1", "pilot"); + let compact = legacy_signature_digest(headers, br#"{"amount":"1000.00"}"#).unwrap(); + let spaced = legacy_signature_digest(headers, br#"{ "amount": "1000.00" }"#).unwrap(); + assert_ne!(compact.as_bytes(), spaced.as_bytes()); +} + +#[test] +fn batch_helper_refuses_bytes_other_than_the_validated_command_encoding() { + let command = batch(); + let body = build_batch_request(&command).unwrap(); + assert!(legacy_batch_request_signature_digest(&command, "pilot", &body).is_ok()); + let changed = String::from_utf8(body) + .unwrap() + .replace("1000.00", "1000.01"); + assert!(legacy_batch_request_signature_digest(&command, "pilot", changed.as_bytes()).is_err()); +} + +/// Generated with Temurin OpenJDK 17.0.20 using the released Java sequence: +/// SHA3-256 UTF-8 input, lowercase hex, then `Cipher.getInstance("RSA")` +/// over a synthetic 2048-bit PKCS#8 key. It is an interoperability vector, +/// not a deployed key or proof of a deployed Payment Hub image. +#[tokio::test] +async fn java_17_vector_reaches_the_typed_legacy_signer_and_verifier() { + assert_eq!( + LEGACY_WEB_SIGNATURE_PROFILE, + "ph-ee-connector-common/v1.8.1:rsa-cipher-sha3-256/v1" + ); + let command = batch(); + let body = build_batch_request(&command).unwrap(); + let digest = legacy_batch_request_signature_digest(&command, "pilot", &body).unwrap(); + assert_eq!(digest.as_str(), JAVA_17_DIGEST); + assert!(JAVA_17_PUBLIC_KEY_DER_BASE64.starts_with("MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8A")); + + let signer = JavaVectorProvider; + let signature = signer.sign_digest_hex(&digest).await.unwrap(); + signer + .verify_digest_hex(&digest, signature.as_bytes()) + .await + .unwrap(); +} + +struct JavaVectorProvider; + +impl LegacyWebSignatureSigner for JavaVectorProvider { + fn sign_digest_hex<'a>( + &'a self, + digest: &'a LegacySignatureDigest, + ) -> LegacySignatureFuture<'a, SecretHeader> { + Box::pin(async move { + if digest.as_str() != JAVA_17_DIGEST { + return Err(LegacySignatureError::Refused); + } + SecretHeader::new(JAVA_17_SIGNATURE).map_err(|_| LegacySignatureError::Refused) + }) + } +} + +impl LegacyWebSignatureVerifier for JavaVectorProvider { + fn verify_digest_hex<'a>( + &'a self, + digest: &'a LegacySignatureDigest, + signature: &'a [u8], + ) -> LegacySignatureFuture<'a, ()> { + Box::pin(async move { + if digest.as_str() == JAVA_17_DIGEST && signature == JAVA_17_SIGNATURE.as_bytes() { + Ok(()) + } else { + Err(LegacySignatureError::Mismatch) + } + }) + } +} diff --git a/crates/registry-payment-protocol/src/lib.rs b/crates/registry-payment-protocol/src/lib.rs index df6c66f9b0..7e3f6902d1 100644 --- a/crates/registry-payment-protocol/src/lib.rs +++ b/crates/registry-payment-protocol/src/lib.rs @@ -207,6 +207,210 @@ pub struct RequestCollection { pub bill_version: u64, } +/// A disbursement intent names an approved, immutable instruction held by the +/// owning registry. The caller cannot supply amount, destination or funding. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct RequestDisbursement { + #[cfg_attr(feature = "schema", schemars(schema_with = "non_nil_uuid_schema"))] + pub instruction_record_id: Uuid, + #[cfg_attr( + feature = "schema", + schemars(range(min = 1, max = 9_007_199_254_740_991_u64)) + )] + pub instruction_version: u64, +} + +/// Read one saved disbursement and its current provider observation. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct ReadDisbursement { + #[cfg_attr(feature = "schema", schemars(schema_with = "non_nil_uuid_schema"))] + pub disbursement_id: Uuid, +} + +impl RequestDisbursement { + /// # Errors + /// Refuses a nil identifier or a nonportable/nonpositive version. + pub fn validate(&self) -> Result<(), ContractError> { + validate_bill(self.instruction_record_id, self.instruction_version) + } +} + +/// A provider accepted the exact instruction command for asynchronous work. +/// This is not confirmation that the recipient was paid. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct DisbursementAccepted { + #[cfg_attr(feature = "schema", schemars(schema_with = "non_nil_uuid_schema"))] + pub disbursement_id: Uuid, + #[cfg_attr(feature = "schema", schemars(schema_with = "non_nil_uuid_schema"))] + pub instruction_record_id: Uuid, + #[cfg_attr(feature = "schema", schemars(schema_with = "non_nil_uuid_schema"))] + pub instruction_id: Uuid, + #[cfg_attr( + feature = "schema", + schemars(range(min = 1, max = 9_007_199_254_740_991_u64)) + )] + pub instruction_version: u64, + pub binding_revision: String, + pub simulation: bool, +} + +impl DisbursementAccepted { + /// # Errors + /// Refuses a missing or malformed durable identity. + pub fn validate(&self) -> Result<(), ContractError> { + validate_bill(self.instruction_record_id, self.instruction_version)?; + if self.instruction_id.is_nil() { + return Err(ContractError("invalid instruction identity")); + } + if self.disbursement_id.is_nil() || !bounded_text(&self.binding_revision, 128) { + return Err(ContractError("invalid disbursement binding")); + } + Ok(()) + } +} + +/// Only provider-confirmed means the pinned provider reported completion. +/// It does not by itself claim end-recipient credit or settlement. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[serde(rename_all = "kebab-case")] +pub enum DisbursementState { + Accepted, + Pending, + ProviderConfirmed, + Failed, + Unknown, +} + +/// A bounded observation of one saved disbursement instruction. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct DisbursementStatus { + #[cfg_attr(feature = "schema", schemars(schema_with = "non_nil_uuid_schema"))] + pub disbursement_id: Uuid, + #[cfg_attr(feature = "schema", schemars(schema_with = "non_nil_uuid_schema"))] + pub instruction_record_id: Uuid, + #[cfg_attr(feature = "schema", schemars(schema_with = "non_nil_uuid_schema"))] + pub instruction_id: Uuid, + #[cfg_attr( + feature = "schema", + schemars(range(min = 1, max = 9_007_199_254_740_991_u64)) + )] + pub instruction_version: u64, + pub binding_revision: String, + pub simulation: bool, + pub state: DisbursementState, + pub money: Money, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub provider_reference: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub failure_reason: Option, +} + +impl DisbursementStatus { + /// # Errors + /// Refuses a status that carries contradictory provider evidence. + pub fn validate(&self) -> Result<(), ContractError> { + DisbursementAccepted { + disbursement_id: self.disbursement_id, + instruction_record_id: self.instruction_record_id, + instruction_id: self.instruction_id, + instruction_version: self.instruction_version, + binding_revision: self.binding_revision.clone(), + simulation: self.simulation, + } + .validate()?; + self.money.minor_units()?; + if (self.state == DisbursementState::ProviderConfirmed) + != self + .provider_reference + .as_ref() + .is_some_and(|value| bounded_text(value, 128)) + || (self.state != DisbursementState::ProviderConfirmed + && self.provider_reference.is_some()) + || (self.state == DisbursementState::Failed) + != self + .failure_reason + .as_ref() + .is_some_and(|value| bounded_text(value, 128)) + || (self.state != DisbursementState::Failed && self.failure_reason.is_some()) + { + return Err(ContractError("state and evidence disagree")); + } + Ok(()) + } +} + +/// Ask the Adapter to report a previously verified provider completion to +/// the instruction registry. The caller supplies no status or evidence. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct RecordProviderConfirmation { + #[cfg_attr(feature = "schema", schemars(schema_with = "non_nil_uuid_schema"))] + pub disbursement_id: Uuid, +} + +/// The exact provider completion reported to the authoritative instruction. +/// This does not claim beneficiary credit or final settlement. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct ProviderConfirmation { + #[cfg_attr(feature = "schema", schemars(schema_with = "non_nil_uuid_schema"))] + pub disbursement_id: Uuid, + #[cfg_attr(feature = "schema", schemars(schema_with = "non_nil_uuid_schema"))] + pub instruction_record_id: Uuid, + #[cfg_attr(feature = "schema", schemars(schema_with = "non_nil_uuid_schema"))] + pub instruction_id: Uuid, + #[cfg_attr( + feature = "schema", + schemars(range(min = 1, max = 9_007_199_254_740_991_u64)) + )] + pub instruction_version: u64, + pub binding_revision: String, + pub simulation: bool, + pub money: Money, + pub provider_reference: String, + pub provider_result_digest: String, +} + +impl ProviderConfirmation { + /// # Errors + /// Refuses a confirmation without exact binding and provider evidence. + pub fn validate(&self) -> Result<(), ContractError> { + DisbursementStatus { + disbursement_id: self.disbursement_id, + instruction_record_id: self.instruction_record_id, + instruction_id: self.instruction_id, + instruction_version: self.instruction_version, + binding_revision: self.binding_revision.clone(), + simulation: self.simulation, + state: DisbursementState::ProviderConfirmed, + money: self.money.clone(), + provider_reference: Some(self.provider_reference.clone()), + failure_reason: None, + } + .validate()?; + if self.provider_result_digest.len() != 64 + || !self + .provider_result_digest + .bytes() + .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte)) + { + return Err(ContractError("invalid provider result digest")); + } + Ok(()) + } +} + impl RequestCollection { /// # Errors /// Refuses a nil identifier or a nonportable/nonpositive bill version. diff --git a/crates/registry-payment-protocol/tests/contract.rs b/crates/registry-payment-protocol/tests/contract.rs index 6ebdc8a986..0d463cb2a1 100644 --- a/crates/registry-payment-protocol/tests/contract.rs +++ b/crates/registry-payment-protocol/tests/contract.rs @@ -1,5 +1,8 @@ // SPDX-License-Identifier: Apache-2.0 -use registry_payment_protocol::{CollectionState, CollectionStatus, Money, RequestCollection}; +use registry_payment_protocol::{ + CollectionState, CollectionStatus, DisbursementState, DisbursementStatus, Money, + ProviderConfirmation, RequestCollection, RequestDisbursement, +}; use serde_json::json; use uuid::Uuid; @@ -34,6 +37,88 @@ fn collection_intent_names_only_the_authoritative_bill() { .is_err()); } +#[test] +fn disbursement_intent_names_only_the_authoritative_instruction() { + let instruction = Uuid::new_v4(); + let intent: RequestDisbursement = serde_json::from_value(json!({ + "instructionRecordId": instruction, "instructionVersion": 1 + })) + .unwrap(); + assert!(intent.validate().is_ok()); + for extra in [ + "amount", + "recipient", + "fundingAccount", + "providerUrl", + "approved", + ] { + let mut value = serde_json::to_value(&intent).unwrap(); + value[extra] = json!("caller-owned"); + assert!( + serde_json::from_value::(value).is_err(), + "{extra}" + ); + } + assert!(RequestDisbursement { + instruction_record_id: instruction, + instruction_version: 0, + } + .validate() + .is_err()); +} + +#[test] +fn only_provider_confirmed_disbursements_carry_provider_evidence() { + let mut status = DisbursementStatus { + disbursement_id: Uuid::new_v4(), + instruction_record_id: Uuid::new_v4(), + instruction_id: Uuid::new_v4(), + instruction_version: 1, + binding_revision: "mifos-legacy-v1".into(), + simulation: true, + state: DisbursementState::Pending, + money: Money { + value: "25.00".into(), + currency: "USD".into(), + scale: 2, + }, + provider_reference: None, + failure_reason: None, + }; + assert!(status.validate().is_ok()); + status.provider_reference = Some("batch-1:transaction-1".into()); + assert!(status.validate().is_err()); + status.state = DisbursementState::ProviderConfirmed; + assert!(status.validate().is_ok()); + status.state = DisbursementState::Failed; + assert!(status.validate().is_err()); + status.provider_reference = None; + status.failure_reason = Some("provider-refused".into()); + assert!(status.validate().is_ok()); +} + +#[test] +fn reported_disbursement_completion_requires_exact_evidence_digest() { + let mut confirmation = ProviderConfirmation { + disbursement_id: Uuid::new_v4(), + instruction_record_id: Uuid::new_v4(), + instruction_id: Uuid::new_v4(), + instruction_version: 1, + binding_revision: "sha256:binding".into(), + simulation: true, + money: Money { + value: "25.00".into(), + currency: "USD".into(), + scale: 2, + }, + provider_reference: "batch-1:transaction-1".into(), + provider_result_digest: "a".repeat(64), + }; + assert!(confirmation.validate().is_ok()); + confirmation.provider_result_digest = "a".repeat(63); + assert!(confirmation.validate().is_err()); +} + #[test] fn money_is_exact_positive_bounded_decimal_text() { for (value, scale, expected) in [ diff --git a/crates/registry-platform-crypto/README.md b/crates/registry-platform-crypto/README.md index f7ca3557d4..bcbf2c9ee1 100644 --- a/crates/registry-platform-crypto/README.md +++ b/crates/registry-platform-crypto/README.md @@ -24,6 +24,9 @@ Crypto primitives shared by registry services. length, and a constant-time byte comparison for shared secrets such as URL tokens. `constant_time_eq` is also exported at the crate root and is the shared compare for secrets. +- `sha3_256(bytes)` exposes AWS-LC's SHA3-256 digest for a consumer with a + pinned external protocol that requires it. The consumer defines the exact + preimage, output representation, and any signature policy. - `random_base64url(bytes)` (also `random::random_base64url`): an unpadded base64url token of 16 to 64 operating-system random bytes, for nonces, `state` values, and session references; other sizes are refused. diff --git a/crates/registry-platform-crypto/src/lib.rs b/crates/registry-platform-crypto/src/lib.rs index faccbc2ced..1e3bfbea2a 100644 --- a/crates/registry-platform-crypto/src/lib.rs +++ b/crates/registry-platform-crypto/src/lib.rs @@ -86,6 +86,18 @@ use std::sync::Arc; #[cfg(feature = "transit")] use std::time::Duration; use thiserror::Error; + +/// SHA3-256 using the platform's maintained AWS-LC backend. +/// +/// Protocol consumers own the exact bytes to hash and the representation of +/// this result. This primitive does not imply a JWS or signing profile. +#[must_use] +pub fn sha3_256(bytes: &[u8]) -> [u8; 32] { + let digest = aws_lc_rs::digest::digest(&aws_lc_rs::digest::SHA3_256, bytes); + let mut output = [0u8; 32]; + output.copy_from_slice(digest.as_ref()); + output +} use url::Host; use zeroize::{Zeroize, Zeroizing}; diff --git a/crates/registry-platform-crypto/tests/sha3_256.rs b/crates/registry-platform-crypto/tests/sha3_256.rs new file mode 100644 index 0000000000..61dfa83653 --- /dev/null +++ b/crates/registry-platform-crypto/tests/sha3_256.rs @@ -0,0 +1,12 @@ +// SPDX-License-Identifier: Apache-2.0 + +#[test] +fn sha3_256_matches_the_empty_message_vector() { + let digest = registry_platform_crypto::sha3_256(b""); + let expected = [ + 0xa7, 0xff, 0xc6, 0xf8, 0xbf, 0x1e, 0xd7, 0x66, 0x51, 0xc1, 0x47, 0x56, 0xa0, 0x61, 0xd6, + 0x62, 0xf5, 0x80, 0xff, 0x4d, 0xe4, 0x3b, 0x49, 0xfa, 0x82, 0xd8, 0x0a, 0x4b, 0x80, 0xf8, + 0x43, 0x4a, + ]; + assert_eq!(digest, expected); +} diff --git a/products/adapter/README.md b/products/adapter/README.md index 484a8cd6d0..c114f7bb7d 100644 --- a/products/adapter/README.md +++ b/products/adapter/README.md @@ -12,8 +12,21 @@ source payloads. The institution's registry remains the system of record. The optional [typed payment host](examples/payment-collections/README.md) shares the listener and PostgreSQL infrastructure while keeping payment attempts outside generic record routes. Coordinator uses dedicated payment -steps; operator configuration binds provider tenant, biller and restricted -registry Actions. The initial connector is synthetic and local-only. +steps. A collection reads an authoritative BReg fee bill; a disbursement +reads an authoritative [BReg instruction](../breg/examples/g2p-disbursement/README.md). +Operator configuration binds restricted registry Actions and an exact provider +pack. The host fixes credentials, origins and mutation methods while the pack +maps the provider's wire shape. The simulator remains synthetic. The Mifos +Payment Hub EE pack is a candidate: its released bulk signature is not yet +implemented by the host, so a direct Mifos G2P connection is refused at +startup before any instruction is bound. Mifos Operations completion is a +provider report and does not authorize a paid +fee-bill receipt. + +For a provider pack upgrade, repeat `--payment-provider-pack` with the current +pack and every retained pack still needed by an unfinished attempt. The host +selects each attempt's exact saved pin for sends and status reads; a missing +retained pack holds that attempt before provider I/O. Source-system knowledge and deployment mappings live in reviewed configuration. A reviewed, versioned pack declares a source's endpoints and route templates, with field mapping in diff --git a/products/adapter/examples/payment-collections/payments.example.yaml b/products/adapter/examples/payment-collections/payments.example.yaml index e29c67104f..06b7059e2d 100644 --- a/products/adapter/examples/payment-collections/payments.example.yaml +++ b/products/adapter/examples/payment-collections/payments.example.yaml @@ -17,12 +17,14 @@ connections: # recovery sends for only this bounded window after the first dispatch. replayWindowSeconds: 3600 provider: - baseUrl: http://127.0.0.1:8099/ - tenant: pilot - biller: ministry - billerName: Ministry - callbackUrl: https://programme.example.test/callback - payerFiBic: SIMBANK + type: simulator + connection: + baseUrl: http://127.0.0.1:8099/ + tenant: pilot + biller: ministry + billerName: Ministry + callbackUrl: https://programme.example.test/callback + payerFiBic: SIMBANK registry: baseUrl: http://127.0.0.1:8080/ recordType: service-fee-bill diff --git a/products/adapter/examples/payment-provider-fixture.yaml b/products/adapter/examples/payment-provider-fixture.yaml new file mode 100644 index 0000000000..9075d960e9 --- /dev/null +++ b/products/adapter/examples/payment-provider-fixture.yaml @@ -0,0 +1,30 @@ +# yaml-language-server: $schema=https://id.registrystack.org/schemas/adapter/payment-provider-fixture/payment-provider-fixture.v1alpha1.schema.json +apiVersion: id.registrystack.org/formats/adapter/payment-provider-fixture/v1alpha1 +kind: AdapterPaymentProviderFixture +type: compiled +connectorProfile: mifos-ph-ee-legacy/channel-v1.12.2+bulk-v1.12.1+operations-v1.17.1 +direction: p2g-collection +command: + correlationId: collection-1 + payer: + - {key: MSISDN, value: '254700000001'} + - {key: ACCOUNTID, value: bill-1} + money: {amount: '25.50', currency: KES} + transactionType: {scenario: MPESA, subScenario: BUYGOODS, initiator: PAYEE, initiatorType: BUSINESS} +expectedRequest: + payer: + - {key: MSISDN, value: '254700000001'} + - {key: ACCOUNTID, value: bill-1} + amount: {amount: '25.50', currency: KES} + transactionType: {scenario: MPESA, subScenario: BUYGOODS, initiator: PAYEE, initiatorType: BUSINESS} + customData: [] +acceptance: + response: {httpStatus: 200, body: {transactionId: tx-1}} + expected: {transactionId: tx-1, state: accepted} +status: + response: + httpStatus: 200 + body: + content: + - {transactionId: tx-1, state: SUCCESS, amount: '25.50', currency: KES, clientCorrelationId: collection-1} + expected: {transactionId: tx-1, state: providerConfirmed, money: {amount: '25.50', currency: KES}} diff --git a/products/adapter/packs/payment-simulator/README.md b/products/adapter/packs/payment-simulator/README.md new file mode 100644 index 0000000000..7741500c63 --- /dev/null +++ b/products/adapter/packs/payment-simulator/README.md @@ -0,0 +1,15 @@ +# Synthetic payment provider pack + +This reviewed pack selects the built-in `simulator-p2g/v1` connector for the +typed Payment Adapter. It is a local test profile. It never moves money. + +The pack fixes the connector and advertised collection capability. A deployment +still supplies its own provider origin, tenant, biller, currency policy, +credential references and BReg binding in `AdapterPayments` configuration. +The connection pins the exact pack bytes; start the host with +`--payment-provider-pack` pointing to this file. The connector implementation +is compiled into `adapter`; the pack cannot execute arbitrary code. + +Check the artifact with `adapterctl payments check-pack pack.yaml`, then check +the deployment with `adapterctl payments check payments.yaml --provider-pack +pack.yaml`. diff --git a/products/adapter/packs/payment-simulator/pack.yaml b/products/adapter/packs/payment-simulator/pack.yaml new file mode 100644 index 0000000000..9b16c724f6 --- /dev/null +++ b/products/adapter/packs/payment-simulator/pack.yaml @@ -0,0 +1,7 @@ +apiVersion: id.registrystack.org/formats/adapter/payment-provider-pack/v1alpha1 +kind: AdapterPaymentProviderPack +id: payment-simulator +version: '1' +connector: simulator-p2g/v1 +capabilities: [collection] +testedVersions: [payment-simulator-p2g-0.1] diff --git a/products/adapter/schemas/payment-provider-fixture.v1alpha1.schema.json b/products/adapter/schemas/payment-provider-fixture.v1alpha1.schema.json new file mode 100644 index 0000000000..c535ff5dee --- /dev/null +++ b/products/adapter/schemas/payment-provider-fixture.v1alpha1.schema.json @@ -0,0 +1,212 @@ +{ + "$defs": { + "Direction": { + "enum": [ + "p2g-collection", + "g2p-disbursement" + ], + "type": "string" + }, + "Exchange": { + "additionalProperties": false, + "properties": { + "expected": true, + "response": { + "$ref": "#/$defs/ProviderResponse" + } + }, + "required": [ + "response", + "expected" + ], + "type": "object" + }, + "FixtureAcceptance": { + "additionalProperties": false, + "properties": { + "correlationId": { + "type": "string" + }, + "references": { + "additionalProperties": { + "type": "string" + }, + "propertyNames": { + "$ref": "#/$defs/LocalId" + }, + "type": "object" + } + }, + "required": [ + "correlationId", + "references" + ], + "type": "object" + }, + "LocalId": { + "description": "A local identifier: a lowercase letter, then up to 63 lowercase letters, digits, `_`, or `-`.", + "pattern": "^[a-z][a-z0-9_-]{0,63}$", + "type": "string" + }, + "MappedExchange": { + "additionalProperties": false, + "properties": { + "acceptance": { + "$ref": "#/$defs/FixtureAcceptance" + }, + "expected": true, + "expectedRequest": true, + "response": { + "$ref": "#/$defs/MappedResponse" + } + }, + "required": [ + "expectedRequest", + "response", + "expected" + ], + "type": "object" + }, + "MappedResponse": { + "additionalProperties": false, + "properties": { + "bodyJson": { + "maxLength": 65536, + "minLength": 1, + "type": "string" + }, + "status": { + "format": "uint32", + "maximum": 599, + "minimum": 100, + "type": "integer" + } + }, + "required": [ + "status", + "bodyJson" + ], + "type": "object" + }, + "ProviderResponse": { + "additionalProperties": false, + "properties": { + "body": true, + "httpStatus": { + "format": "uint32", + "maximum": 599, + "minimum": 100, + "type": "integer" + } + }, + "required": [ + "httpStatus", + "body" + ], + "type": "object" + } + }, + "$id": "https://id.registrystack.org/schemas/adapter/payment-provider-fixture/payment-provider-fixture.v1alpha1.schema.json", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "description": "Both the compiled legacy fixture and the reviewed pure-mapping fixture\nshare one authored envelope during the migration to generic providers.", + "oneOf": [ + { + "additionalProperties": false, + "properties": { + "acceptance": { + "$ref": "#/$defs/Exchange" + }, + "apiVersion": { + "const": "id.registrystack.org/formats/adapter/payment-provider-fixture/v1alpha1", + "type": "string" + }, + "command": true, + "connectorProfile": { + "type": "string" + }, + "direction": { + "$ref": "#/$defs/Direction" + }, + "expectedRequest": true, + "kind": { + "const": "AdapterPaymentProviderFixture", + "type": "string" + }, + "status": { + "$ref": "#/$defs/Exchange" + }, + "type": { + "const": "compiled", + "type": "string" + } + }, + "required": [ + "acceptance", + "apiVersion", + "command", + "connectorProfile", + "direction", + "expectedRequest", + "kind", + "status", + "type" + ], + "type": "object" + }, + { + "additionalProperties": false, + "properties": { + "apiVersion": { + "const": "id.registrystack.org/formats/adapter/payment-provider-fixture/v1alpha1", + "type": "string" + }, + "direction": { + "$ref": "#/$defs/Direction" + }, + "intent": true, + "kind": { + "const": "AdapterPaymentProviderFixture", + "type": "string" + }, + "settings": true, + "status": { + "$ref": "#/$defs/MappedExchange" + }, + "submit": { + "$ref": "#/$defs/MappedExchange" + }, + "type": { + "const": "mapped", + "type": "string" + } + }, + "required": [ + "apiVersion", + "direction", + "intent", + "kind", + "settings", + "status", + "submit", + "type" + ], + "type": "object" + } + ], + "properties": { + "apiVersion": { + "const": "id.registrystack.org/formats/adapter/payment-provider-fixture/v1alpha1", + "type": "string" + }, + "kind": { + "const": "AdapterPaymentProviderFixture", + "type": "string" + } + }, + "required": [ + "apiVersion", + "kind" + ], + "title": "Registry Adapter payment provider fixture", + "unevaluatedProperties": false +} diff --git a/products/adapter/schemas/payment-provider-pack.v1alpha1.schema.json b/products/adapter/schemas/payment-provider-pack.v1alpha1.schema.json new file mode 100644 index 0000000000..71251de9a6 --- /dev/null +++ b/products/adapter/schemas/payment-provider-pack.v1alpha1.schema.json @@ -0,0 +1,199 @@ +{ + "$defs": { + "ConnectorKind": { + "oneOf": [ + { + "enum": [ + "simulator-p2g/v1", + "mifos-ph-ee-legacy/v1" + ], + "type": "string" + }, + { + "const": "adapter-payment-http/v1", + "description": "One fixed-role HTTP transport whose provider-specific behavior is\nlimited to the pack's pure request and response mappings.", + "type": "string" + } + ] + }, + "Digest": { + "description": "A SHA-256 digest: `sha256:` followed by 64 lowercase hex digits.", + "pattern": "^sha256:[0-9a-f]{64}$", + "type": "string" + }, + "LocalId": { + "description": "A local identifier: a lowercase letter, then up to 63 lowercase letters, digits, `_`, or `-`.", + "pattern": "^[a-z][a-z0-9_-]{0,63}$", + "type": "string" + }, + "PaymentCapability": { + "enum": [ + "collection", + "disbursement" + ], + "type": "string" + }, + "PaymentMappingCall": { + "additionalProperties": false, + "description": "One pure mapping pair at a reviewed, origin-relative provider path.\nNeither script can select an origin, endpoint role, method, credential, or\nretry behavior.", + "properties": { + "path": { + "type": "string" + }, + "request": { + "$ref": "#/$defs/RhaiExpression" + }, + "response": { + "$ref": "#/$defs/RhaiExpression" + } + }, + "required": [ + "path", + "request", + "response" + ], + "type": "object" + }, + "PaymentOperationMapping": { + "additionalProperties": false, + "description": "Submit and optional read-only status mappings for one typed payment\ndirection. The host fixes POST for submit and GET for status.", + "properties": { + "auth": { + "$ref": "#/$defs/PaymentProviderAuth", + "description": "Host-enforced credential mechanism for every endpoint in this payment\ndirection. Scripts never receive or select credentials." + }, + "status": { + "$ref": "#/$defs/PaymentMappingCall" + }, + "submit": { + "$ref": "#/$defs/PaymentMappingCall" + } + }, + "required": [ + "auth", + "submit" + ], + "type": "object" + }, + "PaymentProviderAuth": { + "description": "Closed credential mechanisms implemented by the fixed-role payment host.", + "enum": [ + "bearer", + "mifos-legacy-signature" + ], + "type": "string" + }, + "PaymentProviderMapping": { + "additionalProperties": false, + "description": "The complete executable mapping closure of one data-driven provider.\nScripts are reviewed pack files, never deployment values.", + "properties": { + "collection": { + "$ref": "#/$defs/PaymentOperationMapping" + }, + "disbursement": { + "$ref": "#/$defs/PaymentOperationMapping" + }, + "scripts": { + "description": "Every Rhai file reachable from the operation mappings, exactly once.", + "items": { + "$ref": "#/$defs/ScriptReference" + }, + "type": "array" + } + }, + "required": [ + "scripts" + ], + "type": "object" + }, + "RhaiExpression": { + "additionalProperties": false, + "description": "A Rhai expression reference: the digest-pinned file from the pack's\nscript inventory and the precompiled entrypoint to call\n(`products/adapter/CONCEPT.md` sections 5.6 and 8.5). Inline code is\nrefused (CFG-EMBED-1).", + "properties": { + "entrypoint": { + "description": "The precompiled entrypoint the engine calls.", + "type": "string" + }, + "file": { + "description": "The script file path, resolved against the pack's script inventory.", + "type": "string" + } + }, + "required": [ + "file", + "entrypoint" + ], + "type": "object" + }, + "ScriptReference": { + "additionalProperties": false, + "description": "A script seam: code in its own file beside the pack, referenced by a\nrelative path and pinned by digest (CFG-EMBED-1). Scripts never carry\ncredentials and never construct URLs; the `http` component builds every\nrequest from its declared template\n(`products/adapter/CONCEPT.md` section 5.6).", + "properties": { + "digest": { + "$ref": "#/$defs/Digest", + "description": "The `sha256:` digest the file must hash to." + }, + "path": { + "description": "The script file, relative to the pack document.", + "type": "string" + } + }, + "required": [ + "path", + "digest" + ], + "type": "object" + } + }, + "$id": "https://id.registrystack.org/schemas/adapter/payment-provider-pack/payment-provider-pack.v1alpha1.schema.json", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "properties": { + "apiVersion": { + "const": "id.registrystack.org/formats/adapter/payment-provider-pack/v1alpha1", + "type": "string" + }, + "capabilities": { + "items": { + "$ref": "#/$defs/PaymentCapability" + }, + "minItems": 1, + "type": "array", + "uniqueItems": true + }, + "connector": { + "$ref": "#/$defs/ConnectorKind" + }, + "id": { + "$ref": "#/$defs/LocalId" + }, + "kind": { + "const": "AdapterPaymentProviderPack", + "type": "string" + }, + "mapping": { + "$ref": "#/$defs/PaymentProviderMapping", + "description": "Pure, digest-pinned provider wire mappings. Compiled connectors omit\nthis member; the generic HTTP connector requires it." + }, + "testedVersions": { + "default": [], + "items": { + "type": "string" + }, + "type": "array" + }, + "version": { + "type": "string" + } + }, + "required": [ + "apiVersion", + "capabilities", + "connector", + "id", + "kind", + "version" + ], + "title": "Registry Adapter payment provider pack", + "type": "object" +} diff --git a/products/adapter/schemas/payments.v1alpha1.schema.json b/products/adapter/schemas/payments.v1alpha1.schema.json index c1f0a9eb81..7ea46ef5ab 100644 --- a/products/adapter/schemas/payments.v1alpha1.schema.json +++ b/products/adapter/schemas/payments.v1alpha1.schema.json @@ -1,10 +1,402 @@ { "$defs": { + "CollectionProvider": { + "description": "Closed provider bindings for P2G collections, selected by the authored\n`type` member. The shared tagged-union reader preserves source positions\nfor errors inside either strict variant (CFG-ID-7, CFG-SCHEMA-8).", + "oneOf": [ + { + "additionalProperties": false, + "properties": { + "connection": { + "$ref": "#/$defs/SimulatorConnection" + }, + "type": { + "const": "simulator", + "type": "string" + } + }, + "required": [ + "type", + "connection" + ], + "type": "object" + }, + { + "additionalProperties": false, + "properties": { + "connection": { + "$ref": "#/$defs/MifosConnection" + }, + "payer": { + "$ref": "#/$defs/MifosPayerMapping" + }, + "transactionType": { + "$ref": "#/$defs/MifosTransactionType" + }, + "type": { + "const": "mifos", + "type": "string" + } + }, + "required": [ + "type", + "connection", + "payer", + "transactionType" + ], + "type": "object" + }, + { + "additionalProperties": false, + "properties": { + "settings": true, + "statusBaseUrl": { + "$ref": "#/$defs/Url" + }, + "submitBaseUrl": { + "$ref": "#/$defs/Url" + }, + "type": { + "const": "http", + "type": "string" + } + }, + "required": [ + "type", + "submitBaseUrl", + "statusBaseUrl", + "settings" + ], + "type": "object" + } + ] + }, + "Digest": { + "description": "A SHA-256 digest: `sha256:` followed by 64 lowercase hex digits.", + "pattern": "^sha256:[0-9a-f]{64}$", + "type": "string" + }, + "G2pConnection": { + "additionalProperties": false, + "properties": { + "allowedClients": { + "items": { + "type": "string" + }, + "maxItems": 64, + "minItems": 1, + "type": "array", + "uniqueItems": true + }, + "binding": { + "$ref": "#/$defs/G2pConnectionSnapshot" + }, + "id": { + "$ref": "#/$defs/LocalId" + }, + "requiredScope": { + "type": "string" + } + }, + "required": [ + "id", + "allowedClients", + "requiredScope", + "binding" + ], + "type": "object" + }, + "G2pConnectionSnapshot": { + "additionalProperties": false, + "properties": { + "currency": { + "type": "string" + }, + "currencyScale": { + "format": "uint32", + "maximum": 6, + "minimum": 0, + "type": "integer" + }, + "fundingAccountId": { + "type": "string" + }, + "fundingPartyKey": { + "type": "string" + }, + "institutionId": { + "type": "string" + }, + "programmeId": { + "type": "string" + }, + "provider": { + "$ref": "#/$defs/G2pProviderBinding" + }, + "providerPack": { + "$ref": "#/$defs/ProviderPackPin" + }, + "recipientPartyKey": { + "type": "string" + }, + "registry": { + "$ref": "#/$defs/G2pRegistryBinding" + }, + "serviceId": { + "type": "string" + } + }, + "required": [ + "institutionId", + "serviceId", + "programmeId", + "fundingAccountId", + "currency", + "currencyScale", + "providerPack", + "fundingPartyKey", + "recipientPartyKey", + "provider", + "registry" + ], + "type": "object" + }, + "G2pHttpAuth": { + "oneOf": [ + { + "additionalProperties": false, + "properties": { + "type": { + "const": "bearer", + "type": "string" + } + }, + "required": [ + "type" + ], + "type": "object" + }, + { + "additionalProperties": false, + "properties": { + "responseKeyIdentity": { + "type": "string" + }, + "responseKeyRef": { + "$ref": "#/$defs/SecretReference" + }, + "signingKeyIdentity": { + "type": "string" + }, + "signingKeyRef": { + "$ref": "#/$defs/SecretReference" + }, + "type": { + "const": "mifos-legacy-signature", + "type": "string" + } + }, + "required": [ + "type", + "signingKeyIdentity", + "signingKeyRef", + "responseKeyIdentity", + "responseKeyRef" + ], + "type": "object" + } + ] + }, + "G2pProviderBinding": { + "description": "Deployment-owned provider facts frozen into every attempt.", + "oneOf": [ + { + "additionalProperties": false, + "properties": { + "auth": { + "$ref": "#/$defs/G2pHttpAuth" + }, + "credentialIdentity": { + "type": "string" + }, + "credentialRef": { + "$ref": "#/$defs/SecretReference" + }, + "revision": { + "type": "string" + }, + "settings": true, + "statusBaseUrl": { + "$ref": "#/$defs/Url" + }, + "submitBaseUrl": { + "$ref": "#/$defs/Url" + }, + "type": { + "const": "http", + "type": "string" + } + }, + "required": [ + "type", + "revision", + "submitBaseUrl", + "statusBaseUrl", + "credentialIdentity", + "credentialRef", + "auth", + "settings" + ], + "type": "object" + } + ] + }, + "G2pRegistryBinding": { + "additionalProperties": false, + "description": "BReg route and exact Action authority frozen into an attempt.", + "properties": { + "baseUrl": { + "$ref": "#/$defs/Url" + }, + "bindAction": { + "type": "string" + }, + "bindProfile": { + "type": "string" + }, + "credentialIdentity": { + "type": "string" + }, + "credentialRef": { + "$ref": "#/$defs/SecretReference" + }, + "readProfile": { + "type": "string" + }, + "recordRoute": { + "type": "string" + }, + "recordType": { + "type": "string" + }, + "reportAction": { + "type": "string" + }, + "reportProfile": { + "type": "string" + } + }, + "required": [ + "baseUrl", + "credentialIdentity", + "credentialRef", + "recordRoute", + "recordType", + "readProfile", + "bindAction", + "bindProfile", + "reportAction", + "reportProfile" + ], + "type": "object" + }, "LocalId": { "description": "A local identifier: a lowercase letter, then up to 63 lowercase letters, digits, `_`, or `-`.", "pattern": "^[a-z][a-z0-9_-]{0,63}$", "type": "string" }, + "MifosConnection": { + "additionalProperties": false, + "description": "Deployment-owned endpoints and non-secret routing headers. Each component\nhas its own URL because released PH-EE is not a monolith.", + "properties": { + "bulkBaseUrl": { + "$ref": "#/$defs/Url" + }, + "channelBaseUrl": { + "$ref": "#/$defs/Url" + }, + "operationsBaseUrl": { + "$ref": "#/$defs/Url" + }, + "paymentScheme": { + "maxLength": 32, + "minLength": 1, + "pattern": "^[\\x20-\\x7e]+$", + "type": "string" + }, + "tenant": { + "maxLength": 128, + "minLength": 1, + "pattern": "^[\\x20-\\x7e]+$", + "type": "string" + } + }, + "required": [ + "channelBaseUrl", + "bulkBaseUrl", + "operationsBaseUrl", + "tenant", + "paymentScheme" + ], + "type": "object" + }, + "MifosPayerMapping": { + "additionalProperties": false, + "properties": { + "financialAddressKey": { + "maxLength": 32, + "minLength": 1, + "pattern": "^[\\x21-\\x7e]+$", + "type": "string" + }, + "payerIdKey": { + "maxLength": 32, + "minLength": 1, + "pattern": "^[\\x21-\\x7e]+$", + "type": "string" + } + }, + "required": [ + "financialAddressKey", + "payerIdKey" + ], + "type": "object" + }, + "MifosTransactionType": { + "additionalProperties": false, + "properties": { + "initiator": { + "maxLength": 32, + "minLength": 1, + "pattern": "^[\\x21-\\x7e]+$", + "type": "string" + }, + "initiatorType": { + "maxLength": 32, + "minLength": 1, + "pattern": "^[\\x21-\\x7e]+$", + "type": "string" + }, + "scenario": { + "maxLength": 32, + "minLength": 1, + "pattern": "^[\\x21-\\x7e]+$", + "type": "string" + }, + "subScenario": { + "maxLength": 32, + "minLength": 1, + "pattern": "^[\\x21-\\x7e]+$", + "type": "string" + } + }, + "required": [ + "scenario", + "subScenario", + "initiator", + "initiatorType" + ], + "type": "object" + }, "PaymentBinding": { "additionalProperties": false, "description": "Persisted in full before a provider send. It holds credential references\nand identities, never credential values. Rotation at the same reference is\nsupported; changing a reference does not reroute a retained attempt.", @@ -20,7 +412,7 @@ "type": "integer" }, "provider": { - "$ref": "#/$defs/SimulatorConnection" + "$ref": "#/$defs/CollectionProvider" }, "providerCredentialIdentity": { "type": "string" @@ -28,6 +420,10 @@ "providerCredentialRef": { "$ref": "#/$defs/SecretReference" }, + "providerPack": { + "$ref": "#/$defs/ProviderPackPin", + "description": "Exact reviewed provider artifact used for new attempts. Older\nsimulator-only configurations omit it; retained attempts keep their\noriginal binding unchanged across an upgrade." + }, "registry": { "$ref": "#/$defs/RegistryBinding" }, @@ -38,7 +434,6 @@ "type": "integer" }, "simulation": { - "const": true, "type": "boolean" } }, @@ -101,6 +496,26 @@ ], "type": "object" }, + "ProviderPackPin": { + "additionalProperties": false, + "properties": { + "digest": { + "$ref": "#/$defs/Digest" + }, + "id": { + "$ref": "#/$defs/LocalId" + }, + "version": { + "type": "string" + } + }, + "required": [ + "id", + "version", + "digest" + ], + "type": "object" + }, "RegistryBinding": { "additionalProperties": false, "properties": { @@ -220,7 +635,14 @@ "$ref": "#/$defs/PaymentConnection" }, "maxItems": 64, - "minItems": 1, + "type": "array" + }, + "disbursements": { + "default": [], + "items": { + "$ref": "#/$defs/G2pConnection" + }, + "maxItems": 64, "type": "array" }, "kind": { diff --git a/products/adapter/scripts/check_dependency_direction.py b/products/adapter/scripts/check_dependency_direction.py index c7acdd6a8c..9e1836093b 100755 --- a/products/adapter/scripts/check_dependency_direction.py +++ b/products/adapter/scripts/check_dependency_direction.py @@ -123,7 +123,7 @@ CONNECTOR = "registry-adapter-connectors" PAYMENT_HOST = "registry-adapter" PAYMENT_PROTOCOL = "registry-payment-protocol" -PAYMENT_PROVIDER = "registry-payment-simulator-connector" +PAYMENT_PROVIDERS = frozenset({"registry-payment-simulator-connector", "registry-payment-mifos-connector"}) # The maintained product client the connector may reach. CONNECTOR_CLIENTS = frozenset( @@ -304,19 +304,28 @@ def payment_host_may_reach(name: str) -> bool: """The host keeps attempts and calls only the public BReg client surface.""" return ( engine_may_reach(PAYMENT_HOST, name) - or name in {PAYMENT_PROTOCOL, PAYMENT_PROVIDER} + or name == PAYMENT_PROTOCOL or name in PAYMENT_PROVIDERS or name in CONNECTOR_CLIENTS or name in CLIENT_SUPPORT ) def authoring_refused(start, names, every, linked) -> set[str]: - """Authoring may inherit the host closure, not link product clients itself.""" + """Authoring may inherit the host closure and replay a payment provider, not link product clients itself.""" refused = set() for dependency in every.get(start, set()): - permits = payment_host_may_reach if names[dependency] == PAYMENT_HOST else ( - lambda name: engine_may_reach("registry-adapterctl", name) - ) + dependency_name = names[dependency] + if dependency_name == PAYMENT_HOST: + permits = payment_host_may_reach + elif dependency_name in PAYMENT_PROVIDERS: + permits = lambda name: ( + not name.startswith("registry-") + or name == dependency_name + or name == PAYMENT_PROTOCOL + or name.startswith("registry-platform-") + ) + else: + permits = lambda name: engine_may_reach("registry-adapterctl", name) for reached in {dependency, *linked_closure(dependency, linked)}: # The host is the declared authoring edge itself. if names[reached] != PAYMENT_HOST and not permits(names[reached]): @@ -467,12 +476,12 @@ def violations(metadata: dict) -> list[str]: f"{name} reaches package(s) outside registry-platform-* and " f"neutral support: {', '.join(refused)}" ) - elif name in {PAYMENT_PROTOCOL, PAYMENT_PROVIDER}: + elif name == PAYMENT_PROTOCOL or name in PAYMENT_PROVIDERS: refused = sorted( item for item in reached if item.startswith("registry-") and not ( - name == PAYMENT_PROVIDER + name in PAYMENT_PROVIDERS and (item == PAYMENT_PROTOCOL or item.startswith("registry-platform-")) ) ) diff --git a/products/adapter/scripts/test-payment-native.mjs b/products/adapter/scripts/test-payment-native.mjs index 7733a78776..d24deefc25 100644 --- a/products/adapter/scripts/test-payment-native.mjs +++ b/products/adapter/scripts/test-payment-native.mjs @@ -202,7 +202,7 @@ print(json.dumps({'path':str(root), 'python':platform.python_version(), 'files': configuration = { apiVersion: 'id.registrystack.org/formats/adapter/payments/v1alpha1', kind: 'AdapterPayments', connections: [{ id: 'licence-fees', institutionId: 'institution-a', serviceId: 'licence-issuance', allowedClients: ['coordinator-payments'], requiredScope: 'payments:collect', binding: { simulation: true, currency: 'USD', currencyScale: 2, providerCredentialRef: 'secret:file/provider-token', providerCredentialIdentity: 'registry', replayWindowSeconds: 3600, - provider: { baseUrl: simulatorProxy.url, tenant: 'pilot', biller: 'ministry', billerName: 'Ministry', callbackUrl: 'https://programme.example.test/callback', payerFiBic: 'SIMBANK' }, + provider: { type: 'simulator', connection: { baseUrl: simulatorProxy.url, tenant: 'pilot', biller: 'ministry', billerName: 'Ministry', callbackUrl: 'https://programme.example.test/callback', payerFiBic: 'SIMBANK' } }, registry: { baseUrl: registryProxy.url, recordType: fixture.recordType, recordRoute: fixture.recordRoute, readProfile: fixture.readProfile, bindProfile: fixture.bind.profile, receiptProfile: fixture.receipt.profile, bindAction: fixture.bind.action, receiptAction: fixture.receipt.action, credentialRef: 'secret:file/registry-token', credentialIdentity: 'payment-adapter' } }, @@ -234,7 +234,7 @@ print(json.dumps({'path':str(root), 'python':platform.python_version(), 'files': assert.equal(simulatorProxy.records.length, beforeLookup); await simulator.stop(); await startSimulator(); const originalBinding = structuredClone(configuration.connections[0].binding); - Object.assign(configuration.connections[0].binding.provider, { baseUrl: 'http://127.0.0.1:9/', tenant: 'changed-tenant', biller: 'changed-biller' }); + Object.assign(configuration.connections[0].binding.provider.connection, { baseUrl: 'http://127.0.0.1:9/', tenant: 'changed-tenant', biller: 'changed-biller' }); configuration.connections[0].binding.providerCredentialRef = 'secret:file/changed-provider-token'; configuration.connections[0].binding.providerCredentialIdentity = 'changed-producer'; await privateFile(paymentsPath, configuration); await restartAdapter(); diff --git a/products/adapter/scripts/test_dependency_direction.py b/products/adapter/scripts/test_dependency_direction.py index 347c73a0ca..f6f6a4df5e 100755 --- a/products/adapter/scripts/test_dependency_direction.py +++ b/products/adapter/scripts/test_dependency_direction.py @@ -18,6 +18,7 @@ NAMES = { "payment-protocol": "registry-payment-protocol", "payment-provider": "registry-payment-simulator-connector", + "payment-mifos": "registry-payment-mifos-connector", "engine": "registry-adapter", "shared-engine": "registry-adapter-engine", "core": "registry-adapter-core", @@ -55,6 +56,7 @@ INTENDED = { "payment-protocol": ["serde"], "payment-provider": ["payment-protocol", "platform", "serde"], + "payment-mifos": ["payment-protocol", "platform", "serde"], "engine": ["shared-engine", "core", "platform", "platform-script", "serde", ("platform-testing", "dev")], "shared-engine": ["core", "platform", "platform-script", "serde"], "core": ["platform", "serde"], @@ -167,6 +169,14 @@ def failures(**changes: list) -> str: class EngineTests(unittest.TestCase): + def test_authoring_replays_a_payment_provider_without_reaching_product_clients(self): + graph = metadata(ctl=[*INTENDED["ctl"], "payment-mifos"]) + self.assertEqual(MODULE.violations(graph), []) + self.assertIn( + NAMES["breg-client"], + failures(ctl=[*INTENDED["ctl"], "breg-client"]), + ) + def test_only_the_payment_host_reaches_the_payment_contract_and_breg_client(self): graph = metadata(engine=[*INTENDED["engine"], "payment-protocol", "payment-provider", "breg-client"]) self.assertEqual(MODULE.violations(graph), []) diff --git a/products/breg/examples/g2p-disbursement/README.md b/products/breg/examples/g2p-disbursement/README.md new file mode 100644 index 0000000000..4a32afdf7e --- /dev/null +++ b/products/breg/examples/g2p-disbursement/README.md @@ -0,0 +1,101 @@ +# G2P disbursement instruction + +This synthetic project keeps the authoritative disbursement instruction in +BReg while the Payment Adapter owns one provider dispatch, polling, recovery, and +uncertain outcomes. It performs no provider calls. + +The benefit service creates one instruction through +`create-disbursement-instruction`. Its stable `instructionId` is globally +unique in this project, and a positive `instructionVersion` plus +`instructionDigest` bind the source version. The instruction also freezes the +institution, service, programme and cycle, beneficiary identity and destination, funding account, +amount in minor units, currency, and currency scale. No profile has generated +Create or Patch authority, and neither later Action writes those fields. + +`instructionId` is the immutable source correlation UUID. It is deliberately +distinct from the BReg record-root UUID returned as the Action result. Adapter +calls name that root as `instructionRecordId`, then compare the stored source +ID, version, digest, and every frozen instruction fact before any transition. +The exact read route is +`GET /v1/records/disbursement-instructions/{instructionRecordId}` with either +the `payment-adapter-binder` or `payment-adapter-reporter` profile. + +The state machine has three Action-owned transitions: + +1. `create-disbursement-instruction` creates `instruction-ready`. +2. `bind-payout-attempt` changes `instruction-ready` to `attempt-bound`, + atomically recording one `payoutAttemptId` and `providerBindingRevision` + before the Adapter dispatches to a provider. +3. `record-provider-confirmation` changes `attempt-bound` to + `provider-confirmed`, recording exact `providerStatus: COMPLETED`, + `providerReference`, and `providerResultDigest` after the Adapter verifies + the provider response. + +Every Action that changes an existing instruction compares the stored source +identity, version, digest, institution, service, programme, cycle, beneficiary, destination, funding, +and money facts with the Adapter's exact snapshot. It also requires an opaque +BReg target condition captured immediately before the attempt. A changed fact, +changed version, stale condition, or different attempt is refused. + +Only requester client `benefit-service` with scope +`registry:disbursement:create` can create an instruction. Only requester client +`payment-adapter` can select the bind and report profiles, and each profile +requires its separate `registry:payout-attempt:bind` or +`registry:payout-result:report` scope. The Adapter recovers a lost response by +repeating the original idempotency key and exact request. A new key cannot bind +a second attempt or replace a confirmation after the state has advanced. + +The Action routes and profile selections are: + +- `POST /v1/actions/create-disbursement-instruction?accessProfile=disbursement-authority` +- `POST /v1/actions/bind-payout-attempt?accessProfile=payment-adapter-binder` +- `POST /v1/actions/record-provider-confirmation?accessProfile=payment-adapter-reporter` + +## Provider meaning + +`provider-confirmed` means that the configured provider reported the exact +one-instruction batch as `COMPLETED`. It does not establish beneficiary credit, +settlement, or receipt. Those stronger claims require a separately defined and +verified source. + +Pending and unknown provider observations have no BReg mutation. The Adapter +retains them in its attempt custody and continues recovery against the same +attempt. `record-provider-confirmation` accepts only the exact string +`COMPLETED`; `PENDING` and `UNKNOWN` fail input validation, and the instruction +stays `attempt-bound`. That state also makes a second bind fail its commit +guard. + +The Mifos one-instruction batch maps as follows: + +| BReg field | Mifos batch meaning | +| --- | --- | +| `instructionId`, `instructionVersion`, `instructionDigest` | Source instruction correlation and version | +| `institutionId`, `serviceId` | Exact Adapter connection authority | +| `programmeId`, `cycleId` | Programme header and cycle description context | +| `beneficiaryDestination` | One `creditParty` destination | +| `fundingAccountId` | One `debitParty` funding identity | +| `amountMinor`, `currency`, `currencyScale` | Exact batch amount converted without binary floating point | +| `payoutAttemptId` | Adapter-owned attempt correlation before dispatch | +| `providerBindingRevision` | Exact Adapter provider configuration binding | +| `providerReference` | Correlated provider transaction reference from operations detail | +| `providerStatus` | Exact verified provider status, currently only `COMPLETED` | +| `providerResultDigest` | Adapter commitment to the exact verified provider result | + +The authored journey in [`tests/journeys.yaml`](tests/journeys.yaml) covers +authorized creation and exact readback, instruction ID uniqueness, unauthorized +requester clients, changed version and frozen facts, exact idempotent binding, +second-attempt refusal, no-effect pending and unknown results, exact provider +confirmation, and replacement refusal. It uses only synthetic identifiers and +does not contact Mifos or any other provider. + +Validate the authoring contract with a `bregctl` executable built from this +source revision: + +```sh +bregctl check products/breg/examples/g2p-disbursement +``` + +Compiler validation does not prove PostgreSQL uniqueness, authorization, +transaction atomicity, target-condition enforcement, or idempotent recovery. +Those guarantees require `bregctl test` against a disposable PostgreSQL +database using matching `bregctl` and BReg source. diff --git a/products/breg/examples/g2p-disbursement/registry.yaml b/products/breg/examples/g2p-disbursement/registry.yaml new file mode 100644 index 0000000000..1b1abdbe08 --- /dev/null +++ b/products/breg/examples/g2p-disbursement/registry.yaml @@ -0,0 +1,282 @@ +# yaml-language-server: $schema=https://id.registrystack.org/schemas/breg/project/project.v1alpha1.schema.json +apiVersion: id.registrystack.org/formats/breg/project/v1alpha1 +kind: BRegProject +project: + id: g2p-disbursement + canonicalBaseIri: https://g2p-disbursement.example.test + version: 0.1.0 + defaultLanguage: en + display: + label: G2P disbursement instructions + description: Synthetic authoritative instructions with one Adapter-bound payout attempt and an exact provider confirmation. + +package: + sourceRevision: g2p-disbursement-0.1.0 + +datasets: + - id: g2p-disbursements + display: + label: G2P disbursements + description: Authoritative instruction, payout binding, and provider-reported completion facts. + +vocabularies: + - id: disbursement-state + values: [instruction-ready, attempt-bound, provider-confirmed] + +recordTypes: + - id: disbursement-instruction + route: disbursement-instructions + primaryDataset: g2p-disbursements + mutationMode: mutable + constraints: + - id: instruction-id-unique + type: unique + fields: [instruction-id] + - id: payout-attempt-id-unique + type: unique + fields: [payout-attempt-id] + - id: provider-reference-unique + type: unique + fields: [provider-reference] + - id: portable-positive-instruction-version + type: int-range + field: instruction-version + minimum: 1 + maximum: 9007199254740991 + - id: portable-positive-amount-minor + type: int-range + field: amount-minor + minimum: 1 + maximum: 9007199254740991 + - id: portable-currency-scale + type: int-range + field: currency-scale + minimum: 0 + maximum: 6 + display: + label: Disbursement instruction + description: One authority-owned instruction whose payment facts never change after creation. + fields: + - {id: instruction-id, apiName: instructionId, type: uuid, required: true, classification: internal} + - {id: instruction-version, apiName: instructionVersion, type: int64, required: true, classification: internal} + - {id: instruction-digest, apiName: instructionDigest, type: string, required: true, minimumLength: 64, maximumLength: 64, pattern: '^[0-9a-f]{64}$', classification: internal} + - {id: institution-id, apiName: institutionId, type: string, required: true, minimumLength: 1, maximumLength: 128, classification: internal} + - {id: service-id, apiName: serviceId, type: string, required: true, minimumLength: 1, maximumLength: 128, classification: internal} + - {id: programme-id, apiName: programmeId, type: string, required: true, minimumLength: 1, maximumLength: 128, classification: internal} + - {id: cycle-id, apiName: cycleId, type: string, required: true, minimumLength: 1, maximumLength: 128, classification: internal} + - {id: beneficiary-id, apiName: beneficiaryId, type: string, required: true, minimumLength: 1, maximumLength: 128, classification: restricted} + - {id: beneficiary-destination, apiName: beneficiaryDestination, type: string, required: true, minimumLength: 1, maximumLength: 128, pattern: '^[ -~]{1,128}$', classification: restricted} + - {id: funding-account-id, apiName: fundingAccountId, type: string, required: true, minimumLength: 1, maximumLength: 128, classification: restricted} + - {id: amount-minor, apiName: amountMinor, type: int64, required: true, classification: internal} + - {id: currency, type: string, required: true, minimumLength: 3, maximumLength: 3, pattern: '^[A-Z]{3}$', classification: internal} + - {id: currency-scale, apiName: currencyScale, type: int64, required: true, classification: internal} + - {id: disbursement-state, apiName: disbursementState, type: vocabulary-code, vocabulary: disbursement-state, required: true, classification: internal} + - {id: payout-attempt-id, apiName: payoutAttemptId, type: uuid, required: false, classification: internal} + - {id: provider-binding-revision, apiName: providerBindingRevision, type: string, required: false, minimumLength: 1, maximumLength: 128, classification: internal} + - {id: provider-status, apiName: providerStatus, type: string, required: false, minimumLength: 9, maximumLength: 9, pattern: '^COMPLETED$', classification: internal} + - {id: provider-reference, apiName: providerReference, type: string, required: false, minimumLength: 1, maximumLength: 128, classification: internal} + - {id: provider-result-digest, apiName: providerResultDigest, type: string, required: false, minimumLength: 64, maximumLength: 64, pattern: '^[0-9a-f]{64}$', classification: internal} + +actions: + - id: create-disbursement-instruction + display: + label: Create disbursement instruction + description: Freeze one authority-owned instruction before payment processing begins. + execution: {mode: immediate} + inputs: + - {id: instruction-id, apiName: instructionId, type: uuid, required: true, classification: internal} + - {id: instruction-version, apiName: instructionVersion, type: int64, required: true, classification: internal} + - {id: instruction-digest, apiName: instructionDigest, type: string, required: true, minimumLength: 64, maximumLength: 64, classification: internal} + - {id: institution-id, apiName: institutionId, type: string, required: true, minimumLength: 1, maximumLength: 128, classification: internal} + - {id: service-id, apiName: serviceId, type: string, required: true, minimumLength: 1, maximumLength: 128, classification: internal} + - {id: programme-id, apiName: programmeId, type: string, required: true, minimumLength: 1, maximumLength: 128, classification: internal} + - {id: cycle-id, apiName: cycleId, type: string, required: true, minimumLength: 1, maximumLength: 128, classification: internal} + - {id: beneficiary-id, apiName: beneficiaryId, type: string, required: true, minimumLength: 1, maximumLength: 128, classification: restricted} + - {id: beneficiary-destination, apiName: beneficiaryDestination, type: string, required: true, minimumLength: 1, maximumLength: 128, classification: restricted} + - {id: funding-account-id, apiName: fundingAccountId, type: string, required: true, minimumLength: 1, maximumLength: 128, classification: restricted} + - {id: amount-minor, apiName: amountMinor, type: int64, required: true, classification: internal} + - {id: currency, type: string, required: true, minimumLength: 3, maximumLength: 3, classification: internal} + - {id: currency-scale, apiName: currencyScale, type: int64, required: true, classification: internal} + plan: + type: fixed + effects: + - id: instruction + target: {recordType: disbursement-instruction} + operation: create + set: + instruction-id: {fromInput: instruction-id} + instruction-version: {fromInput: instruction-version} + instruction-digest: {fromInput: instruction-digest} + institution-id: {fromInput: institution-id} + service-id: {fromInput: service-id} + programme-id: {fromInput: programme-id} + cycle-id: {fromInput: cycle-id} + beneficiary-id: {fromInput: beneficiary-id} + beneficiary-destination: {fromInput: beneficiary-destination} + funding-account-id: {fromInput: funding-account-id} + amount-minor: {fromInput: amount-minor} + currency: {fromInput: currency} + currency-scale: {fromInput: currency-scale} + disbursement-state: {value: instruction-ready} + + - id: bind-payout-attempt + display: + label: Bind payout attempt + description: Bind exactly one Adapter attempt and provider configuration before dispatch. + execution: {mode: immediate} + inputs: + - {id: instruction, apiName: instructionRecordId, type: reference, target: disbursement-instruction, required: true, classification: internal} + - {id: instruction-id, apiName: instructionId, type: uuid, required: true, classification: internal} + - {id: instruction-version, apiName: instructionVersion, type: int64, required: true, classification: internal} + - {id: instruction-digest, apiName: instructionDigest, type: string, required: true, minimumLength: 64, maximumLength: 64, classification: internal} + - {id: institution-id, apiName: institutionId, type: string, required: true, minimumLength: 1, maximumLength: 128, classification: internal} + - {id: service-id, apiName: serviceId, type: string, required: true, minimumLength: 1, maximumLength: 128, classification: internal} + - {id: programme-id, apiName: programmeId, type: string, required: true, minimumLength: 1, maximumLength: 128, classification: internal} + - {id: cycle-id, apiName: cycleId, type: string, required: true, minimumLength: 1, maximumLength: 128, classification: internal} + - {id: beneficiary-id, apiName: beneficiaryId, type: string, required: true, minimumLength: 1, maximumLength: 128, classification: restricted} + - {id: beneficiary-destination, apiName: beneficiaryDestination, type: string, required: true, minimumLength: 1, maximumLength: 128, classification: restricted} + - {id: funding-account-id, apiName: fundingAccountId, type: string, required: true, minimumLength: 1, maximumLength: 128, classification: restricted} + - {id: amount-minor, apiName: amountMinor, type: int64, required: true, classification: internal} + - {id: currency, type: string, required: true, minimumLength: 3, maximumLength: 3, classification: internal} + - {id: currency-scale, apiName: currencyScale, type: int64, required: true, classification: internal} + - {id: payout-attempt-id, apiName: payoutAttemptId, type: uuid, required: true, classification: internal} + - {id: provider-binding-revision, apiName: providerBindingRevision, type: string, required: true, minimumLength: 1, maximumLength: 128, classification: internal} + commitGuards: + targets: + - {input: instruction, field: disbursement-state, equals: instruction-ready} + - {input: instruction, field: instruction-id, equalsFromInput: instruction-id} + - {input: instruction, field: instruction-version, equalsFromInput: instruction-version} + - {input: instruction, field: instruction-digest, equalsFromInput: instruction-digest} + - {input: instruction, field: institution-id, equalsFromInput: institution-id} + - {input: instruction, field: service-id, equalsFromInput: service-id} + - {input: instruction, field: programme-id, equalsFromInput: programme-id} + - {input: instruction, field: cycle-id, equalsFromInput: cycle-id} + - {input: instruction, field: beneficiary-id, equalsFromInput: beneficiary-id} + - {input: instruction, field: beneficiary-destination, equalsFromInput: beneficiary-destination} + - {input: instruction, field: funding-account-id, equalsFromInput: funding-account-id} + - {input: instruction, field: amount-minor, equalsFromInput: amount-minor} + - {input: instruction, field: currency, equalsFromInput: currency} + - {input: instruction, field: currency-scale, equalsFromInput: currency-scale} + plan: + type: fixed + effects: + - id: instruction + target: {fromInput: instruction} + operation: patch + set: + payout-attempt-id: {fromInput: payout-attempt-id} + provider-binding-revision: {fromInput: provider-binding-revision} + disbursement-state: {value: attempt-bound} + + - id: record-provider-confirmation + display: + label: Record provider confirmation + description: Record the exact provider-reported completion for the one frozen payout attempt. + execution: {mode: immediate} + inputs: + - {id: instruction, apiName: instructionRecordId, type: reference, target: disbursement-instruction, required: true, classification: internal} + - {id: instruction-id, apiName: instructionId, type: uuid, required: true, classification: internal} + - {id: instruction-version, apiName: instructionVersion, type: int64, required: true, classification: internal} + - {id: instruction-digest, apiName: instructionDigest, type: string, required: true, minimumLength: 64, maximumLength: 64, classification: internal} + - {id: institution-id, apiName: institutionId, type: string, required: true, minimumLength: 1, maximumLength: 128, classification: internal} + - {id: service-id, apiName: serviceId, type: string, required: true, minimumLength: 1, maximumLength: 128, classification: internal} + - {id: programme-id, apiName: programmeId, type: string, required: true, minimumLength: 1, maximumLength: 128, classification: internal} + - {id: cycle-id, apiName: cycleId, type: string, required: true, minimumLength: 1, maximumLength: 128, classification: internal} + - {id: beneficiary-id, apiName: beneficiaryId, type: string, required: true, minimumLength: 1, maximumLength: 128, classification: restricted} + - {id: beneficiary-destination, apiName: beneficiaryDestination, type: string, required: true, minimumLength: 1, maximumLength: 128, classification: restricted} + - {id: funding-account-id, apiName: fundingAccountId, type: string, required: true, minimumLength: 1, maximumLength: 128, classification: restricted} + - {id: amount-minor, apiName: amountMinor, type: int64, required: true, classification: internal} + - {id: currency, type: string, required: true, minimumLength: 3, maximumLength: 3, classification: internal} + - {id: currency-scale, apiName: currencyScale, type: int64, required: true, classification: internal} + - {id: payout-attempt-id, apiName: payoutAttemptId, type: uuid, required: true, classification: internal} + - {id: provider-binding-revision, apiName: providerBindingRevision, type: string, required: true, minimumLength: 1, maximumLength: 128, classification: internal} + - {id: provider-status, apiName: providerStatus, type: string, required: true, minimumLength: 9, maximumLength: 9, classification: internal} + - {id: provider-reference, apiName: providerReference, type: string, required: true, minimumLength: 1, maximumLength: 128, classification: internal} + - {id: provider-result-digest, apiName: providerResultDigest, type: string, required: true, minimumLength: 64, maximumLength: 64, classification: internal} + commitGuards: + targets: + - {input: instruction, field: disbursement-state, equals: attempt-bound} + - {input: instruction, field: instruction-id, equalsFromInput: instruction-id} + - {input: instruction, field: instruction-version, equalsFromInput: instruction-version} + - {input: instruction, field: instruction-digest, equalsFromInput: instruction-digest} + - {input: instruction, field: institution-id, equalsFromInput: institution-id} + - {input: instruction, field: service-id, equalsFromInput: service-id} + - {input: instruction, field: programme-id, equalsFromInput: programme-id} + - {input: instruction, field: cycle-id, equalsFromInput: cycle-id} + - {input: instruction, field: beneficiary-id, equalsFromInput: beneficiary-id} + - {input: instruction, field: beneficiary-destination, equalsFromInput: beneficiary-destination} + - {input: instruction, field: funding-account-id, equalsFromInput: funding-account-id} + - {input: instruction, field: amount-minor, equalsFromInput: amount-minor} + - {input: instruction, field: currency, equalsFromInput: currency} + - {input: instruction, field: currency-scale, equalsFromInput: currency-scale} + - {input: instruction, field: payout-attempt-id, equalsFromInput: payout-attempt-id} + - {input: instruction, field: provider-binding-revision, equalsFromInput: provider-binding-revision} + plan: + type: fixed + effects: + - id: instruction + target: {fromInput: instruction} + operation: patch + set: + provider-status: {fromInput: provider-status} + provider-reference: {fromInput: provider-reference} + provider-result-digest: {fromInput: provider-result-digest} + disbursement-state: {value: provider-confirmed} + +accessProfiles: + - id: disbursement-authority + actorKind: service + principalClaim: registry_principal + requesterClients: [benefit-service] + requiredScopes: [registry:disbursement:create] + requiredPurposes: [benefit-disbursement] + permissions: + records: + - recordType: disbursement-instruction + operations: [get] + readableFields: [instruction-id, instruction-version, instruction-digest, institution-id, service-id, programme-id, cycle-id, beneficiary-id, beneficiary-destination, funding-account-id, amount-minor, currency, currency-scale, disbursement-state, payout-attempt-id, provider-binding-revision, provider-status, provider-reference, provider-result-digest] + rowBoundaries: unrestricted + actions: + - action: create-disbursement-instruction + operations: [invoke] + targets: + - {recordType: disbursement-instruction, rowBoundaries: unrestricted} + results: [instruction] + + - id: payment-adapter-binder + actorKind: service + principalClaim: registry_principal + requesterClients: [payment-adapter] + requiredScopes: [registry:payout-attempt:bind] + requiredPurposes: [payment-processing] + permissions: + records: + - recordType: disbursement-instruction + operations: [get] + readableFields: [instruction-id, instruction-version, instruction-digest, institution-id, service-id, programme-id, cycle-id, beneficiary-id, beneficiary-destination, funding-account-id, amount-minor, currency, currency-scale, disbursement-state, payout-attempt-id, provider-binding-revision] + rowBoundaries: unrestricted + actions: + - action: bind-payout-attempt + operations: [invoke] + targets: + - {recordType: disbursement-instruction, rowBoundaries: unrestricted} + results: [instruction] + + - id: payment-adapter-reporter + actorKind: service + principalClaim: registry_principal + requesterClients: [payment-adapter] + requiredScopes: [registry:payout-result:report] + requiredPurposes: [payment-processing] + permissions: + records: + - recordType: disbursement-instruction + operations: [get] + readableFields: [instruction-id, instruction-version, instruction-digest, institution-id, service-id, programme-id, cycle-id, beneficiary-id, beneficiary-destination, funding-account-id, amount-minor, currency, currency-scale, disbursement-state, payout-attempt-id, provider-binding-revision, provider-status, provider-reference, provider-result-digest] + rowBoundaries: unrestricted + actions: + - action: record-provider-confirmation + operations: [invoke] + targets: + - {recordType: disbursement-instruction, rowBoundaries: unrestricted} + results: [instruction] diff --git a/products/breg/examples/g2p-disbursement/tests/journeys.yaml b/products/breg/examples/g2p-disbursement/tests/journeys.yaml new file mode 100644 index 0000000000..cfd724869d --- /dev/null +++ b/products/breg/examples/g2p-disbursement/tests/journeys.yaml @@ -0,0 +1,221 @@ +# 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: exact-g2p-disbursement-instruction + steps: + - id: create-authoritative-instruction + action: create-disbursement-instruction + accessProfile: disbursement-authority + claims: {principal: synthetic-benefit-service, scopes: [registry:disbursement:create], purpose: benefit-disbursement, actorKind: service, requesterClient: benefit-service} + request: + type: invoke + idempotencyKey: create-authoritative-instruction + input: {instructionId: 00000000-0000-4000-8000-000000000101, instructionVersion: 1, instructionDigest: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, institutionId: ministry-social, serviceId: cash-transfer, programmeId: cash-programme, cycleId: cycle-2026-11, beneficiaryId: beneficiary-001, beneficiaryDestination: "254700000002", fundingAccountId: programme-account, amountMinor: 100000, currency: KES, currencyScale: 2} + expect: {outcome: success, status: 200} + captureResults: {instruction: instruction} + + - id: read-frozen-instruction + recordType: disbursement-instruction + accessProfile: disbursement-authority + claims: {principal: synthetic-benefit-service, scopes: [registry:disbursement:create], purpose: benefit-disbursement, actorKind: service, requesterClient: benefit-service} + request: {type: get, recordCapture: instruction} + expect: + outcome: success + status: 200 + fields: {instructionId: 00000000-0000-4000-8000-000000000101, instructionVersion: 1, instructionDigest: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, institutionId: ministry-social, serviceId: cash-transfer, programmeId: cash-programme, cycleId: cycle-2026-11, beneficiaryId: beneficiary-001, beneficiaryDestination: "254700000002", fundingAccountId: programme-account, amountMinor: 100000, currency: KES, currencyScale: 2, disbursementState: instruction-ready} + + - id: changed-version-cannot-replace-instruction + action: create-disbursement-instruction + accessProfile: disbursement-authority + claims: {principal: synthetic-benefit-service, scopes: [registry:disbursement:create], purpose: benefit-disbursement, actorKind: service, requesterClient: benefit-service} + request: + type: invoke + idempotencyKey: replace-instruction-version + input: {instructionId: 00000000-0000-4000-8000-000000000101, instructionVersion: 2, instructionDigest: bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb, institutionId: ministry-social, serviceId: cash-transfer, programmeId: cash-programme, cycleId: cycle-2026-11, beneficiaryId: beneficiary-001, beneficiaryDestination: "254700000002", fundingAccountId: programme-account, amountMinor: 100000, currency: KES, currencyScale: 2} + expect: {outcome: refusal, status: 409, problemCode: mutation.conflict} + + - id: capture-bind-condition-after-create + action: bind-payout-attempt + accessProfile: payment-adapter-binder + claims: {principal: synthetic-payment-adapter, scopes: [registry:payout-attempt:bind], purpose: payment-processing, actorKind: service, requesterClient: payment-adapter} + request: {type: target-conditions, input: {instructionRecordId: {recordCapture: instruction}}} + expect: {outcome: success, status: 200} + capture: bind-condition-after-create + + - id: unauthorized-service-cannot-bind + action: bind-payout-attempt + accessProfile: payment-adapter-binder + claims: {principal: synthetic-unauthorized-adapter, scopes: [], purpose: payment-processing, actorKind: service, requesterClient: payment-adapter} + request: + type: invoke + idempotencyKey: unauthorized-bind + preconditions: {instructionRecordId: {conditionCapture: bind-condition-after-create}} + input: {instructionRecordId: {recordCapture: instruction}, instructionId: 00000000-0000-4000-8000-000000000101, instructionVersion: 1, instructionDigest: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, institutionId: ministry-social, serviceId: cash-transfer, programmeId: cash-programme, cycleId: cycle-2026-11, beneficiaryId: beneficiary-001, beneficiaryDestination: "254700000002", fundingAccountId: programme-account, amountMinor: 100000, currency: KES, currencyScale: 2, payoutAttemptId: 00000000-0000-4000-8000-000000000201, providerBindingRevision: mifos-synthetic-v1} + expect: {outcome: refusal, status: 404, problemCode: resource.not_found} + + - id: changed-version-cannot-bind + action: bind-payout-attempt + accessProfile: payment-adapter-binder + claims: {principal: synthetic-payment-adapter, scopes: [registry:payout-attempt:bind], purpose: payment-processing, actorKind: service, requesterClient: payment-adapter} + request: + type: invoke + idempotencyKey: changed-version-bind + preconditions: {instructionRecordId: {conditionCapture: bind-condition-after-create}} + input: {instructionRecordId: {recordCapture: instruction}, instructionId: 00000000-0000-4000-8000-000000000101, instructionVersion: 2, instructionDigest: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, institutionId: ministry-social, serviceId: cash-transfer, programmeId: cash-programme, cycleId: cycle-2026-11, beneficiaryId: beneficiary-001, beneficiaryDestination: "254700000002", fundingAccountId: programme-account, amountMinor: 100000, currency: KES, currencyScale: 2, payoutAttemptId: 00000000-0000-4000-8000-000000000201, providerBindingRevision: mifos-synthetic-v1} + expect: {outcome: refusal, status: 412, problemCode: action.guard_failed} + + - id: changed-destination-cannot-bind + action: bind-payout-attempt + accessProfile: payment-adapter-binder + claims: {principal: synthetic-payment-adapter, scopes: [registry:payout-attempt:bind], purpose: payment-processing, actorKind: service, requesterClient: payment-adapter} + request: + type: invoke + idempotencyKey: changed-destination-bind + preconditions: {instructionRecordId: {conditionCapture: bind-condition-after-create}} + input: {instructionRecordId: {recordCapture: instruction}, instructionId: 00000000-0000-4000-8000-000000000101, instructionVersion: 1, instructionDigest: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, institutionId: ministry-social, serviceId: cash-transfer, programmeId: cash-programme, cycleId: cycle-2026-11, beneficiaryId: beneficiary-001, beneficiaryDestination: "254700000099", fundingAccountId: programme-account, amountMinor: 100000, currency: KES, currencyScale: 2, payoutAttemptId: 00000000-0000-4000-8000-000000000201, providerBindingRevision: mifos-synthetic-v1} + expect: {outcome: refusal, status: 412, problemCode: action.guard_failed} + + - id: changed-funding-or-money-cannot-bind + action: bind-payout-attempt + accessProfile: payment-adapter-binder + claims: {principal: synthetic-payment-adapter, scopes: [registry:payout-attempt:bind], purpose: payment-processing, actorKind: service, requesterClient: payment-adapter} + request: + type: invoke + idempotencyKey: changed-funding-bind + preconditions: {instructionRecordId: {conditionCapture: bind-condition-after-create}} + input: {instructionRecordId: {recordCapture: instruction}, instructionId: 00000000-0000-4000-8000-000000000101, instructionVersion: 1, instructionDigest: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, institutionId: ministry-social, serviceId: cash-transfer, programmeId: cash-programme, cycleId: cycle-2026-11, beneficiaryId: beneficiary-001, beneficiaryDestination: "254700000002", fundingAccountId: other-account, amountMinor: 100001, currency: KES, currencyScale: 2, payoutAttemptId: 00000000-0000-4000-8000-000000000201, providerBindingRevision: mifos-synthetic-v1} + expect: {outcome: refusal, status: 412, problemCode: action.guard_failed} + + - id: bind-exact-payout-attempt + action: bind-payout-attempt + accessProfile: payment-adapter-binder + claims: {principal: synthetic-payment-adapter, scopes: [registry:payout-attempt:bind], purpose: payment-processing, actorKind: service, requesterClient: payment-adapter} + request: + type: invoke + idempotencyKey: bind-exact-payout-attempt + preconditions: {instructionRecordId: {conditionCapture: bind-condition-after-create}} + input: {instructionRecordId: {recordCapture: instruction}, instructionId: 00000000-0000-4000-8000-000000000101, instructionVersion: 1, instructionDigest: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, institutionId: ministry-social, serviceId: cash-transfer, programmeId: cash-programme, cycleId: cycle-2026-11, beneficiaryId: beneficiary-001, beneficiaryDestination: "254700000002", fundingAccountId: programme-account, amountMinor: 100000, currency: KES, currencyScale: 2, payoutAttemptId: 00000000-0000-4000-8000-000000000201, providerBindingRevision: mifos-synthetic-v1} + expect: {outcome: success, status: 200} + + - id: recover-exact-binding + action: bind-payout-attempt + accessProfile: payment-adapter-binder + claims: {principal: synthetic-payment-adapter, scopes: [registry:payout-attempt:bind], purpose: payment-processing, actorKind: service, requesterClient: payment-adapter} + request: + type: invoke + idempotencyKey: bind-exact-payout-attempt + preconditions: {instructionRecordId: {conditionCapture: bind-condition-after-create}} + input: {instructionRecordId: {recordCapture: instruction}, instructionId: 00000000-0000-4000-8000-000000000101, instructionVersion: 1, instructionDigest: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, institutionId: ministry-social, serviceId: cash-transfer, programmeId: cash-programme, cycleId: cycle-2026-11, beneficiaryId: beneficiary-001, beneficiaryDestination: "254700000002", fundingAccountId: programme-account, amountMinor: 100000, currency: KES, currencyScale: 2, payoutAttemptId: 00000000-0000-4000-8000-000000000201, providerBindingRevision: mifos-synthetic-v1} + expect: {outcome: success, status: 200} + + - id: capture-bind-condition-after-binding + action: bind-payout-attempt + accessProfile: payment-adapter-binder + claims: {principal: synthetic-payment-adapter, scopes: [registry:payout-attempt:bind], purpose: payment-processing, actorKind: service, requesterClient: payment-adapter} + request: {type: target-conditions, input: {instructionRecordId: {recordCapture: instruction}}} + expect: {outcome: success, status: 200} + capture: bind-condition-after-binding + + - id: capture-confirm-condition-after-binding + action: record-provider-confirmation + accessProfile: payment-adapter-reporter + claims: {principal: synthetic-payment-adapter, scopes: [registry:payout-result:report], purpose: payment-processing, actorKind: service, requesterClient: payment-adapter} + request: {type: target-conditions, input: {instructionRecordId: {recordCapture: instruction}}} + expect: {outcome: success, status: 200} + capture: confirm-condition-after-binding + + - id: pending-or-unknown-cannot-create-second-attempt + action: bind-payout-attempt + accessProfile: payment-adapter-binder + claims: {principal: synthetic-payment-adapter, scopes: [registry:payout-attempt:bind], purpose: payment-processing, actorKind: service, requesterClient: payment-adapter} + request: + type: invoke + idempotencyKey: second-payout-attempt + preconditions: {instructionRecordId: {conditionCapture: bind-condition-after-binding}} + input: {instructionRecordId: {recordCapture: instruction}, instructionId: 00000000-0000-4000-8000-000000000101, instructionVersion: 1, instructionDigest: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, institutionId: ministry-social, serviceId: cash-transfer, programmeId: cash-programme, cycleId: cycle-2026-11, beneficiaryId: beneficiary-001, beneficiaryDestination: "254700000002", fundingAccountId: programme-account, amountMinor: 100000, currency: KES, currencyScale: 2, payoutAttemptId: 00000000-0000-4000-8000-000000000202, providerBindingRevision: mifos-synthetic-v1} + expect: {outcome: refusal, status: 412, problemCode: action.guard_failed} + + - id: pending-cannot-mark-provider-confirmed + action: record-provider-confirmation + accessProfile: payment-adapter-reporter + claims: {principal: synthetic-payment-adapter, scopes: [registry:payout-result:report], purpose: payment-processing, actorKind: service, requesterClient: payment-adapter} + request: + type: invoke + idempotencyKey: pending-result + preconditions: {instructionRecordId: {conditionCapture: confirm-condition-after-binding}} + input: {instructionRecordId: {recordCapture: instruction}, instructionId: 00000000-0000-4000-8000-000000000101, instructionVersion: 1, instructionDigest: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, institutionId: ministry-social, serviceId: cash-transfer, programmeId: cash-programme, cycleId: cycle-2026-11, beneficiaryId: beneficiary-001, beneficiaryDestination: "254700000002", fundingAccountId: programme-account, amountMinor: 100000, currency: KES, currencyScale: 2, payoutAttemptId: 00000000-0000-4000-8000-000000000201, providerBindingRevision: mifos-synthetic-v1, providerStatus: PENDING, providerReference: synthetic-batch-001, providerResultDigest: cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc} + expect: {outcome: refusal, status: 400, problemCode: request.invalid} + + - id: unknown-cannot-mark-provider-confirmed + action: record-provider-confirmation + accessProfile: payment-adapter-reporter + claims: {principal: synthetic-payment-adapter, scopes: [registry:payout-result:report], purpose: payment-processing, actorKind: service, requesterClient: payment-adapter} + request: + type: invoke + idempotencyKey: unknown-result + preconditions: {instructionRecordId: {conditionCapture: confirm-condition-after-binding}} + input: {instructionRecordId: {recordCapture: instruction}, instructionId: 00000000-0000-4000-8000-000000000101, instructionVersion: 1, instructionDigest: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, institutionId: ministry-social, serviceId: cash-transfer, programmeId: cash-programme, cycleId: cycle-2026-11, beneficiaryId: beneficiary-001, beneficiaryDestination: "254700000002", fundingAccountId: programme-account, amountMinor: 100000, currency: KES, currencyScale: 2, payoutAttemptId: 00000000-0000-4000-8000-000000000201, providerBindingRevision: mifos-synthetic-v1, providerStatus: UNKNOWN, providerReference: synthetic-batch-001, providerResultDigest: cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc} + expect: {outcome: refusal, status: 400, problemCode: request.invalid} + + - id: changed-instruction-fact-cannot-confirm + action: record-provider-confirmation + accessProfile: payment-adapter-reporter + claims: {principal: synthetic-payment-adapter, scopes: [registry:payout-result:report], purpose: payment-processing, actorKind: service, requesterClient: payment-adapter} + request: + type: invoke + idempotencyKey: changed-fact-confirmation + preconditions: {instructionRecordId: {conditionCapture: confirm-condition-after-binding}} + input: {instructionRecordId: {recordCapture: instruction}, instructionId: 00000000-0000-4000-8000-000000000101, instructionVersion: 1, instructionDigest: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, institutionId: ministry-social, serviceId: cash-transfer, programmeId: cash-programme, cycleId: cycle-2026-11, beneficiaryId: beneficiary-001, beneficiaryDestination: "254700000002", fundingAccountId: programme-account, amountMinor: 100001, currency: KES, currencyScale: 2, payoutAttemptId: 00000000-0000-4000-8000-000000000201, providerBindingRevision: mifos-synthetic-v1, providerStatus: COMPLETED, providerReference: synthetic-batch-001, providerResultDigest: cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc} + expect: {outcome: refusal, status: 412, problemCode: action.guard_failed} + + - id: unauthorized-service-cannot-confirm + action: record-provider-confirmation + accessProfile: payment-adapter-reporter + claims: {principal: synthetic-unauthorized-adapter, scopes: [], purpose: payment-processing, actorKind: service, requesterClient: payment-adapter} + request: + type: invoke + idempotencyKey: unauthorized-confirmation + preconditions: {instructionRecordId: {conditionCapture: confirm-condition-after-binding}} + input: {instructionRecordId: {recordCapture: instruction}, instructionId: 00000000-0000-4000-8000-000000000101, instructionVersion: 1, instructionDigest: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, institutionId: ministry-social, serviceId: cash-transfer, programmeId: cash-programme, cycleId: cycle-2026-11, beneficiaryId: beneficiary-001, beneficiaryDestination: "254700000002", fundingAccountId: programme-account, amountMinor: 100000, currency: KES, currencyScale: 2, payoutAttemptId: 00000000-0000-4000-8000-000000000201, providerBindingRevision: mifos-synthetic-v1, providerStatus: COMPLETED, providerReference: synthetic-batch-001, providerResultDigest: cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc} + expect: {outcome: refusal, status: 404, problemCode: resource.not_found} + + - id: record-exact-provider-confirmation + action: record-provider-confirmation + accessProfile: payment-adapter-reporter + claims: {principal: synthetic-payment-adapter, scopes: [registry:payout-result:report], purpose: payment-processing, actorKind: service, requesterClient: payment-adapter} + request: + type: invoke + idempotencyKey: record-exact-provider-confirmation + preconditions: {instructionRecordId: {conditionCapture: confirm-condition-after-binding}} + input: {instructionRecordId: {recordCapture: instruction}, instructionId: 00000000-0000-4000-8000-000000000101, instructionVersion: 1, instructionDigest: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, institutionId: ministry-social, serviceId: cash-transfer, programmeId: cash-programme, cycleId: cycle-2026-11, beneficiaryId: beneficiary-001, beneficiaryDestination: "254700000002", fundingAccountId: programme-account, amountMinor: 100000, currency: KES, currencyScale: 2, payoutAttemptId: 00000000-0000-4000-8000-000000000201, providerBindingRevision: mifos-synthetic-v1, providerStatus: COMPLETED, providerReference: synthetic-batch-001, providerResultDigest: cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc} + expect: {outcome: success, status: 200} + + - id: read-exact-provider-confirmation + recordType: disbursement-instruction + accessProfile: payment-adapter-reporter + claims: {principal: synthetic-payment-adapter, scopes: [registry:payout-result:report], purpose: payment-processing, actorKind: service, requesterClient: payment-adapter} + request: {type: get, recordCapture: instruction} + expect: + outcome: success + status: 200 + fields: {instructionId: 00000000-0000-4000-8000-000000000101, instructionVersion: 1, instructionDigest: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, institutionId: ministry-social, serviceId: cash-transfer, programmeId: cash-programme, cycleId: cycle-2026-11, beneficiaryId: beneficiary-001, beneficiaryDestination: "254700000002", fundingAccountId: programme-account, amountMinor: 100000, currency: KES, currencyScale: 2, disbursementState: provider-confirmed, payoutAttemptId: 00000000-0000-4000-8000-000000000201, providerBindingRevision: mifos-synthetic-v1, providerStatus: COMPLETED, providerReference: synthetic-batch-001, providerResultDigest: cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc} + + - id: capture-confirm-condition-after-confirmation + action: record-provider-confirmation + accessProfile: payment-adapter-reporter + claims: {principal: synthetic-payment-adapter, scopes: [registry:payout-result:report], purpose: payment-processing, actorKind: service, requesterClient: payment-adapter} + request: {type: target-conditions, input: {instructionRecordId: {recordCapture: instruction}}} + expect: {outcome: success, status: 200} + capture: confirm-condition-after-confirmation + + - id: confirmation-cannot-be-replaced + action: record-provider-confirmation + accessProfile: payment-adapter-reporter + claims: {principal: synthetic-payment-adapter, scopes: [registry:payout-result:report], purpose: payment-processing, actorKind: service, requesterClient: payment-adapter} + request: + type: invoke + idempotencyKey: replacement-confirmation + preconditions: {instructionRecordId: {conditionCapture: confirm-condition-after-confirmation}} + input: {instructionRecordId: {recordCapture: instruction}, instructionId: 00000000-0000-4000-8000-000000000101, instructionVersion: 1, instructionDigest: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, institutionId: ministry-social, serviceId: cash-transfer, programmeId: cash-programme, cycleId: cycle-2026-11, beneficiaryId: beneficiary-001, beneficiaryDestination: "254700000002", fundingAccountId: programme-account, amountMinor: 100000, currency: KES, currencyScale: 2, payoutAttemptId: 00000000-0000-4000-8000-000000000201, providerBindingRevision: mifos-synthetic-v1, providerStatus: COMPLETED, providerReference: synthetic-batch-002, providerResultDigest: dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd} + expect: {outcome: refusal, status: 412, problemCode: action.guard_failed} diff --git a/products/coordinator/CHANGELOG.md b/products/coordinator/CHANGELOG.md index 853b7b41ba..2754252143 100644 --- a/products/coordinator/CHANGELOG.md +++ b/products/coordinator/CHANGELOG.md @@ -104,6 +104,14 @@ every read to the accepted bill and binding, and settles the collection attempt only on confirmed or failed state. Only Adapter-verified confirmed state can produce a registry receipt. +- Add native G2P disbursement operations: submit one approved immutable + instruction, observe its typed provider state, and report a verified + provider confirmation under a separate same-command key. An uncertain + submission stays held and permits only read-only original-command + reconciliation, never a fresh provider send. The host-owned `disbursement` + completion keeps accepted, pending, and unknown states waiting, correlates + every read to the accepted instruction and binding, and settles only on + provider-confirmed or failed state. ## 0.46.0 - 2026-11-08 diff --git a/products/coordinator/examples/g2p-disbursements/README.md b/products/coordinator/examples/g2p-disbursements/README.md new file mode 100644 index 0000000000..1d12f60daf --- /dev/null +++ b/products/coordinator/examples/g2p-disbursements/README.md @@ -0,0 +1,55 @@ +# G2P disbursement project + +This project accepts one approved instruction record identity, asks the bound +Adapter payment connection to submit it, waits for the named `disbursement` +completion, and reports an exact provider confirmation back to the owning +instruction registry. Coordinator never receives the amount, recipient +destination, funding account, provider request, or provider evidence. + +The three outcomes are deliberately narrow: + +- `confirmation-recorded` returns the Adapter's exact `ProviderConfirmation`. + It means the pinned provider reported completion and the owning instruction + was updated. It does not claim end-recipient credit or final settlement. +- `disbursement-failed` returns the verified failed provider observation. It + does not report a confirmation or authorize a replacement submission. +- `disbursement-unresolved` has no output. A wait timeout, or an accepted, + pending, or unknown observation, does not prove failure and must not start a + new disbursement. + +An uncertain `request-disbursement` is held and cannot use `retry-same`. +Reconcile it only through the Adapter's read-only lookup for the exact saved +instruction and key. An uncertain `record-provider-confirmation` may use +`retry-same`, which resends only the saved reporting command under its saved +key. Neither recovery path permits a fresh provider submission. + +## Check and package + +From the repository root, use binaries built from this checkout: + +```sh +coordinatorctl check --project products/coordinator/examples/g2p-disbursements --explain +coordinatorctl test --project products/coordinator/examples/g2p-disbursements +coordinatorctl package \ + --project products/coordinator/examples/g2p-disbursements \ + --output /absolute/private/g2p-disbursements-package +``` + +Copy `runtime.yaml` outside the package. Replace its package root and digest, +database URLs, PostgreSQL role, issuer, JWKS source, Adapter and token +endpoints, listener, secret root, and audit path. The payment connection must +select an Adapter connection whose own policy resolves the approved +instruction and provider binding. Give Coordinator only the Adapter payment +capability. Keep instruction-read and provider-reporting grants with the +Adapter reporter identity. + +Start a run with `input.example.json` after replacing the synthetic UUID and +version with the exact immutable instruction record. Use a unique admission +key and the currently reported `workflowRevision`. Status belongs to the +admitting caller; inspection and recovery use the separately authorized +operator identity. + +After a terminal run, accept only named outcome `confirmation-recorded` and +verify its instruction record ID, instruction ID and version, disbursement ID, +binding revision, exact money, provider reference, simulation marker, and +provider-result digest before any downstream service proceeds. diff --git a/products/coordinator/examples/g2p-disbursements/input.example.json b/products/coordinator/examples/g2p-disbursements/input.example.json new file mode 100644 index 0000000000..5455683b07 --- /dev/null +++ b/products/coordinator/examples/g2p-disbursements/input.example.json @@ -0,0 +1,4 @@ +{ + "instructionRecordId": "00000000-0000-4000-8000-000000000101", + "instructionVersion": 1 +} diff --git a/products/coordinator/examples/g2p-disbursements/runtime.yaml b/products/coordinator/examples/g2p-disbursements/runtime.yaml new file mode 100644 index 0000000000..a33772a670 --- /dev/null +++ b/products/coordinator/examples/g2p-disbursements/runtime.yaml @@ -0,0 +1,57 @@ +# yaml-language-server: $schema=https://id.registrystack.org/schemas/coordinator/runtime/runtime.v1alpha1.schema.json +apiVersion: id.registrystack.org/formats/coordinator/runtime/v1alpha1 +kind: CoordinatorRuntimeConfig +secretProviders: + environment: {} + file: + root: /run/registry-coordinator/secrets +database: + runtimeUrlRef: secret:env/COORDINATOR_DATABASE_URL + migrationUrlRef: secret:env/COORDINATOR_MIGRATION_URL +namespace: coordinator_g2p_disbursements +connections: + g2p-payments: + type: payments + baseUrl: http://127.0.0.1:8098 + paymentConnection: g2p-disbursements + authorization: + tokenEndpoint: http://127.0.0.1:8090/token + clientAssertionAudience: http://127.0.0.1:8090 + clientId: coordinator-g2p + signingKeyRef: secret:file/coordinator-g2p-jwk + resource: urn:registry:payment-adapter + scopes: ['payments:disburse'] + resultCheckSeconds: 60 +deployment: + databaseId: coordinator-institution-g2p-disbursements + runtimeRole: coordinator_runtime + packages: + - root: /opt/registry-coordinator/g2p-disbursements-package + expectedDigest: sha256:0000000000000000000000000000000000000000000000000000000000000000 + listener: + bind: 127.0.0.1:8108 + tlsTermination: operator-controlled-upstream + authentication: + issuer: https://issuer.example.org + audience: urn:example:coordinator + jwksSource: {type: discovery} + scopeClaim: scope + policies: + benefits-service: + subjects: [benefits-service] + requiredScopes: ['coordinator:start'] + workflows: [g2p-disbursements] + actions: [start, status] + payment-operator: + subjects: [payment-operator] + requiredScopes: ['coordinator:operate'] + workflows: [g2p-disbursements] + actions: [status, inspect, retry-same, cancel, reconcile] + operator: true + auditFile: /var/lib/registry-coordinator/g2p-disbursements-audit.jsonl + auditKeyRef: secret:file/audit-key + activeStateKey: 1 + stateKeys: + '1': + keyRef: secret:file/state-key-1 + admissionKeyRef: secret:file/admission-key diff --git a/products/coordinator/examples/g2p-disbursements/scenarios.yaml b/products/coordinator/examples/g2p-disbursements/scenarios.yaml new file mode 100644 index 0000000000..6bc9b7352b --- /dev/null +++ b/products/coordinator/examples/g2p-disbursements/scenarios.yaml @@ -0,0 +1,252 @@ +# yaml-language-server: $schema=https://id.registrystack.org/schemas/coordinator/scenarios/scenarios.v1alpha1.schema.json +apiVersion: id.registrystack.org/formats/coordinator/scenarios/v1alpha1 +kind: CoordinatorScenarios +cases: +- id: provider-confirmed-disbursement-records-confirmation + admittedAt: '2026-11-12T00:00:00Z' + input: + instructionRecordId: 00000000-0000-4000-8000-000000000101 + instructionVersion: 1 + replies: + request-disbursement: + - type: success + value: + disbursementId: 00000000-0000-4000-8000-000000000201 + instructionRecordId: 00000000-0000-4000-8000-000000000101 + instructionId: 00000000-0000-4000-8000-000000000301 + instructionVersion: 1 + bindingRevision: sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa + simulation: true + record-provider-confirmation: + - type: success + value: + disbursementId: 00000000-0000-4000-8000-000000000201 + instructionRecordId: 00000000-0000-4000-8000-000000000101 + instructionId: 00000000-0000-4000-8000-000000000301 + instructionVersion: 1 + bindingRevision: sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa + simulation: true + money: {value: '125.00', currency: USD, scale: 2} + providerReference: MIFOS-G2P-001 + providerResultDigest: bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb + waits: + await-disbursement: + type: event + value: + disbursementId: 00000000-0000-4000-8000-000000000201 + instructionRecordId: 00000000-0000-4000-8000-000000000101 + instructionId: 00000000-0000-4000-8000-000000000301 + instructionVersion: 1 + bindingRevision: sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa + simulation: true + state: provider-confirmed + money: {value: '125.00', currency: USD, scale: 2} + providerReference: MIFOS-G2P-001 + expect: + path: [request-disbursement, await-disbursement, route-disbursement, record-provider-confirmation, confirmation-recorded] + state: completed + outcome: {type: named, value: confirmation-recorded} + output: + disbursementId: 00000000-0000-4000-8000-000000000201 + instructionRecordId: 00000000-0000-4000-8000-000000000101 + instructionId: 00000000-0000-4000-8000-000000000301 + instructionVersion: 1 + bindingRevision: sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa + simulation: true + money: {value: '125.00', currency: USD, scale: 2} + providerReference: MIFOS-G2P-001 + providerResultDigest: bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb +- id: failed-disbursement-does-not-record-confirmation + admittedAt: '2026-11-12T00:00:00Z' + input: + instructionRecordId: 00000000-0000-4000-8000-000000000101 + instructionVersion: 1 + replies: + request-disbursement: + - type: success + value: + disbursementId: 00000000-0000-4000-8000-000000000201 + instructionRecordId: 00000000-0000-4000-8000-000000000101 + instructionId: 00000000-0000-4000-8000-000000000301 + instructionVersion: 1 + bindingRevision: sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa + simulation: true + waits: + await-disbursement: + type: event + value: + disbursementId: 00000000-0000-4000-8000-000000000201 + instructionRecordId: 00000000-0000-4000-8000-000000000101 + instructionId: 00000000-0000-4000-8000-000000000301 + instructionVersion: 1 + bindingRevision: sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa + simulation: true + state: failed + money: {value: '125.00', currency: USD, scale: 2} + failureReason: provider-rejected + expect: + path: [request-disbursement, await-disbursement, route-disbursement, disbursement-failed] + state: completed + outcome: {type: named, value: disbursement-failed} + output: + disbursementId: 00000000-0000-4000-8000-000000000201 + instructionRecordId: 00000000-0000-4000-8000-000000000101 + instructionId: 00000000-0000-4000-8000-000000000301 + instructionVersion: 1 + bindingRevision: sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa + simulation: true + state: failed + money: {value: '125.00', currency: USD, scale: 2} + failureReason: provider-rejected +- id: pending-until-timeout-remains-unresolved + admittedAt: '2026-11-12T00:00:00Z' + input: + instructionRecordId: 00000000-0000-4000-8000-000000000101 + instructionVersion: 1 + replies: + request-disbursement: + - type: success + value: + disbursementId: 00000000-0000-4000-8000-000000000201 + instructionRecordId: 00000000-0000-4000-8000-000000000101 + instructionId: 00000000-0000-4000-8000-000000000301 + instructionVersion: 1 + bindingRevision: sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa + simulation: true + waits: + await-disbursement: {type: timeout} + expect: + path: [request-disbursement, await-disbursement, disbursement-unresolved] + state: completed + outcome: {type: named, value: disbursement-unresolved} + output: null + workflowElapsedSeconds: 3600 +- id: uncertain-submit-is-held-without-a-fresh-send + admittedAt: '2026-11-12T00:00:00Z' + input: + instructionRecordId: 00000000-0000-4000-8000-000000000101 + instructionVersion: 1 + replies: + request-disbursement: + - type: uncertain + code: payment-outcome-unknown + expect: + path: [request-disbursement] + state: uncertain + outcome: {type: none} +- id: read-only-reconciliation-recovers-original-acceptance + admittedAt: '2026-11-12T00:00:00Z' + input: + instructionRecordId: 00000000-0000-4000-8000-000000000101 + instructionVersion: 1 + replies: + request-disbursement: + - type: uncertain + code: payment-provider-protocol + - type: success + value: + disbursementId: 00000000-0000-4000-8000-000000000201 + instructionRecordId: 00000000-0000-4000-8000-000000000101 + instructionId: 00000000-0000-4000-8000-000000000301 + instructionVersion: 1 + bindingRevision: sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa + simulation: true + record-provider-confirmation: + - type: success + value: + disbursementId: 00000000-0000-4000-8000-000000000201 + instructionRecordId: 00000000-0000-4000-8000-000000000101 + instructionId: 00000000-0000-4000-8000-000000000301 + instructionVersion: 1 + bindingRevision: sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa + simulation: true + money: {value: '125.00', currency: USD, scale: 2} + providerReference: MIFOS-G2P-001 + providerResultDigest: bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb + recovery: + request-disbursement: reconcile + waits: + await-disbursement: + type: event + value: + disbursementId: 00000000-0000-4000-8000-000000000201 + instructionRecordId: 00000000-0000-4000-8000-000000000101 + instructionId: 00000000-0000-4000-8000-000000000301 + instructionVersion: 1 + bindingRevision: sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa + simulation: true + state: provider-confirmed + money: {value: '125.00', currency: USD, scale: 2} + providerReference: MIFOS-G2P-001 + expect: + path: [request-disbursement, await-disbursement, route-disbursement, record-provider-confirmation, confirmation-recorded] + state: completed + outcome: {type: named, value: confirmation-recorded} + output: + disbursementId: 00000000-0000-4000-8000-000000000201 + instructionRecordId: 00000000-0000-4000-8000-000000000101 + instructionId: 00000000-0000-4000-8000-000000000301 + instructionVersion: 1 + bindingRevision: sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa + simulation: true + money: {value: '125.00', currency: USD, scale: 2} + providerReference: MIFOS-G2P-001 + providerResultDigest: bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb +- id: confirmation-report-retries-the-same-command + admittedAt: '2026-11-12T00:00:00Z' + input: + instructionRecordId: 00000000-0000-4000-8000-000000000101 + instructionVersion: 1 + replies: + request-disbursement: + - type: success + value: + disbursementId: 00000000-0000-4000-8000-000000000201 + instructionRecordId: 00000000-0000-4000-8000-000000000101 + instructionId: 00000000-0000-4000-8000-000000000301 + instructionVersion: 1 + bindingRevision: sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa + simulation: true + record-provider-confirmation: + - type: uncertain + code: payment-outcome-unknown + - type: success + value: + disbursementId: 00000000-0000-4000-8000-000000000201 + instructionRecordId: 00000000-0000-4000-8000-000000000101 + instructionId: 00000000-0000-4000-8000-000000000301 + instructionVersion: 1 + bindingRevision: sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa + simulation: true + money: {value: '125.00', currency: USD, scale: 2} + providerReference: MIFOS-G2P-001 + providerResultDigest: bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb + recovery: + record-provider-confirmation: retry-same + waits: + await-disbursement: + type: event + value: + disbursementId: 00000000-0000-4000-8000-000000000201 + instructionRecordId: 00000000-0000-4000-8000-000000000101 + instructionId: 00000000-0000-4000-8000-000000000301 + instructionVersion: 1 + bindingRevision: sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa + simulation: true + state: provider-confirmed + money: {value: '125.00', currency: USD, scale: 2} + providerReference: MIFOS-G2P-001 + expect: + path: [request-disbursement, await-disbursement, route-disbursement, record-provider-confirmation, confirmation-recorded] + state: completed + outcome: {type: named, value: confirmation-recorded} + output: + disbursementId: 00000000-0000-4000-8000-000000000201 + instructionRecordId: 00000000-0000-4000-8000-000000000101 + instructionId: 00000000-0000-4000-8000-000000000301 + instructionVersion: 1 + bindingRevision: sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa + simulation: true + money: {value: '125.00', currency: USD, scale: 2} + providerReference: MIFOS-G2P-001 + providerResultDigest: bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb diff --git a/products/coordinator/examples/g2p-disbursements/workflow.yaml b/products/coordinator/examples/g2p-disbursements/workflow.yaml new file mode 100644 index 0000000000..a487c8b81d --- /dev/null +++ b/products/coordinator/examples/g2p-disbursements/workflow.yaml @@ -0,0 +1,70 @@ +# yaml-language-server: $schema=https://id.registrystack.org/schemas/coordinator/project/project.v1alpha1.schema.json +apiVersion: id.registrystack.org/formats/coordinator/project/v1alpha1 +kind: CoordinatorProject +project: + id: g2p-disbursements + version: '1' +operations: + request-disbursement: + uses: payments.request-disbursement/v1 + connection: g2p-payments + record-provider-confirmation: + uses: payments.record-provider-confirmation/v1 + connection: g2p-payments +workflow: + input: + operationInput: request-disbursement + deadlineSeconds: 7200 + start: request-disbursement + steps: + request-disbursement: + type: call + operation: request-disbursement + input: {type: input} + next: await-disbursement + await-disbursement: + type: wait-for + completion: {step: request-disbursement, name: disbursement} + timeoutSeconds: 3600 + next: route-disbursement + onTimeout: disbursement-unresolved + route-disbursement: + type: choose + choose: + type: step + step: await-disbursement + path: /state + cases: + accepted: disbursement-unresolved + pending: disbursement-unresolved + provider-confirmed: record-provider-confirmation + failed: disbursement-failed + unknown: disbursement-unresolved + record-provider-confirmation: + type: call + operation: record-provider-confirmation + input: + type: fields + fields: + disbursementId: + type: step + step: await-disbursement + path: /disbursementId + next: confirmation-recorded + confirmation-recorded: + type: finish + outcome: confirmation-recorded + output: {type: step, step: record-provider-confirmation} + disbursement-failed: + type: finish + outcome: disbursement-failed + output: {type: step, step: await-disbursement} + disbursement-unresolved: + type: finish + outcome: disbursement-unresolved + outcomes: + confirmation-recorded: + operationOutput: record-provider-confirmation + disbursement-failed: + completionOutput: {operation: request-disbursement, name: disbursement} + disbursement-unresolved: {type: 'null'} diff --git a/products/coordinator/generated/openapi/coordinator.openapi.json b/products/coordinator/generated/openapi/coordinator.openapi.json index fe8cf4e684..672b07189f 100644 --- a/products/coordinator/generated/openapi/coordinator.openapi.json +++ b/products/coordinator/generated/openapi/coordinator.openapi.json @@ -464,7 +464,10 @@ "breg.read-record/v2", "payments.request-collection/v1", "payments.read-collection/v1", - "payments.record-receipt/v1" + "payments.record-receipt/v1", + "payments.request-disbursement/v1", + "payments.read-disbursement/v1", + "payments.record-provider-confirmation/v1" ], "type": "string" }, diff --git a/products/coordinator/generated/operations/README.md b/products/coordinator/generated/operations/README.md index cb372f50b6..1c1b11eec2 100644 --- a/products/coordinator/generated/operations/README.md +++ b/products/coordinator/generated/operations/README.md @@ -33,6 +33,9 @@ Each catalog operation has an input contract, the type its adapter decodes, and | [`payments.request-collection/v1`](#payments.request-collection/v1) | 1 | `payments` | mutation | required | none | same-command-and-receipt | read | none | | [`payments.read-collection/v1`](#payments.read-collection/v1) | 1 | `payments` | read | none | none | read-again | none | none | | [`payments.record-receipt/v1`](#payments.record-receipt/v1) | 1 | `payments` | mutation | required | none | same-command | none | none | +| [`payments.request-disbursement/v1`](#payments.request-disbursement/v1) | 1 | `payments` | mutation | required | none | hold-after-dispatch | read | none | +| [`payments.read-disbursement/v1`](#payments.read-disbursement/v1) | 1 | `payments` | read | none | none | read-again | none | none | +| [`payments.record-provider-confirmation/v1`](#payments.record-provider-confirmation/v1) | 1 | `payments` | mutation | required | none | same-command | none | none | ## breg.read-record/v1 @@ -2086,6 +2089,269 @@ Output ([`payments.record-receipt.v1.output.schema.json`](payments.record-receip No other members are accepted. +## payments.request-disbursement/v1 + +Host execution and completion contract: + +```json +{ + "authority": "current-bound-connection-authority", + "completionObservation": { + "acceptedBinding": [ + "disbursementId", + "instructionRecordId", + "instructionId", + "instructionVersion", + "bindingRevision", + "simulation" + ], + "authenticatedWake": false, + "authority": "current-bound-payment-connection", + "deadline": "original-wait-timeout-within-original-run-deadline", + "defaultIntervalSeconds": 900, + "maximumRetryAfterSeconds": 86400, + "minimumIntervalSeconds": 30, + "name": "disbursement", + "observationLimit": "1 + ceil(waitDurationSeconds / effectiveIntervalSeconds)", + "paymentSuccessState": "provider-confirmed", + "pendingStates": [ + "accepted", + "pending", + "unknown" + ], + "profile": "payment-disbursement", + "settledStates": [ + "provider-confirmed", + "failed" + ], + "signalCarriesResult": false, + "terminalEvidence": "validated-authoritative-disbursement-read" + }, + "connectionInterface": "payments", + "identity": { + "effect": "mutation", + "id": "payments.request-disbursement/v1", + "keyRequirement": "required", + "product": "payments", + "readReceipt": true, + "recovery": "hold-after-dispatch", + "requiresPreparation": false, + "version": 1 + }, + "limits": { + "attemptTimeoutSeconds": 10, + "http": { + "attemptTimeoutMilliseconds": 2000, + "connectTimeoutMilliseconds": 1000, + "maximumMutationRetries": 0, + "maximumResponseBytes": 65536 + }, + "maximumCallAttempts": 10, + "maximumCallRetryDelaySeconds": 300, + "maximumConcurrentAttemptsPerRun": 1, + "maximumPreparationBytes": 65536, + "maximumRunDurationSeconds": 31536000, + "value": { + "maximumArrayItems": 256, + "maximumBytes": 131072, + "maximumDepth": 32, + "maximumNodes": 4096, + "maximumObjectMembers": 256, + "maximumStringBytes": 16384 + } + } +} +``` + +Input ([`payments.request-disbursement.v1.input.schema.json`](payments.request-disbursement.v1.input.schema.json)): + +| Member | Type | Required | +|---|---|---| +| `instructionRecordId` | string (uuid) | yes | +| `instructionVersion` | integer | yes | + +No other members are accepted. + +Output ([`payments.request-disbursement.v1.output.schema.json`](payments.request-disbursement.v1.output.schema.json)): + +| Member | Type | Required | +|---|---|---| +| `bindingRevision` | string | yes | +| `disbursementId` | string (uuid) | yes | +| `instructionId` | string (uuid) | yes | +| `instructionRecordId` | string (uuid) | yes | +| `instructionVersion` | integer | yes | +| `simulation` | boolean | yes | + +No other members are accepted. + +## payments.read-disbursement/v1 + +Host execution and completion contract: + +```json +{ + "authority": "current-bound-connection-authority", + "completionObservation": { + "acceptedBinding": [ + "disbursementId", + "instructionRecordId", + "instructionId", + "instructionVersion", + "bindingRevision", + "simulation" + ], + "authenticatedWake": false, + "authority": "current-bound-payment-connection", + "deadline": "original-wait-timeout-within-original-run-deadline", + "defaultIntervalSeconds": 900, + "maximumRetryAfterSeconds": 86400, + "minimumIntervalSeconds": 30, + "name": "disbursement", + "observationLimit": "1 + ceil(waitDurationSeconds / effectiveIntervalSeconds)", + "paymentSuccessState": "provider-confirmed", + "pendingStates": [ + "accepted", + "pending", + "unknown" + ], + "profile": "payment-disbursement", + "settledStates": [ + "provider-confirmed", + "failed" + ], + "signalCarriesResult": false, + "terminalEvidence": "validated-authoritative-disbursement-read" + }, + "connectionInterface": "payments", + "identity": { + "effect": "read", + "id": "payments.read-disbursement/v1", + "keyRequirement": "none", + "product": "payments", + "readReceipt": false, + "recovery": "read-again", + "requiresPreparation": false, + "version": 1 + }, + "limits": { + "attemptTimeoutSeconds": 10, + "http": { + "attemptTimeoutMilliseconds": 2000, + "connectTimeoutMilliseconds": 1000, + "maximumMutationRetries": 0, + "maximumResponseBytes": 65536 + }, + "maximumCallAttempts": 10, + "maximumCallRetryDelaySeconds": 300, + "maximumConcurrentAttemptsPerRun": 1, + "maximumPreparationBytes": 65536, + "maximumRunDurationSeconds": 31536000, + "value": { + "maximumArrayItems": 256, + "maximumBytes": 131072, + "maximumDepth": 32, + "maximumNodes": 4096, + "maximumObjectMembers": 256, + "maximumStringBytes": 16384 + } + } +} +``` + +Input ([`payments.read-disbursement.v1.input.schema.json`](payments.read-disbursement.v1.input.schema.json)): + +| Member | Type | Required | +|---|---|---| +| `disbursementId` | string (uuid) | yes | + +No other members are accepted. + +Output ([`payments.read-disbursement.v1.output.schema.json`](payments.read-disbursement.v1.output.schema.json)): + +| Member | Type | Required | +|---|---|---| +| `bindingRevision` | string | yes | +| `disbursementId` | string (uuid) | yes | +| `failureReason` | string or null | no | +| `instructionId` | string (uuid) | yes | +| `instructionRecordId` | string (uuid) | yes | +| `instructionVersion` | integer | yes | +| `money` | `Money` | yes | +| `providerReference` | string or null | no | +| `simulation` | boolean | yes | +| `state` | `DisbursementState` | yes | + +No other members are accepted. + +## payments.record-provider-confirmation/v1 + +Host execution and completion contract: + +```json +{ + "authority": "current-bound-connection-authority", + "completionObservation": null, + "connectionInterface": "payments", + "identity": { + "effect": "mutation", + "id": "payments.record-provider-confirmation/v1", + "keyRequirement": "required", + "product": "payments", + "readReceipt": false, + "recovery": "same-command", + "requiresPreparation": false, + "version": 1 + }, + "limits": { + "attemptTimeoutSeconds": 10, + "http": { + "attemptTimeoutMilliseconds": 2000, + "connectTimeoutMilliseconds": 1000, + "maximumMutationRetries": 0, + "maximumResponseBytes": 65536 + }, + "maximumCallAttempts": 10, + "maximumCallRetryDelaySeconds": 300, + "maximumConcurrentAttemptsPerRun": 1, + "maximumPreparationBytes": 65536, + "maximumRunDurationSeconds": 31536000, + "value": { + "maximumArrayItems": 256, + "maximumBytes": 131072, + "maximumDepth": 32, + "maximumNodes": 4096, + "maximumObjectMembers": 256, + "maximumStringBytes": 16384 + } + } +} +``` + +Input ([`payments.record-provider-confirmation.v1.input.schema.json`](payments.record-provider-confirmation.v1.input.schema.json)): + +| Member | Type | Required | +|---|---|---| +| `disbursementId` | string (uuid) | yes | + +No other members are accepted. + +Output ([`payments.record-provider-confirmation.v1.output.schema.json`](payments.record-provider-confirmation.v1.output.schema.json)): + +| Member | Type | Required | +|---|---|---| +| `bindingRevision` | string | yes | +| `disbursementId` | string (uuid) | yes | +| `instructionId` | string (uuid) | yes | +| `instructionRecordId` | string (uuid) | yes | +| `instructionVersion` | integer | yes | +| `money` | `Money` | yes | +| `providerReference` | string | yes | +| `providerResultDigest` | string | yes | +| `simulation` | boolean | yes | + +No other members are accepted. + ## Completions A `wait-for` step observes a named completion on an accepted Operation. The host reads the authoritative result under current connection authority, using the saved command and exact correlation. A terminal result continues through `next` as the step output. A step reached by `onTimeout` has no completion output. Authenticated signals only wake an eligible read and never carry the result. Durable read spacing, the observation budget and the original deadline survive retries and restarts. diff --git a/products/coordinator/generated/operations/catalog.json b/products/coordinator/generated/operations/catalog.json index 5420c6ffd3..b373c6c92d 100644 --- a/products/coordinator/generated/operations/catalog.json +++ b/products/coordinator/generated/operations/catalog.json @@ -2834,6 +2834,357 @@ "type": "object" } }, + "payments.read-disbursement/v1": { + "host": { + "authority": "current-bound-connection-authority", + "completionObservation": { + "acceptedBinding": [ + "disbursementId", + "instructionRecordId", + "instructionId", + "instructionVersion", + "bindingRevision", + "simulation" + ], + "authenticatedWake": false, + "authority": "current-bound-payment-connection", + "deadline": "original-wait-timeout-within-original-run-deadline", + "defaultIntervalSeconds": 900, + "maximumRetryAfterSeconds": 86400, + "minimumIntervalSeconds": 30, + "name": "disbursement", + "observationLimit": "1 + ceil(waitDurationSeconds / effectiveIntervalSeconds)", + "paymentSuccessState": "provider-confirmed", + "pendingStates": [ + "accepted", + "pending", + "unknown" + ], + "profile": "payment-disbursement", + "settledStates": [ + "provider-confirmed", + "failed" + ], + "signalCarriesResult": false, + "terminalEvidence": "validated-authoritative-disbursement-read" + }, + "connectionInterface": "payments", + "identity": { + "effect": "read", + "id": "payments.read-disbursement/v1", + "keyRequirement": "none", + "product": "payments", + "readReceipt": false, + "recovery": "read-again", + "requiresPreparation": false, + "version": 1 + }, + "limits": { + "attemptTimeoutSeconds": 10, + "http": { + "attemptTimeoutMilliseconds": 2000, + "connectTimeoutMilliseconds": 1000, + "maximumMutationRetries": 0, + "maximumResponseBytes": 65536 + }, + "maximumCallAttempts": 10, + "maximumCallRetryDelaySeconds": 300, + "maximumConcurrentAttemptsPerRun": 1, + "maximumPreparationBytes": 65536, + "maximumRunDurationSeconds": 31536000, + "value": { + "maximumArrayItems": 256, + "maximumBytes": 131072, + "maximumDepth": 32, + "maximumNodes": 4096, + "maximumObjectMembers": 256, + "maximumStringBytes": 16384 + } + } + }, + "input": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "description": "Read one saved disbursement and its current provider observation.", + "properties": { + "disbursementId": { + "format": "uuid", + "not": { + "const": "00000000-0000-0000-0000-000000000000" + }, + "type": "string" + } + }, + "required": [ + "disbursementId" + ], + "title": "payments.read-disbursement/v1 input", + "type": "object" + }, + "output": { + "$defs": { + "DisbursementState": { + "description": "Only provider-confirmed means the pinned provider reported completion.\nIt does not by itself claim end-recipient credit or settlement.", + "enum": [ + "accepted", + "pending", + "provider-confirmed", + "failed", + "unknown" + ], + "type": "string" + }, + "Money": { + "additionalProperties": false, + "description": "An exact positive decimal amount. Scale belongs to the configured currency\npolicy; wire amounts are strings so no binary floating-point rounding occurs.", + "properties": { + "currency": { + "pattern": "^[A-Z]{3}$", + "type": "string" + }, + "scale": { + "maximum": 6, + "minimum": 0, + "type": "integer" + }, + "value": { + "maxLength": 24, + "minLength": 1, + "not": { + "pattern": "^0(\\.0{1,6})?$" + }, + "pattern": "^(0|[1-9][0-9]*)(\\.[0-9]{1,6})?$", + "type": "string" + } + }, + "required": [ + "value", + "currency", + "scale" + ], + "type": "object" + } + }, + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "description": "A bounded observation of one saved disbursement instruction.", + "properties": { + "bindingRevision": { + "type": "string" + }, + "disbursementId": { + "format": "uuid", + "not": { + "const": "00000000-0000-0000-0000-000000000000" + }, + "type": "string" + }, + "failureReason": { + "type": [ + "string", + "null" + ] + }, + "instructionId": { + "format": "uuid", + "not": { + "const": "00000000-0000-0000-0000-000000000000" + }, + "type": "string" + }, + "instructionRecordId": { + "format": "uuid", + "not": { + "const": "00000000-0000-0000-0000-000000000000" + }, + "type": "string" + }, + "instructionVersion": { + "maximum": 9007199254740991, + "minimum": 1, + "type": "integer" + }, + "money": { + "$ref": "#/$defs/Money" + }, + "providerReference": { + "type": [ + "string", + "null" + ] + }, + "simulation": { + "type": "boolean" + }, + "state": { + "$ref": "#/$defs/DisbursementState" + } + }, + "required": [ + "disbursementId", + "instructionRecordId", + "instructionId", + "instructionVersion", + "bindingRevision", + "simulation", + "state", + "money" + ], + "title": "payments.read-disbursement/v1 output", + "type": "object" + } + }, + "payments.record-provider-confirmation/v1": { + "host": { + "authority": "current-bound-connection-authority", + "completionObservation": null, + "connectionInterface": "payments", + "identity": { + "effect": "mutation", + "id": "payments.record-provider-confirmation/v1", + "keyRequirement": "required", + "product": "payments", + "readReceipt": false, + "recovery": "same-command", + "requiresPreparation": false, + "version": 1 + }, + "limits": { + "attemptTimeoutSeconds": 10, + "http": { + "attemptTimeoutMilliseconds": 2000, + "connectTimeoutMilliseconds": 1000, + "maximumMutationRetries": 0, + "maximumResponseBytes": 65536 + }, + "maximumCallAttempts": 10, + "maximumCallRetryDelaySeconds": 300, + "maximumConcurrentAttemptsPerRun": 1, + "maximumPreparationBytes": 65536, + "maximumRunDurationSeconds": 31536000, + "value": { + "maximumArrayItems": 256, + "maximumBytes": 131072, + "maximumDepth": 32, + "maximumNodes": 4096, + "maximumObjectMembers": 256, + "maximumStringBytes": 16384 + } + } + }, + "input": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "description": "Ask the Adapter to report a previously verified provider completion to\nthe instruction registry. The caller supplies no status or evidence.", + "properties": { + "disbursementId": { + "format": "uuid", + "not": { + "const": "00000000-0000-0000-0000-000000000000" + }, + "type": "string" + } + }, + "required": [ + "disbursementId" + ], + "title": "payments.record-provider-confirmation/v1 input", + "type": "object" + }, + "output": { + "$defs": { + "Money": { + "additionalProperties": false, + "description": "An exact positive decimal amount. Scale belongs to the configured currency\npolicy; wire amounts are strings so no binary floating-point rounding occurs.", + "properties": { + "currency": { + "pattern": "^[A-Z]{3}$", + "type": "string" + }, + "scale": { + "maximum": 6, + "minimum": 0, + "type": "integer" + }, + "value": { + "maxLength": 24, + "minLength": 1, + "not": { + "pattern": "^0(\\.0{1,6})?$" + }, + "pattern": "^(0|[1-9][0-9]*)(\\.[0-9]{1,6})?$", + "type": "string" + } + }, + "required": [ + "value", + "currency", + "scale" + ], + "type": "object" + } + }, + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "description": "The exact provider completion reported to the authoritative instruction.\nThis does not claim beneficiary credit or final settlement.", + "properties": { + "bindingRevision": { + "type": "string" + }, + "disbursementId": { + "format": "uuid", + "not": { + "const": "00000000-0000-0000-0000-000000000000" + }, + "type": "string" + }, + "instructionId": { + "format": "uuid", + "not": { + "const": "00000000-0000-0000-0000-000000000000" + }, + "type": "string" + }, + "instructionRecordId": { + "format": "uuid", + "not": { + "const": "00000000-0000-0000-0000-000000000000" + }, + "type": "string" + }, + "instructionVersion": { + "maximum": 9007199254740991, + "minimum": 1, + "type": "integer" + }, + "money": { + "$ref": "#/$defs/Money" + }, + "providerReference": { + "type": "string" + }, + "providerResultDigest": { + "type": "string" + }, + "simulation": { + "type": "boolean" + } + }, + "required": [ + "disbursementId", + "instructionRecordId", + "instructionId", + "instructionVersion", + "bindingRevision", + "simulation", + "money", + "providerReference", + "providerResultDigest" + ], + "title": "payments.record-provider-confirmation/v1 output", + "type": "object" + } + }, "payments.record-receipt/v1": { "host": { "authority": "current-bound-connection-authority", @@ -3111,6 +3462,149 @@ "type": "object" } }, + "payments.request-disbursement/v1": { + "host": { + "authority": "current-bound-connection-authority", + "completionObservation": { + "acceptedBinding": [ + "disbursementId", + "instructionRecordId", + "instructionId", + "instructionVersion", + "bindingRevision", + "simulation" + ], + "authenticatedWake": false, + "authority": "current-bound-payment-connection", + "deadline": "original-wait-timeout-within-original-run-deadline", + "defaultIntervalSeconds": 900, + "maximumRetryAfterSeconds": 86400, + "minimumIntervalSeconds": 30, + "name": "disbursement", + "observationLimit": "1 + ceil(waitDurationSeconds / effectiveIntervalSeconds)", + "paymentSuccessState": "provider-confirmed", + "pendingStates": [ + "accepted", + "pending", + "unknown" + ], + "profile": "payment-disbursement", + "settledStates": [ + "provider-confirmed", + "failed" + ], + "signalCarriesResult": false, + "terminalEvidence": "validated-authoritative-disbursement-read" + }, + "connectionInterface": "payments", + "identity": { + "effect": "mutation", + "id": "payments.request-disbursement/v1", + "keyRequirement": "required", + "product": "payments", + "readReceipt": true, + "recovery": "hold-after-dispatch", + "requiresPreparation": false, + "version": 1 + }, + "limits": { + "attemptTimeoutSeconds": 10, + "http": { + "attemptTimeoutMilliseconds": 2000, + "connectTimeoutMilliseconds": 1000, + "maximumMutationRetries": 0, + "maximumResponseBytes": 65536 + }, + "maximumCallAttempts": 10, + "maximumCallRetryDelaySeconds": 300, + "maximumConcurrentAttemptsPerRun": 1, + "maximumPreparationBytes": 65536, + "maximumRunDurationSeconds": 31536000, + "value": { + "maximumArrayItems": 256, + "maximumBytes": 131072, + "maximumDepth": 32, + "maximumNodes": 4096, + "maximumObjectMembers": 256, + "maximumStringBytes": 16384 + } + } + }, + "input": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "description": "A disbursement intent names an approved, immutable instruction held by the\nowning registry. The caller cannot supply amount, destination or funding.", + "properties": { + "instructionRecordId": { + "format": "uuid", + "not": { + "const": "00000000-0000-0000-0000-000000000000" + }, + "type": "string" + }, + "instructionVersion": { + "maximum": 9007199254740991, + "minimum": 1, + "type": "integer" + } + }, + "required": [ + "instructionRecordId", + "instructionVersion" + ], + "title": "payments.request-disbursement/v1 input", + "type": "object" + }, + "output": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "description": "A provider accepted the exact instruction command for asynchronous work.\nThis is not confirmation that the recipient was paid.", + "properties": { + "bindingRevision": { + "type": "string" + }, + "disbursementId": { + "format": "uuid", + "not": { + "const": "00000000-0000-0000-0000-000000000000" + }, + "type": "string" + }, + "instructionId": { + "format": "uuid", + "not": { + "const": "00000000-0000-0000-0000-000000000000" + }, + "type": "string" + }, + "instructionRecordId": { + "format": "uuid", + "not": { + "const": "00000000-0000-0000-0000-000000000000" + }, + "type": "string" + }, + "instructionVersion": { + "maximum": 9007199254740991, + "minimum": 1, + "type": "integer" + }, + "simulation": { + "type": "boolean" + } + }, + "required": [ + "disbursementId", + "instructionRecordId", + "instructionId", + "instructionVersion", + "bindingRevision", + "simulation" + ], + "title": "payments.request-disbursement/v1 output", + "type": "object" + } + }, "scheduling.cancel-appointment/v1": { "host": { "authority": "current-bound-connection-authority", diff --git a/products/coordinator/generated/operations/payments.disbursement.completion.schema.json b/products/coordinator/generated/operations/payments.disbursement.completion.schema.json new file mode 100644 index 0000000000..7044f0fec5 --- /dev/null +++ b/products/coordinator/generated/operations/payments.disbursement.completion.schema.json @@ -0,0 +1,112 @@ +{ + "$defs": { + "DisbursementState": { + "description": "Only provider-confirmed means the pinned provider reported completion.\nIt does not by itself claim end-recipient credit or settlement.", + "enum": [ + "accepted", + "pending", + "provider-confirmed", + "failed", + "unknown" + ], + "type": "string" + }, + "Money": { + "additionalProperties": false, + "description": "An exact positive decimal amount. Scale belongs to the configured currency\npolicy; wire amounts are strings so no binary floating-point rounding occurs.", + "properties": { + "currency": { + "pattern": "^[A-Z]{3}$", + "type": "string" + }, + "scale": { + "maximum": 6, + "minimum": 0, + "type": "integer" + }, + "value": { + "maxLength": 24, + "minLength": 1, + "not": { + "pattern": "^0(\\.0{1,6})?$" + }, + "pattern": "^(0|[1-9][0-9]*)(\\.[0-9]{1,6})?$", + "type": "string" + } + }, + "required": [ + "value", + "currency", + "scale" + ], + "type": "object" + } + }, + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "description": "A bounded observation of one saved disbursement instruction.", + "properties": { + "bindingRevision": { + "type": "string" + }, + "disbursementId": { + "format": "uuid", + "not": { + "const": "00000000-0000-0000-0000-000000000000" + }, + "type": "string" + }, + "failureReason": { + "type": [ + "string", + "null" + ] + }, + "instructionId": { + "format": "uuid", + "not": { + "const": "00000000-0000-0000-0000-000000000000" + }, + "type": "string" + }, + "instructionRecordId": { + "format": "uuid", + "not": { + "const": "00000000-0000-0000-0000-000000000000" + }, + "type": "string" + }, + "instructionVersion": { + "maximum": 9007199254740991, + "minimum": 1, + "type": "integer" + }, + "money": { + "$ref": "#/$defs/Money" + }, + "providerReference": { + "type": [ + "string", + "null" + ] + }, + "simulation": { + "type": "boolean" + }, + "state": { + "$ref": "#/$defs/DisbursementState" + } + }, + "required": [ + "disbursementId", + "instructionRecordId", + "instructionId", + "instructionVersion", + "bindingRevision", + "simulation", + "state", + "money" + ], + "title": "Payment disbursement completion", + "type": "object" +} diff --git a/products/coordinator/generated/operations/payments.read-disbursement.v1.input.schema.json b/products/coordinator/generated/operations/payments.read-disbursement.v1.input.schema.json new file mode 100644 index 0000000000..6484bcf07c --- /dev/null +++ b/products/coordinator/generated/operations/payments.read-disbursement.v1.input.schema.json @@ -0,0 +1,19 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "description": "Read one saved disbursement and its current provider observation.", + "properties": { + "disbursementId": { + "format": "uuid", + "not": { + "const": "00000000-0000-0000-0000-000000000000" + }, + "type": "string" + } + }, + "required": [ + "disbursementId" + ], + "title": "payments.read-disbursement/v1 input", + "type": "object" +} diff --git a/products/coordinator/generated/operations/payments.read-disbursement.v1.output.schema.json b/products/coordinator/generated/operations/payments.read-disbursement.v1.output.schema.json new file mode 100644 index 0000000000..72f4ce9b4a --- /dev/null +++ b/products/coordinator/generated/operations/payments.read-disbursement.v1.output.schema.json @@ -0,0 +1,112 @@ +{ + "$defs": { + "DisbursementState": { + "description": "Only provider-confirmed means the pinned provider reported completion.\nIt does not by itself claim end-recipient credit or settlement.", + "enum": [ + "accepted", + "pending", + "provider-confirmed", + "failed", + "unknown" + ], + "type": "string" + }, + "Money": { + "additionalProperties": false, + "description": "An exact positive decimal amount. Scale belongs to the configured currency\npolicy; wire amounts are strings so no binary floating-point rounding occurs.", + "properties": { + "currency": { + "pattern": "^[A-Z]{3}$", + "type": "string" + }, + "scale": { + "maximum": 6, + "minimum": 0, + "type": "integer" + }, + "value": { + "maxLength": 24, + "minLength": 1, + "not": { + "pattern": "^0(\\.0{1,6})?$" + }, + "pattern": "^(0|[1-9][0-9]*)(\\.[0-9]{1,6})?$", + "type": "string" + } + }, + "required": [ + "value", + "currency", + "scale" + ], + "type": "object" + } + }, + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "description": "A bounded observation of one saved disbursement instruction.", + "properties": { + "bindingRevision": { + "type": "string" + }, + "disbursementId": { + "format": "uuid", + "not": { + "const": "00000000-0000-0000-0000-000000000000" + }, + "type": "string" + }, + "failureReason": { + "type": [ + "string", + "null" + ] + }, + "instructionId": { + "format": "uuid", + "not": { + "const": "00000000-0000-0000-0000-000000000000" + }, + "type": "string" + }, + "instructionRecordId": { + "format": "uuid", + "not": { + "const": "00000000-0000-0000-0000-000000000000" + }, + "type": "string" + }, + "instructionVersion": { + "maximum": 9007199254740991, + "minimum": 1, + "type": "integer" + }, + "money": { + "$ref": "#/$defs/Money" + }, + "providerReference": { + "type": [ + "string", + "null" + ] + }, + "simulation": { + "type": "boolean" + }, + "state": { + "$ref": "#/$defs/DisbursementState" + } + }, + "required": [ + "disbursementId", + "instructionRecordId", + "instructionId", + "instructionVersion", + "bindingRevision", + "simulation", + "state", + "money" + ], + "title": "payments.read-disbursement/v1 output", + "type": "object" +} diff --git a/products/coordinator/generated/operations/payments.record-provider-confirmation.v1.input.schema.json b/products/coordinator/generated/operations/payments.record-provider-confirmation.v1.input.schema.json new file mode 100644 index 0000000000..ace912e805 --- /dev/null +++ b/products/coordinator/generated/operations/payments.record-provider-confirmation.v1.input.schema.json @@ -0,0 +1,19 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "description": "Ask the Adapter to report a previously verified provider completion to\nthe instruction registry. The caller supplies no status or evidence.", + "properties": { + "disbursementId": { + "format": "uuid", + "not": { + "const": "00000000-0000-0000-0000-000000000000" + }, + "type": "string" + } + }, + "required": [ + "disbursementId" + ], + "title": "payments.record-provider-confirmation/v1 input", + "type": "object" +} diff --git a/products/coordinator/generated/operations/payments.record-provider-confirmation.v1.output.schema.json b/products/coordinator/generated/operations/payments.record-provider-confirmation.v1.output.schema.json new file mode 100644 index 0000000000..9e041e9560 --- /dev/null +++ b/products/coordinator/generated/operations/payments.record-provider-confirmation.v1.output.schema.json @@ -0,0 +1,93 @@ +{ + "$defs": { + "Money": { + "additionalProperties": false, + "description": "An exact positive decimal amount. Scale belongs to the configured currency\npolicy; wire amounts are strings so no binary floating-point rounding occurs.", + "properties": { + "currency": { + "pattern": "^[A-Z]{3}$", + "type": "string" + }, + "scale": { + "maximum": 6, + "minimum": 0, + "type": "integer" + }, + "value": { + "maxLength": 24, + "minLength": 1, + "not": { + "pattern": "^0(\\.0{1,6})?$" + }, + "pattern": "^(0|[1-9][0-9]*)(\\.[0-9]{1,6})?$", + "type": "string" + } + }, + "required": [ + "value", + "currency", + "scale" + ], + "type": "object" + } + }, + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "description": "The exact provider completion reported to the authoritative instruction.\nThis does not claim beneficiary credit or final settlement.", + "properties": { + "bindingRevision": { + "type": "string" + }, + "disbursementId": { + "format": "uuid", + "not": { + "const": "00000000-0000-0000-0000-000000000000" + }, + "type": "string" + }, + "instructionId": { + "format": "uuid", + "not": { + "const": "00000000-0000-0000-0000-000000000000" + }, + "type": "string" + }, + "instructionRecordId": { + "format": "uuid", + "not": { + "const": "00000000-0000-0000-0000-000000000000" + }, + "type": "string" + }, + "instructionVersion": { + "maximum": 9007199254740991, + "minimum": 1, + "type": "integer" + }, + "money": { + "$ref": "#/$defs/Money" + }, + "providerReference": { + "type": "string" + }, + "providerResultDigest": { + "type": "string" + }, + "simulation": { + "type": "boolean" + } + }, + "required": [ + "disbursementId", + "instructionRecordId", + "instructionId", + "instructionVersion", + "bindingRevision", + "simulation", + "money", + "providerReference", + "providerResultDigest" + ], + "title": "payments.record-provider-confirmation/v1 output", + "type": "object" +} diff --git a/products/coordinator/generated/operations/payments.request-disbursement.v1.input.schema.json b/products/coordinator/generated/operations/payments.request-disbursement.v1.input.schema.json new file mode 100644 index 0000000000..81e2f6f9ec --- /dev/null +++ b/products/coordinator/generated/operations/payments.request-disbursement.v1.input.schema.json @@ -0,0 +1,25 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "description": "A disbursement intent names an approved, immutable instruction held by the\nowning registry. The caller cannot supply amount, destination or funding.", + "properties": { + "instructionRecordId": { + "format": "uuid", + "not": { + "const": "00000000-0000-0000-0000-000000000000" + }, + "type": "string" + }, + "instructionVersion": { + "maximum": 9007199254740991, + "minimum": 1, + "type": "integer" + } + }, + "required": [ + "instructionRecordId", + "instructionVersion" + ], + "title": "payments.request-disbursement/v1 input", + "type": "object" +} diff --git a/products/coordinator/generated/operations/payments.request-disbursement.v1.output.schema.json b/products/coordinator/generated/operations/payments.request-disbursement.v1.output.schema.json new file mode 100644 index 0000000000..4df7ab3991 --- /dev/null +++ b/products/coordinator/generated/operations/payments.request-disbursement.v1.output.schema.json @@ -0,0 +1,49 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "description": "A provider accepted the exact instruction command for asynchronous work.\nThis is not confirmation that the recipient was paid.", + "properties": { + "bindingRevision": { + "type": "string" + }, + "disbursementId": { + "format": "uuid", + "not": { + "const": "00000000-0000-0000-0000-000000000000" + }, + "type": "string" + }, + "instructionId": { + "format": "uuid", + "not": { + "const": "00000000-0000-0000-0000-000000000000" + }, + "type": "string" + }, + "instructionRecordId": { + "format": "uuid", + "not": { + "const": "00000000-0000-0000-0000-000000000000" + }, + "type": "string" + }, + "instructionVersion": { + "maximum": 9007199254740991, + "minimum": 1, + "type": "integer" + }, + "simulation": { + "type": "boolean" + } + }, + "required": [ + "disbursementId", + "instructionRecordId", + "instructionId", + "instructionVersion", + "bindingRevision", + "simulation" + ], + "title": "payments.request-disbursement/v1 output", + "type": "object" +} diff --git a/products/coordinator/generated/project/project.schema.json b/products/coordinator/generated/project/project.schema.json index 9ac61615ec..64304d2df8 100644 --- a/products/coordinator/generated/project/project.schema.json +++ b/products/coordinator/generated/project/project.schema.json @@ -964,7 +964,10 @@ "breg.read-record/v2", "payments.request-collection/v1", "payments.read-collection/v1", - "payments.record-receipt/v1" + "payments.record-receipt/v1", + "payments.request-disbursement/v1", + "payments.read-disbursement/v1", + "payments.record-provider-confirmation/v1" ], "type": "string" }, diff --git a/products/platform/config-formats.yaml b/products/platform/config-formats.yaml index 7a00a17171..114484c325 100644 --- a/products/platform/config-formats.yaml +++ b/products/platform/config-formats.yaml @@ -4505,6 +4505,86 @@ formats: whenOmitted: closed restrictingMembers: [/allowedPrivateCidrs, /oidc/audience, /oidc/issuer] + - id: adapter/payment-provider-fixture + product: adapter + title: Registry Adapter payment provider fixture + files: [payment-provider-fixture.yaml] + syntax: yaml + audience: authored + stability: experimental + current: + apiVersion: id.registrystack.org/formats/adapter/payment-provider-fixture/v1alpha1 + kind: AdapterPaymentProviderFixture + checkedBy: + file: crates/registry-adapterctl/src/payment_fixtures.rs + symbol: VERSION + target: + apiVersion: id.registrystack.org/formats/adapter/payment-provider-fixture/v1alpha1 + kind: AdapterPaymentProviderFixture + schema: + path: products/adapter/schemas/payment-provider-fixture.v1alpha1.schema.json + id: https://id.registrystack.org/schemas/adapter/payment-provider-fixture/payment-provider-fixture.v1alpha1.schema.json + origin: generated + generator: cargo run -p registry-adapterctl -- schemas --output-dir products/adapter/schemas + driftCheck: products/adapter/scripts/check-contracts.sh + reader: + crate: registry-adapterctl + file: crates/registry-adapterctl/src/payment_fixtures.rs + function: replay_mapped + type: FixtureDocument + check: adapterctl payments fixtures replay {payments} --provider-pack {pack}/pack.yaml --fixtures {file} + example: products/adapter/examples/payment-provider-fixture.yaml + conformance: + requiredText: /type + optionalText: none + integer: /acceptance/response/httpStatus + boolean: none + securityMembers: [] + restrictingMembers: [/type, /direction] + + - id: adapter/payment-provider-pack + product: adapter + title: Registry Adapter payment provider pack + files: [packs/*/pack.yaml] + syntax: yaml + audience: authored + stability: experimental + current: + apiVersion: id.registrystack.org/formats/adapter/payment-provider-pack/v1alpha1 + kind: AdapterPaymentProviderPack + checkedBy: + file: crates/registry-adapter/src/payments/pack.rs + symbol: API_VERSION + target: + apiVersion: id.registrystack.org/formats/adapter/payment-provider-pack/v1alpha1 + kind: AdapterPaymentProviderPack + schema: + path: products/adapter/schemas/payment-provider-pack.v1alpha1.schema.json + id: https://id.registrystack.org/schemas/adapter/payment-provider-pack/payment-provider-pack.v1alpha1.schema.json + origin: generated + generator: cargo run -p registry-adapterctl -- schemas --output-dir products/adapter/schemas + driftCheck: products/adapter/scripts/check-contracts.sh + reader: + crate: registry-adapter + file: crates/registry-adapter/src/payments/pack.rs + function: from_yaml + type: PaymentProviderPack + check: adapterctl payments check-pack {file} + example: products/adapter/packs/payment-simulator/pack.yaml + conformance: + requiredText: /id + optionalText: none + integer: none + boolean: none + securityMembers: + - {pointer: /connector, whenOmitted: refused} + - {pointer: /capabilities, whenOmitted: refused} + # Required for each declared direction of the generic HTTP connector; + # compiled connector packs have no mapping member. + - {pointer: /mapping/collection/auth, whenOmitted: unclassified} + - {pointer: /mapping/disbursement/auth, whenOmitted: unclassified} + restrictingMembers: [/connector, /capabilities, /mapping/collection/auth, /mapping/disbursement/auth] + - id: adapter/payments product: adapter title: Registry Adapter payment connections @@ -4540,15 +4620,23 @@ formats: integer: /connections/0/binding/replayWindowSeconds boolean: /connections/0/binding/simulation securityMembers: - - {pointer: /connections, whenOmitted: refused} + - {pointer: /connections, whenOmitted: closed} - {pointer: /connections/*/allowedClients, whenOmitted: refused} - {pointer: /connections/*/requiredScope, whenOmitted: refused} - {pointer: /connections/*/institutionId, whenOmitted: refused} - {pointer: /connections/*/serviceId, whenOmitted: refused} - {pointer: /connections/*/binding/simulation, whenOmitted: refused} - - {pointer: /connections/*/binding/provider/baseUrl, whenOmitted: refused} - - {pointer: /connections/*/binding/provider/tenant, whenOmitted: refused} - - {pointer: /connections/*/binding/provider/biller, whenOmitted: refused} + - {pointer: /connections/*/binding/provider/type, whenOmitted: refused} + - {pointer: /connections/*/binding/provider/connection/baseUrl, whenOmitted: refused} + - {pointer: /connections/*/binding/provider/connection/channelBaseUrl, whenOmitted: refused} + - {pointer: /connections/*/binding/provider/connection/bulkBaseUrl, whenOmitted: refused} + - {pointer: /connections/*/binding/provider/connection/operationsBaseUrl, whenOmitted: refused} + - {pointer: /connections/*/binding/provider/connection/tenant, whenOmitted: refused} + - {pointer: /connections/*/binding/provider/connection/biller, whenOmitted: refused} + - {pointer: /connections/*/binding/provider/connection/paymentScheme, whenOmitted: refused} + - {pointer: /connections/*/binding/provider/payer/financialAddressKey, whenOmitted: refused} + - {pointer: /connections/*/binding/provider/payer/payerIdKey, whenOmitted: refused} + - {pointer: /connections/*/binding/provider/transactionType, whenOmitted: refused} - {pointer: /connections/*/binding/providerCredentialRef, whenOmitted: refused} - {pointer: /connections/*/binding/providerCredentialIdentity, whenOmitted: refused} - {pointer: /connections/*/binding/replayWindowSeconds, whenOmitted: refused} @@ -4559,7 +4647,7 @@ formats: - {pointer: /connections/*/binding/registry/receiptProfile, whenOmitted: refused} - {pointer: /connections/*/binding/registry/bindAction, whenOmitted: refused} - {pointer: /connections/*/binding/registry/receiptAction, whenOmitted: refused} - restrictingMembers: [/connections, /connections/*/allowedClients, /connections/*/requiredScope, /connections/*/institutionId, /connections/*/serviceId, /connections/*/binding/simulation] + restrictingMembers: [/connections/*/allowedClients, /connections/*/requiredScope, /connections/*/institutionId, /connections/*/serviceId, /connections/*/binding/simulation] - id: adapter/job-runtime product: adapter From d66567e49b5726c66d480da8e9b5106e67d93a87 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 13 Nov 2026 03:44:58 +0700 Subject: [PATCH 06/40] docs(payments): align typed disbursement and recovery contracts Signed-off-by: Jeremi Joslin --- AGENTS.md | 8 +++++--- crates/registry-payment-client/src/lib.rs | 13 +++++++------ products/adapter/AGENTS.md | 17 ++++++++++------- products/coordinator/README.md | 2 ++ .../examples/g2p-disbursements/README.md | 6 ++++-- 5 files changed, 28 insertions(+), 18 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index e542fd462e..94183cdc3b 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -55,6 +55,7 @@ not products of their own. | `crates/registry-payment-protocol` | Runtime-free exact-money payment intents, observations, receipts and problem vocabulary | | `crates/registry-payment-client` | Bounded typed HTTP client for the Adapter payment contract | | `crates/registry-payment-simulator-connector` | Standalone synthetic P2G provider connector; no Adapter, Coordinator or product runtime dependency | +| `crates/registry-payment-mifos-connector` | Bounded Mifos Payment Hub EE wire and legacy signature profile; key custody belongs to the payment host | | `crates/registry-adapterctl` | Adapter authoring and operator tooling and the `adapterctl` binary | | `crates/registry-adapter-job` | Adapter ingestion-job host and the `adapter-job` binary: item table, pass, interval and authenticated hook triggers, and destination seam; identity and position only, never payloads | | `crates/registry-adapter-connectors` | Ingestion BReg connector over `registry-breg-client`, reachable only through the job host's explicit off-by-default `direct-breg` feature; never through the engine or facade; distinct from the payment host's direct public BReg client dependency; the dependency gate enforces this boundary | @@ -338,9 +339,10 @@ crate, and split. The adapter inherits no authorization from any product. The optional payment module is a separate approved host exception: `registry-adapter` may use `registry-payment-protocol`, the -standalone synthetic provider connector, and the public `registry-breg-client` -for authoritative bill reads and restricted binding/receipt Actions. The -source-neutral core, engine and generic job host gain no payment dependencies. +standalone simulator and Mifos provider connectors, and the public +`registry-breg-client` for authoritative bill and instruction reads and +restricted binding and reporting Actions. The source-neutral core, engine and +generic job host gain no payment dependencies. The payment host retains original attempt bindings and grants no authority to Coordinator or callers to assert financial facts. The record facade inherits no authorization diff --git a/crates/registry-payment-client/src/lib.rs b/crates/registry-payment-client/src/lib.rs index c2d2aa9bbc..52206ff710 100644 --- a/crates/registry-payment-client/src/lib.rs +++ b/crates/registry-payment-client/src/lib.rs @@ -2,12 +2,13 @@ //! Bounded client for Adapter collection and disbursement capabilities. //! -//! The client sends only the authoritative bill identifier and version a -//! service workflow supplies. Amount, provider state, and receipt evidence -//! are decoded from the Adapter's typed responses and validated before they -//! leave this crate. Reads are single exchanges. Keyed mutations may resend -//! only the exact request under the caller's original key, within the bounded -//! retry policy selected in [`PaymentClientConfig`]. +//! The client requests a collection by bill identity and version, or a +//! disbursement by instruction record identity and version. It validates +//! amount, provider state, and evidence in the Adapter's typed responses. +//! Reads are single exchanges. Disbursement submission sends once and uses a +//! read-only lookup to reconcile an unknown result. For mutations that permit +//! a resend, the bounded policy in [`PaymentClientConfig`] preserves the exact +//! request and the caller's original key. #![deny(unsafe_code)] diff --git a/products/adapter/AGENTS.md b/products/adapter/AGENTS.md index 686f0dcec0..a16f09f45b 100644 --- a/products/adapter/AGENTS.md +++ b/products/adapter/AGENTS.md @@ -19,8 +19,9 @@ product or any `registry-adapter*` crate. | `crates/registry-adapter-core` | Source-neutral Adapter model, wire DTOs, `adapter.*` problem codes, and pure authoring checks; no I/O (it depends on `registry-platform-httputil` only for its pure header predicates and bounds) | | `crates/registry-adapter-engine` | Bounded route engine, components, compilation and replay shared by facade, jobs and Evidence; no listener or PostgreSQL client | | `crates/registry-adapter` | Governed facade, caller security, audit journal and idempotency custody over the shared engine; optional typed payment host and PostgreSQL attempts | -| `crates/registry-payment-protocol` | Runtime-free typed collection, observation, receipt and problem contract | +| `crates/registry-payment-protocol` | Runtime-free typed collection, disbursement, observation, reporting and problem contract | | `crates/registry-payment-simulator-connector` | Standalone synthetic P2G wire and transport; no product clients, stores or runtimes | +| `crates/registry-payment-mifos-connector` | Released Mifos Payment Hub EE wire and signature profile; the payment host owns key custody | | `crates/registry-adapterctl` | Adapter authoring and operator tooling and the `adapterctl` binary | | `crates/registry-adapter-job` | The ingestion-job host and the `adapter-job` binary: the item table, the pass, interval and authenticated hook triggers, and the destination seam; it keeps identity and position only, never payloads | | `crates/registry-adapter-connectors` | BReg connector over `registry-breg-client`, behind the job host's off-by-default `direct-breg` feature. Engine and facade cannot reach it; the dependency gate names the exact permitted path | @@ -46,12 +47,14 @@ only, behind a feature, never a product runtime, CLI, or database crate, and `products/adapter/scripts/check_dependency_direction.py` enforces that boundary mechanically. No facade binary and neither engine crate links the ingestion connector crate. -The payment-host exception is `registry-adapter::payments`: the host links -the payment protocol, standalone synthetic provider connector, and public -`registry-breg-client` for restricted bill and receipt Actions. Its authoring -tool may inherit that host closure. Core and engine remain source-neutral; -neither gains payment types, stores or product clients. No product runtime, -tooling, database crate or Coordinator client enters the payment host closure. +The payment-host exception is `registry-adapter::payments`. The host links +the payment protocol, standalone simulator and Mifos provider connectors, and +public `registry-breg-client` for authoritative bill and instruction reads and +restricted binding and reporting Actions. Its authoring tool may inherit that +host closure and link the provider connectors for offline fixture replay. Core +and engine remain source-neutral and have no payment types, stores or product +clients. No product runtime, tooling, database crate or Coordinator client +enters the payment host closure. ## Gates diff --git a/products/coordinator/README.md b/products/coordinator/README.md index dfe10b5c9b..463b259772 100644 --- a/products/coordinator/README.md +++ b/products/coordinator/README.md @@ -67,6 +67,8 @@ project, its mappings, waits, and checks. interpreter for one previously selected external job. - [Payment collection](examples/payment-collections/README.md) requests one Adapter-owned collection, waits for its named completion, and records only a confirmed receipt. +- [Disbursement](examples/g2p-disbursements/README.md) submits one approved instruction, + waits for the correlated provider observation, and reports verified provider completion. ## Package and deploy diff --git a/products/coordinator/examples/g2p-disbursements/README.md b/products/coordinator/examples/g2p-disbursements/README.md index 1d12f60daf..c0ab77ae00 100644 --- a/products/coordinator/examples/g2p-disbursements/README.md +++ b/products/coordinator/examples/g2p-disbursements/README.md @@ -3,8 +3,10 @@ This project accepts one approved instruction record identity, asks the bound Adapter payment connection to submit it, waits for the named `disbursement` completion, and reports an exact provider confirmation back to the owning -instruction registry. Coordinator never receives the amount, recipient -destination, funding account, provider request, or provider evidence. +instruction registry. Adapter resolves the amount, recipient destination and +funding account from the approved BReg instruction. Coordinator receives +bounded, validated status and confirmation fields, including exact money, +provider reference and provider-result digest. The three outcomes are deliberately narrow: From 35733a10f415ad1f40b677128c1f6a9158bac496 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 13 Nov 2026 03:44:58 +0700 Subject: [PATCH 07/40] test(ci): cover mapped payment provider dependencies Signed-off-by: Jeremi Joslin --- .github/scripts/test_ci_changes.py | 3 +++ products/adapter/scripts/check-contracts.sh | 4 ++-- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/.github/scripts/test_ci_changes.py b/.github/scripts/test_ci_changes.py index 0f13a11e4a..4a7a620b09 100644 --- a/.github/scripts/test_ci_changes.py +++ b/.github/scripts/test_ci_changes.py @@ -1267,6 +1267,7 @@ def test_adapter_crates_and_product_select_its_shard(self) -> None: "crates/registry-adapter/src/lib.rs", "crates/registry-adapter-job/src/pass.rs", "crates/registry-adapterctl/src/main.rs", + "crates/registry-payment-mifos-connector/src/lib.rs", ): with self.subTest(path=path): outputs = classify(self.workspace, (path,)) @@ -3944,6 +3945,7 @@ def test_lock_selection_follows_build_and_dev_edges_to_every_consumer( change.members, frozenset( { + "registry-adapter", "registry-adapter-engine", "registry-breg", "registry-coordinator", @@ -3957,6 +3959,7 @@ def test_lock_selection_follows_build_and_dev_edges_to_every_consumer( ), ) outputs = classify(self.workspace, ("Cargo.lock",), lock_change=change) + self.assertTrue(outputs["adapter_contracts"]) self.assertTrue(outputs["platform"]) self.assertTrue(outputs["breg_contracts"]) self.assertTrue(outputs["evidence_contracts"]) diff --git a/products/adapter/scripts/check-contracts.sh b/products/adapter/scripts/check-contracts.sh index d808eb0613..04bc95fc7e 100755 --- a/products/adapter/scripts/check-contracts.sh +++ b/products/adapter/scripts/check-contracts.sh @@ -27,8 +27,8 @@ python3 -m unittest discover -s products/adapter/scripts -p 'test_test_connector # the caller's PATH. PATH="$HOME/.cargo/bin:$PATH" cargo fmt --all --check clear_completed_adapter_lane -PATH="$HOME/.cargo/bin:$PATH" cargo clippy --locked -p registry-adapter -p registry-adapter-core -p registry-adapter-engine -p registry-adapter-job -p registry-adapterctl -p registry-payment-protocol -p registry-payment-client -p registry-payment-simulator-connector --all-targets -- -D warnings -PATH="$HOME/.cargo/bin:$PATH" cargo test --locked -p registry-adapter -p registry-adapter-core -p registry-adapter-engine -p registry-adapter-job -p registry-adapterctl -p registry-payment-protocol -p registry-payment-client -p registry-payment-simulator-connector --no-fail-fast +PATH="$HOME/.cargo/bin:$PATH" cargo clippy --locked -p registry-adapter -p registry-adapter-core -p registry-adapter-engine -p registry-adapter-job -p registry-adapterctl -p registry-payment-protocol -p registry-payment-client -p registry-payment-simulator-connector -p registry-payment-mifos-connector --all-targets -- -D warnings +PATH="$HOME/.cargo/bin:$PATH" cargo test --locked -p registry-adapter -p registry-adapter-core -p registry-adapter-engine -p registry-adapter-job -p registry-adapterctl -p registry-payment-protocol -p registry-payment-client -p registry-payment-simulator-connector -p registry-payment-mifos-connector --no-fail-fast # The BReg connector is default-off. Compile every connector target with its # feature and execute its scripted suites here; the real-runtime scenarios # remain isolated under test-connector-native.py because they provision BReg From 6d2e1993f00c4a648b4126aea76b5060c158859a Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 13 Nov 2026 03:54:36 +0700 Subject: [PATCH 08/40] docs(adapter): publish payment fixture replay help Signed-off-by: Jeremi Joslin --- crates/registry-adapterctl/src/payments.rs | 3 + crates/registry-cli-docs/catalog.json | 190 ++++++++++++++++++++- 2 files changed, 192 insertions(+), 1 deletion(-) diff --git a/crates/registry-adapterctl/src/payments.rs b/crates/registry-adapterctl/src/payments.rs index 84a7431f02..e3e2b20ef6 100644 --- a/crates/registry-adapterctl/src/payments.rs +++ b/crates/registry-adapterctl/src/payments.rs @@ -59,10 +59,13 @@ pub enum PaymentsCommand { pub enum PaymentsFixturesCommand { /// Compare the pinned provider request and response mappings with fixtures. Replay { + /// Payment connection configuration used for replay. #[arg(value_name = "FILE")] file: PathBuf, + /// Provider pack pinned by the payment connection. #[arg(long, value_name = "FILE")] provider_pack: PathBuf, + /// Payment fixture file. Repeat to replay multiple files. #[arg(long, value_name = "FILE", required = true)] fixtures: Vec, }, diff --git a/crates/registry-cli-docs/catalog.json b/crates/registry-cli-docs/catalog.json index 8ccc617887..40397816cc 100644 --- a/crates/registry-cli-docs/catalog.json +++ b/crates/registry-cli-docs/catalog.json @@ -65,6 +65,15 @@ "possible_values": [], "environment": null }, + { + "display": "--payment-provider-pack ", + "description": "Reviewed provider packs for current connections and retained attempts", + "always_required": false, + "repeatable": true, + "default_values": [], + "possible_values": [], + "environment": null + }, { "display": "--profile ", "description": "The profile file; defaults to profile.yaml beside the project", @@ -93,7 +102,15 @@ "environment": null } ], - "constraints": [], + "constraints": [ + { + "kind": "requires-all", + "when": "--payment-provider-pack ", + "arguments": [ + "--payments-config " + ] + } + ], "subcommands": [] }, { @@ -1455,6 +1472,51 @@ ], "constraints": [], "subcommands": [ + { + "name": "check-pack", + "invocation": "adapterctl payments check-pack", + "about": "Validate one reviewed payment provider pack without a deployment", + "long_about": null, + "usage": "adapterctl payments check-pack [OPTIONS] ", + "arguments": [ + { + "display": "", + "description": "Provider pack file to validate", + "always_required": true, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + } + ], + "options": [ + { + "display": "--format ", + "description": "Emit the selected command's report in this format", + "always_required": false, + "repeatable": false, + "default_values": [ + "human" + ], + "possible_values": [ + "human", + "json" + ], + "environment": null + }, + { + "display": "-h, --help", + "description": "Print help", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + } + ], + "constraints": [], + "subcommands": [] + }, { "name": "check", "invocation": "adapterctl payments check", @@ -1473,6 +1535,24 @@ } ], "options": [ + { + "display": "--provider-pack ", + "description": "Exact provider pack pinned by the payment connections", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--fixtures ", + "description": "Offline provider request and response fixtures to check", + "always_required": false, + "repeatable": true, + "default_values": [], + "possible_values": [], + "environment": null + }, { "display": "--deny-warnings", "description": "Refuse warnings as well as errors", @@ -1527,6 +1607,15 @@ } ], "options": [ + { + "display": "--provider-pack ", + "description": "Exact provider pack pinned by the payment connections", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, { "display": "--format ", "description": "Emit the selected command's report in this format", @@ -1553,6 +1642,105 @@ ], "constraints": [], "subcommands": [] + }, + { + "name": "fixtures", + "invocation": "adapterctl payments fixtures", + "about": "Replay provider mappings without connecting to Mifos or BReg", + "long_about": null, + "usage": "adapterctl payments fixtures [OPTIONS] ", + "arguments": [], + "options": [ + { + "display": "--format ", + "description": "Emit the selected command's report in this format", + "always_required": false, + "repeatable": false, + "default_values": [ + "human" + ], + "possible_values": [ + "human", + "json" + ], + "environment": null + }, + { + "display": "-h, --help", + "description": "Print help", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + } + ], + "constraints": [], + "subcommands": [ + { + "name": "replay", + "invocation": "adapterctl payments fixtures replay", + "about": "Compare the pinned provider request and response mappings with fixtures", + "long_about": null, + "usage": "adapterctl payments fixtures replay [OPTIONS] --provider-pack --fixtures ", + "arguments": [ + { + "display": "", + "description": "Payment connection configuration used for replay", + "always_required": true, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + } + ], + "options": [ + { + "display": "--provider-pack ", + "description": "Provider pack pinned by the payment connection", + "always_required": true, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--fixtures ", + "description": "Payment fixture file. Repeat to replay multiple files", + "always_required": true, + "repeatable": true, + "default_values": [], + "possible_values": [], + "environment": null + }, + { + "display": "--format ", + "description": "Emit the selected command's report in this format", + "always_required": false, + "repeatable": false, + "default_values": [ + "human" + ], + "possible_values": [ + "human", + "json" + ], + "environment": null + }, + { + "display": "-h, --help", + "description": "Print help", + "always_required": false, + "repeatable": false, + "default_values": [], + "possible_values": [], + "environment": null + } + ], + "constraints": [], + "subcommands": [] + } + ] } ] }, From 0e9cc6ffd50e760553d007306e61a6e93f4efadc Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 13 Nov 2026 04:25:30 +0700 Subject: [PATCH 09/40] fix(adapter): validate every configured payment provider pack Signed-off-by: Jeremi Joslin --- crates/registry-adapterctl/src/payments.rs | 482 +++++++++++++------ crates/registry-adapterctl/tests/payments.rs | 285 ++++++++++- crates/registry-cli-docs/catalog.json | 8 +- 3 files changed, 619 insertions(+), 156 deletions(-) diff --git a/crates/registry-adapterctl/src/payments.rs b/crates/registry-adapterctl/src/payments.rs index e3e2b20ef6..6af5cc7f8a 100644 --- a/crates/registry-adapterctl/src/payments.rs +++ b/crates/registry-adapterctl/src/payments.rs @@ -4,12 +4,14 @@ use crate::payment_fixtures::{self, FixtureError}; use clap::{Args, Subcommand}; use registry_adapter::payments::config::{PaymentsConfig, API_VERSION, KIND}; use registry_adapter::payments::pack::{ - ConnectorKind, PaymentCapability, PaymentProviderAuth, PaymentProviderPack, + ConnectorKind, PaymentCapability, PaymentProviderAuth, PaymentProviderPack, ProviderPackPin, }; use registry_platform_config::{RuntimeConfigLoader, RuntimeEnvelope, DEFAULT_STAND_IN}; use registry_platform_yaml::{Diagnostic, Report}; use serde_json::{json, Value}; -use std::path::PathBuf; +use std::{collections::BTreeMap, path::PathBuf}; + +const MAX_PAYMENT_PROVIDER_PACKS: usize = 32; #[derive(Debug, Args)] pub struct PaymentsArgs { @@ -29,9 +31,9 @@ pub enum PaymentsCommand { /// AdapterPayments configuration file to validate. #[arg(value_name = "FILE")] file: PathBuf, - /// Exact provider pack pinned by the payment connections. + /// Exact provider pack pinned by a payment connection. Repeat for every active pin. #[arg(long, value_name = "FILE")] - provider_pack: Option, + provider_pack: Vec, /// Offline provider request and response fixtures to check. #[arg(long, value_name = "FILE")] fixtures: Vec, @@ -44,9 +46,9 @@ pub enum PaymentsCommand { /// AdapterPayments configuration file whose contract is exported. #[arg(value_name = "FILE")] file: PathBuf, - /// Exact provider pack pinned by the payment connections. + /// Exact provider pack pinned by a payment connection. Repeat for every active pin. #[arg(long, value_name = "FILE")] - provider_pack: Option, + provider_pack: Vec, }, /// Replay provider mappings without connecting to Mifos or BReg. Fixtures { @@ -85,11 +87,127 @@ pub struct PaymentCheck { pub deny_warnings: bool, } +struct LoadedProviderPack { + path: PathBuf, + pack: PaymentProviderPack, + bytes: Vec, +} + +struct ProviderPackRegistry { + by_digest: BTreeMap, +} + +enum ProviderPackLoadError { + Diagnostics(Vec), + Problem { + code: &'static str, + message: &'static str, + action: &'static str, + }, +} + +#[derive(Clone, Copy)] +enum ProviderPackSelectionError { + Missing, + Mismatch, +} + +impl ProviderPackRegistry { + fn load(paths: &[PathBuf]) -> Result { + if paths.len() > MAX_PAYMENT_PROVIDER_PACKS { + return Err(ProviderPackLoadError::Problem { + code: "adapter.payment.provider-pack-limit", + message: "Too many payment provider packs were supplied.", + action: "Supply no more than 32 exact provider pack files.", + }); + } + let mut by_digest = BTreeMap::new(); + for path in paths { + let absolute = + std::fs::canonicalize(path).map_err(|_| ProviderPackLoadError::Problem { + code: "adapter.payment.provider-pack-unavailable", + message: "A payment provider pack could not be read.", + action: "Correct the provider pack path and retry.", + })?; + let bytes = std::fs::read(&absolute).map_err(|_| ProviderPackLoadError::Problem { + code: "adapter.payment.provider-pack-unavailable", + message: "A payment provider pack could not be read.", + action: "Correct the provider pack path and retry.", + })?; + let pack = PaymentProviderPack::from_yaml(&bytes) + .map_err(|report| ProviderPackLoadError::Diagnostics(report.into_diagnostics()))?; + if pack.validate().is_err() { + return Err(ProviderPackLoadError::Problem { + code: "adapter.payment.provider-pack-refused", + message: "A payment provider pack was refused.", + action: "Correct the provider pack and retry.", + }); + } + let digest = registry_platform_config::sha256_uri(&bytes); + if by_digest.contains_key(&digest) { + return Err(ProviderPackLoadError::Problem { + code: "adapter.payment.provider-pack-duplicate", + message: "A payment provider pack was supplied more than once.", + action: "Supply each exact provider pack file once.", + }); + } + if pack.connector == ConnectorKind::AdapterPaymentHttpV1 + && payment_fixtures::compile_mapped_pack(&absolute, &pack, &bytes).is_err() + { + return Err(ProviderPackLoadError::Problem { + code: "adapter.payment.provider-pack-script-refused", + message: "The payment provider scripts were refused.", + action: "Check the complete script inventory, digests and entrypoints.", + }); + } + by_digest.insert( + digest, + LoadedProviderPack { + path: absolute, + pack, + bytes, + }, + ); + } + Ok(Self { by_digest }) + } + + fn for_pin( + &self, + pin: &ProviderPackPin, + ) -> Result<&LoadedProviderPack, ProviderPackSelectionError> { + if let Some(loaded) = self.by_digest.get(&pin.digest) { + return loaded + .pack + .check_pin(pin, &loaded.bytes) + .map(|()| loaded) + .map_err(|_| ProviderPackSelectionError::Mismatch); + } + if self + .by_digest + .values() + .any(|loaded| loaded.pack.id == pin.id && loaded.pack.version == pin.version) + { + Err(ProviderPackSelectionError::Mismatch) + } else { + Err(ProviderPackSelectionError::Missing) + } + } + + fn only(&self) -> Option<&LoadedProviderPack> { + if self.by_digest.len() == 1 { + self.by_digest.values().next() + } else { + None + } + } +} + pub fn run(command: &PaymentsCommand) -> PaymentCheck { if let PaymentsCommand::CheckPack { file } = command { return check_pack(file); } - let (file, provider_pack, fixtures, deny_warnings) = match command { + let (file, provider_packs, fixtures, deny_warnings) = match command { PaymentsCommand::Check { file, provider_pack, @@ -97,14 +215,14 @@ pub fn run(command: &PaymentsCommand) -> PaymentCheck { deny_warnings, } => ( file, - provider_pack.as_deref(), + provider_pack.as_slice(), fixtures.as_slice(), *deny_warnings, ), PaymentsCommand::Contract { file, provider_pack, - } => (file, provider_pack.as_deref(), &[][..], false), + } => (file, provider_pack.as_slice(), &[][..], false), PaymentsCommand::Fixtures { command: PaymentsFixturesCommand::Replay { @@ -114,7 +232,7 @@ pub fn run(command: &PaymentsCommand) -> PaymentCheck { }, } => ( file, - Some(provider_pack.as_path()), + std::slice::from_ref(provider_pack), fixtures.as_slice(), false, ), @@ -149,149 +267,25 @@ pub fn run(command: &PaymentsCommand) -> PaymentCheck { "The payment connections were refused.", "Check connection scopes, unique caller identities, currency and synthetic provider bindings; then retry.")); } else { - match provider_pack { - Some(path) => match std::fs::read(path) { - Ok(bytes) => match PaymentProviderPack::from_yaml(&bytes) { - Ok(pack) => { - if pack.validate().is_err() { - additional.push(check.error_at( - KIND, - "adapter.payment.provider-pack-refused", - "/connections", - "The payment provider pack was refused.", - "Correct the provider pack and retry.", - )); - } - if pack.connector == ConnectorKind::AdapterPaymentHttpV1 - && payment_fixtures::compile_mapped_pack(path, &pack, &bytes) - .is_err() - { - additional.push(check.error_at( - KIND, - "adapter.payment.provider-pack-script-refused", - "/connections", - "The payment provider scripts were refused.", - "Check the complete script inventory, digests and entrypoints.", - )); - } - for connection in &loaded.config.connections { - if pack.connector != connection.binding.connector_kind() - || !pack.capabilities.contains(&PaymentCapability::Collection) - || connection - .binding - .provider_pack - .as_ref() - .is_none_or(|pin| pack.check_pin(pin, &bytes).is_err()) - { - additional.push(check.error_at(KIND, "adapter.payment.provider-pack-pin", "/connections", - "The payment provider pack pin was refused.", - "Pin the exact reviewed provider pack bytes for every connection.")); - } - if pack.connector == ConnectorKind::AdapterPaymentHttpV1 - && pack - .mapping - .as_ref() - .and_then(|mapping| mapping.collection.as_ref()) - .is_none_or(|operation| { - operation.auth != PaymentProviderAuth::Bearer - }) - { - additional.push(check.error_at( - KIND, - "adapter.payment.provider-pack-auth", - "/connections", - "The collection authentication profile was refused.", - "Use a bearer collection pack supported by the HTTP host.", - )); - } - } - for connection in &loaded.config.disbursements { - if pack.connector != ConnectorKind::AdapterPaymentHttpV1 - || !pack.capabilities.contains(&PaymentCapability::Disbursement) - || pack - .check_pin(&connection.binding.provider_pack, &bytes) - .is_err() - { - additional.push(check.error_at(KIND, "adapter.payment.provider-pack-pin", "/disbursements", - "The G2P provider pack pin, connector, or capability was refused.", - "Pin the exact mapped provider pack with disbursement capability.")); - } - if pack.connector == ConnectorKind::AdapterPaymentHttpV1 - && pack - .mapping - .as_ref() - .and_then(|mapping| mapping.disbursement.as_ref()) - .is_none_or(|operation| { - operation.auth - != connection.binding.provider.auth_profile() - }) - { - additional.push(check.error_at( - KIND, - "adapter.payment.provider-pack-auth", - "/disbursements", - "The disbursement authentication profile differs from the pinned pack.", - "Select the host authentication profile required by the reviewed pack.", - )); - } - } - for fixture in fixtures { - let replay = if pack.connector - == ConnectorKind::AdapterPaymentHttpV1 - { - payment_fixtures::replay_mapped(fixture, path, &pack, &bytes) - } else { - payment_fixtures::replay(fixture, pack.connector) - }; - if let Err(error) = replay { - let (code, message, action) = match error { - FixtureError::Unavailable => ("adapter.payment.fixture-unavailable", "A payment provider fixture could not be read.", "Correct the fixture path and retry."), - FixtureError::Refused => ("adapter.payment.fixture-refused", "A payment provider fixture did not match the pinned connector mapping.", "Correct the fixture or provider pack and retry."), - }; - additional.push(check.error_at( - KIND, - code, - "/fixtures", - message, - action, - )); - } - } - } - Err(report) => additional.extend(report.into_diagnostics()), - }, - Err(_) => additional.push(check.error_at( - KIND, - "adapter.payment.provider-pack-unavailable", - "/connections", - "The payment provider pack could not be read.", - "Correct the provider pack path and retry.", - )), - }, - None if loaded.config.connections.iter().any(|connection| { - connection.binding.provider_pack.is_some() || !connection.binding.simulation - }) || !loaded.config.disbursements.is_empty() => - { - additional.push(check.error_at( - KIND, - "adapter.payment.provider-pack-required", - "/connections", - "A pinned payment provider pack was not supplied.", - "Pass --provider-pack with the exact pinned pack file.", - )); + match ProviderPackRegistry::load(provider_packs) { + Ok(registry) => check_provider_pack_bindings( + &check, + &loaded.config, + ®istry, + fixtures, + &mut additional, + ), + Err(ProviderPackLoadError::Diagnostics(diagnostics)) => { + additional.extend(diagnostics); } - None => {} + Err(ProviderPackLoadError::Problem { + code, + message, + action, + }) => additional.push(check.error_at(KIND, code, "/connections", message, action)), } - if !fixtures.is_empty() && provider_pack.is_none() { - additional.push(check.error_at( - KIND, - "adapter.payment.fixture-pack-required", - "/fixtures", - "Payment provider fixtures require a provider pack.", - "Pass --provider-pack with the exact pinned pack file.", - )); - } - value["connectionCount"] = json!(loaded.config.connections.len()); + value["connectionCount"] = + json!(loaded.config.connections.len() + loaded.config.disbursements.len()); value["fixturesChecked"] = json!(fixtures.len()); if matches!(command, PaymentsCommand::Contract { .. }) { value["contract"] = registry_adapter::payments::http::contract(&loaded.config); @@ -306,6 +300,192 @@ pub fn run(command: &PaymentsCommand) -> PaymentCheck { } } +fn check_provider_pack_bindings( + check: ®istry_platform_config::RuntimeFileCheck, + config: &PaymentsConfig, + registry: &ProviderPackRegistry, + fixtures: &[PathBuf], + additional: &mut Vec, +) { + check_payment_fixtures(check, registry, fixtures, additional); + for (index, connection) in config.connections.iter().enumerate() { + let path = format!("/connections/{index}/binding/providerPack"); + let Some(pin) = connection.binding.provider_pack.as_ref() else { + if connection.binding.simulation { + continue; + } + additional.push(check.error_at( + KIND, + "adapter.payment.provider-pack-required", + &path, + "A pinned payment provider pack was not supplied.", + "Pass --provider-pack with the exact pinned pack file.", + )); + continue; + }; + let selected = match registry.for_pin(pin) { + Ok(selected) => selected, + Err(error) => { + let (code, message, action) = match error { + ProviderPackSelectionError::Missing => ( + "adapter.payment.provider-pack-required", + "The pinned payment provider pack was not supplied.", + "Pass --provider-pack with the exact pinned pack file.", + ), + ProviderPackSelectionError::Mismatch => ( + "adapter.payment.provider-pack-pin", + "The payment provider pack pin was refused.", + "Pin the exact reviewed provider pack bytes for this connection.", + ), + }; + additional.push(check.error_at(KIND, code, &path, message, action)); + continue; + } + }; + if selected.pack.connector != connection.binding.connector_kind() + || !selected + .pack + .capabilities + .contains(&PaymentCapability::Collection) + { + additional.push(check.error_at( + KIND, + "adapter.payment.provider-pack-pin", + &path, + "The payment provider pack connector or capability was refused.", + "Pin an exact provider pack with the connection's collection capability.", + )); + continue; + } + if matches!( + &connection.binding.provider, + registry_adapter::payments::config::CollectionProvider::Http { .. } + ) && selected + .pack + .mapping + .as_ref() + .and_then(|mapping| mapping.collection.as_ref()) + .is_none_or(|operation| operation.auth != PaymentProviderAuth::Bearer) + { + additional.push(check.error_at( + KIND, + "adapter.payment.provider-pack-auth", + &format!("/connections/{index}/binding/provider"), + "The collection authentication profile was refused.", + "Use a bearer collection pack supported by the HTTP host.", + )); + } + } + for (index, connection) in config.disbursements.iter().enumerate() { + let path = format!("/disbursements/{index}/binding/providerPack"); + let selected = match registry.for_pin(&connection.binding.provider_pack) { + Ok(selected) => selected, + Err(error) => { + let (code, message, action) = match error { + ProviderPackSelectionError::Missing => ( + "adapter.payment.provider-pack-required", + "The pinned G2P provider pack was not supplied.", + "Pass --provider-pack with the exact pinned pack file.", + ), + ProviderPackSelectionError::Mismatch => ( + "adapter.payment.provider-pack-pin", + "The G2P provider pack pin was refused.", + "Pin the exact reviewed provider pack bytes for this connection.", + ), + }; + additional.push(check.error_at(KIND, code, &path, message, action)); + continue; + } + }; + if selected.pack.connector != ConnectorKind::AdapterPaymentHttpV1 + || !selected + .pack + .capabilities + .contains(&PaymentCapability::Disbursement) + { + additional.push(check.error_at( + KIND, + "adapter.payment.provider-pack-pin", + &path, + "The G2P provider pack connector or capability was refused.", + "Pin the exact mapped provider pack with disbursement capability.", + )); + continue; + } + let expected_auth = connection.binding.provider.auth_profile(); + let mapped_auth_matches = selected + .pack + .mapping + .as_ref() + .and_then(|mapping| mapping.disbursement.as_ref()) + .is_some_and(|operation| operation.auth == expected_auth); + if !mapped_auth_matches { + additional.push(check.error_at( + KIND, + "adapter.payment.provider-pack-auth", + &format!("/disbursements/{index}/binding/provider"), + "The disbursement authentication profile differs from the pinned pack.", + "Select the host authentication profile required by the reviewed pack.", + )); + } + } +} + +fn check_payment_fixtures( + check: ®istry_platform_config::RuntimeFileCheck, + registry: &ProviderPackRegistry, + fixtures: &[PathBuf], + additional: &mut Vec, +) { + if fixtures.is_empty() { + return; + } + let Some(selected) = registry.only() else { + let (code, message, action) = if registry.by_digest.is_empty() { + ( + "adapter.payment.fixture-pack-required", + "Payment provider fixtures require a provider pack.", + "Pass --provider-pack with the exact pinned pack file.", + ) + } else { + ( + "adapter.payment.fixture-pack-ambiguous", + "Payment provider fixtures cannot select among multiple provider packs.", + "Check fixtures with one --provider-pack invocation at a time.", + ) + }; + additional.push(check.error_at(KIND, code, "/fixtures", message, action)); + return; + }; + for fixture in fixtures { + let replay = if selected.pack.connector == ConnectorKind::AdapterPaymentHttpV1 { + payment_fixtures::replay_mapped( + fixture, + &selected.path, + &selected.pack, + &selected.bytes, + ) + } else { + payment_fixtures::replay(fixture, selected.pack.connector) + }; + if let Err(error) = replay { + let (code, message, action) = match error { + FixtureError::Unavailable => ( + "adapter.payment.fixture-unavailable", + "A payment provider fixture could not be read.", + "Correct the fixture path and retry.", + ), + FixtureError::Refused => ( + "adapter.payment.fixture-refused", + "A payment provider fixture did not match the pinned connector mapping.", + "Correct the fixture or provider pack and retry.", + ), + }; + additional.push(check.error_at(KIND, code, "/fixtures", message, action)); + } + } +} + fn check_pack(file: &PathBuf) -> PaymentCheck { let bytes = match std::fs::read(file) { Ok(bytes) => bytes, diff --git a/crates/registry-adapterctl/tests/payments.rs b/crates/registry-adapterctl/tests/payments.rs index ce96fdf58f..1c901dde4a 100644 --- a/crates/registry-adapterctl/tests/payments.rs +++ b/crates/registry-adapterctl/tests/payments.rs @@ -1,5 +1,134 @@ // SPDX-License-Identifier: Apache-2.0 -use std::{path::PathBuf, process::ExitCode}; +use serde_json::{json, Value}; +use std::{ + path::{Path, PathBuf}, + process::ExitCode, +}; + +const MAPPED_PROVIDER_SCRIPT: &str = r#" +fn submit_request(intent, settings, acceptance) { + if settings == () || acceptance != () { throw "invalid submit context"; } + #{pathParameters: #{}, query: #{}, headers: #{}, body: #{correlation: intent.correlationId}} +} +fn submit_response(intent, settings, acceptance, response) { + if settings == () || acceptance != () || response == () { throw "invalid submit context"; } + #{correlationId: intent.correlationId, references: #{transaction: "accepted"}} +} +fn status_request(intent, settings, acceptance) { + if intent == () || settings == () || acceptance == () { throw "status needs context"; } + #{pathParameters: #{}, query: #{}, headers: #{}, body: ()} +} +fn status_response(intent, settings, acceptance, response) { + if settings == () || acceptance == () || response == () { throw "status needs context"; } + #{ + correlationId: intent.correlationId, + providerReference: "accepted", + state: "pending", + money: intent.money, + parties: [#{role: "payer", key: intent.source.scheme, value: intent.source.value}] + } +} +"#; + +fn mapped_provider_pack(id: &str) -> String { + format!( + r#"apiVersion: id.registrystack.org/formats/adapter/payment-provider-pack/v1alpha1 +kind: AdapterPaymentProviderPack +id: {id} +version: '1' +connector: adapter-payment-http/v1 +capabilities: [collection] +mapping: + collection: + auth: bearer + submit: + path: /collections + request: {{file: mapping.rhai, entrypoint: submit_request}} + response: {{file: mapping.rhai, entrypoint: submit_response}} + status: + path: /collections/status + request: {{file: mapping.rhai, entrypoint: status_request}} + response: {{file: mapping.rhai, entrypoint: status_response}} + scripts: + - path: mapping.rhai + digest: {} +"#, + registry_platform_config::sha256_uri(MAPPED_PROVIDER_SCRIPT.as_bytes()) + ) +} + +fn write_mapped_provider_pack(directory: &Path, id: &str) -> (PathBuf, String) { + std::fs::write(directory.join("mapping.rhai"), MAPPED_PROVIDER_SCRIPT).unwrap(); + let bytes = mapped_provider_pack(id); + let path = directory.join(format!("{id}.yaml")); + std::fs::write(&path, &bytes).unwrap(); + let digest = registry_platform_config::sha256_uri(bytes.as_bytes()); + (path, digest) +} + +fn registry_binding() -> Value { + json!({ + "baseUrl": "http://127.0.0.1:8080/", + "recordType": "service-fee-bill", + "recordRoute": "service-fee-bills", + "readProfile": "payment-adapter-reporter", + "bindProfile": "payment-adapter-binder", + "receiptProfile": "payment-adapter-reporter", + "bindAction": "bind-payment-attempt", + "receiptAction": "record-payment-receipt", + "credentialRef": "secret:env/PAYMENT_REPORTER_TOKEN", + "credentialIdentity": "payment-adapter" + }) +} + +fn mapped_collection(id: &str, pack_id: &str, digest: &str) -> Value { + json!({ + "id": id, + "institutionId": "ministry", + "serviceId": id, + "allowedClients": ["payment-coordinator"], + "requiredScope": "payments:collections", + "binding": { + "providerPack": {"id": pack_id, "version": "1", "digest": digest}, + "simulation": false, + "currency": "USD", + "currencyScale": 2, + "providerCredentialRef": "secret:env/PROVIDER_TOKEN", + "providerCredentialIdentity": "provider-client", + "replayWindowSeconds": 3600, + "provider": { + "type": "http", + "submitBaseUrl": "https://submit.example.test/", + "statusBaseUrl": "https://status.example.test/", + "settings": {"tenant": "pilot"} + }, + "registry": registry_binding() + } + }) +} + +fn write_payments(directory: &Path, connections: Vec) -> PathBuf { + let path = directory.join("payments.json"); + std::fs::write( + &path, + serde_json::to_vec_pretty(&json!({ + "apiVersion": "id.registrystack.org/formats/adapter/payments/v1alpha1", + "kind": "AdapterPayments", + "connections": connections + })) + .unwrap(), + ) + .unwrap(); + path +} + +fn run_json(args: Vec) -> (ExitCode, Value) { + let mut stdout = Vec::new(); + let mut stderr = Vec::new(); + let code = registry_adapterctl::main_entry_from(args, &mut stdout, &mut stderr); + assert!(stderr.is_empty(), "{}", String::from_utf8_lossy(&stderr)); + (code, serde_json::from_slice(&stdout).unwrap()) +} #[test] fn payment_connections_can_be_checked_without_secrets_a_registry_project_or_network() { @@ -166,3 +295,157 @@ fn payment_check_consumes_the_exact_pinned_provider_pack() { "adapter.payment.provider-pack-pin" ); } + +#[test] +fn payment_check_and_contract_accept_distinct_active_provider_pins() { + let directory = tempfile::tempdir().unwrap(); + let (alpha_path, alpha_digest) = write_mapped_provider_pack(directory.path(), "provider-alpha"); + let (beta_path, beta_digest) = write_mapped_provider_pack(directory.path(), "provider-beta"); + let file = write_payments( + directory.path(), + vec![ + mapped_collection("alpha-fees", "provider-alpha", &alpha_digest), + mapped_collection("beta-fees", "provider-beta", &beta_digest), + ], + ); + + for command in ["check", "contract"] { + let (code, report) = run_json(vec![ + "adapterctl".into(), + "--format".into(), + "json".into(), + "payments".into(), + command.into(), + file.display().to_string(), + "--provider-pack".into(), + alpha_path.display().to_string(), + "--provider-pack".into(), + beta_path.display().to_string(), + ]); + assert_eq!(code, ExitCode::SUCCESS, "{command}: {report}"); + assert_eq!(report["diagnostics"], json!([]), "{command}: {report}"); + if command == "contract" { + assert!(report["contract"].is_object(), "{report}"); + } + } +} + +#[test] +fn payment_check_fails_closed_for_a_missing_or_mismatched_active_pack() { + let directory = tempfile::tempdir().unwrap(); + let (alpha_path, alpha_digest) = write_mapped_provider_pack(directory.path(), "provider-alpha"); + let (beta_path, beta_digest) = write_mapped_provider_pack(directory.path(), "provider-beta"); + let file = write_payments( + directory.path(), + vec![ + mapped_collection("alpha-fees", "provider-alpha", &alpha_digest), + mapped_collection("beta-fees", "provider-beta", &beta_digest), + ], + ); + + let base = vec![ + "adapterctl".into(), + "--format".into(), + "json".into(), + "payments".into(), + "check".into(), + file.display().to_string(), + "--provider-pack".into(), + alpha_path.display().to_string(), + ]; + let (code, report) = run_json(base.clone()); + assert_eq!(code, ExitCode::from(1), "{report}"); + assert!(report["diagnostics"] + .as_array() + .unwrap() + .iter() + .any(|item| { + item["code"] == "adapter.payment.provider-pack-required" + && item["path"] == "/connections/1/binding/providerPack" + })); + + std::fs::write( + &beta_path, + mapped_provider_pack("provider-beta").replace( + "capabilities: [collection]", + "capabilities: [collection]\ntestedVersions: [tampered]", + ), + ) + .unwrap(); + let mut mismatched = base; + mismatched.extend(["--provider-pack".into(), beta_path.display().to_string()]); + let (code, report) = run_json(mismatched); + assert_eq!(code, ExitCode::from(1), "{report}"); + assert!(report["diagnostics"] + .as_array() + .unwrap() + .iter() + .any(|item| { + item["code"] == "adapter.payment.provider-pack-pin" + && item["path"] == "/connections/1/binding/providerPack" + })); +} + +#[test] +fn payment_check_bounds_the_provider_pack_registry() { + let directory = tempfile::tempdir().unwrap(); + let (pack_path, digest) = write_mapped_provider_pack(directory.path(), "provider-alpha"); + let file = write_payments( + directory.path(), + vec![mapped_collection("alpha-fees", "provider-alpha", &digest)], + ); + let mut args = vec![ + "adapterctl".into(), + "--format".into(), + "json".into(), + "payments".into(), + "check".into(), + file.display().to_string(), + ]; + for _ in 0..33 { + args.extend(["--provider-pack".into(), pack_path.display().to_string()]); + } + + let (code, report) = run_json(args); + assert_eq!(code, ExitCode::from(1), "{report}"); + assert_eq!( + report["diagnostics"][0]["code"], + "adapter.payment.provider-pack-limit" + ); +} + +#[test] +fn payment_check_refuses_ambiguous_multi_pack_fixture_replay() { + let directory = tempfile::tempdir().unwrap(); + let (alpha_path, alpha_digest) = write_mapped_provider_pack(directory.path(), "provider-alpha"); + let (beta_path, beta_digest) = write_mapped_provider_pack(directory.path(), "provider-beta"); + let file = write_payments( + directory.path(), + vec![ + mapped_collection("alpha-fees", "provider-alpha", &alpha_digest), + mapped_collection("beta-fees", "provider-beta", &beta_digest), + ], + ); + let fixture = directory.path().join("fixture.yaml"); + std::fs::write(&fixture, "not inspected when pack selection is ambiguous\n").unwrap(); + + let (code, report) = run_json(vec![ + "adapterctl".into(), + "--format".into(), + "json".into(), + "payments".into(), + "check".into(), + file.display().to_string(), + "--provider-pack".into(), + alpha_path.display().to_string(), + "--provider-pack".into(), + beta_path.display().to_string(), + "--fixtures".into(), + fixture.display().to_string(), + ]); + assert_eq!(code, ExitCode::from(1), "{report}"); + assert_eq!( + report["diagnostics"][0]["code"], + "adapter.payment.fixture-pack-ambiguous" + ); +} diff --git a/crates/registry-cli-docs/catalog.json b/crates/registry-cli-docs/catalog.json index 40397816cc..2a84f02168 100644 --- a/crates/registry-cli-docs/catalog.json +++ b/crates/registry-cli-docs/catalog.json @@ -1537,9 +1537,9 @@ "options": [ { "display": "--provider-pack ", - "description": "Exact provider pack pinned by the payment connections", + "description": "Exact provider pack pinned by a payment connection. Repeat for every active pin", "always_required": false, - "repeatable": false, + "repeatable": true, "default_values": [], "possible_values": [], "environment": null @@ -1609,9 +1609,9 @@ "options": [ { "display": "--provider-pack ", - "description": "Exact provider pack pinned by the payment connections", + "description": "Exact provider pack pinned by a payment connection. Repeat for every active pin", "always_required": false, - "repeatable": false, + "repeatable": true, "default_values": [], "possible_values": [], "environment": null From 2daf77add2283acb2ffed7026f3b2b55b56a0a16 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 13 Nov 2026 04:23:30 +0700 Subject: [PATCH 10/40] feat(adapter): enforce Mifos Bulk signatures and Operations bearer access Signed-off-by: Jeremi Joslin --- crates/registry-adapter/Cargo.toml | 2 +- .../src/payments/g2p_model.rs | 191 ++++- .../src/payments/g2p_service.rs | 376 ++++++++-- crates/registry-adapter/src/payments/http.rs | 24 +- .../src/payments/provider_mapping.rs | 1 + crates/registry-adapter/tests/g2p_model.rs | 199 +++++- crates/registry-adapter/tests/g2p_postgres.rs | 10 +- crates/registry-adapter/tests/g2p_provider.rs | 676 +++++++++++++++++- .../tests/payment_provider_mapping.rs | 2 + crates/registry-adapterctl/tests/payments.rs | 83 +++ products/adapter/README.md | 24 +- .../examples/payment-collections/README.md | 53 +- .../payments.mifos.example.yaml | 99 +++ .../schemas/payments.v1alpha1.schema.json | 81 ++- products/platform/config-formats.yaml | 48 +- 15 files changed, 1708 insertions(+), 161 deletions(-) create mode 100644 products/adapter/examples/payment-collections/payments.mifos.example.yaml diff --git a/crates/registry-adapter/Cargo.toml b/crates/registry-adapter/Cargo.toml index 1170a0a221..06ed52e255 100644 --- a/crates/registry-adapter/Cargo.toml +++ b/crates/registry-adapter/Cargo.toml @@ -71,7 +71,7 @@ schemars = { workspace = true, optional = true } async-trait.workspace = true registry-platform-buildinfo.workspace = true registry-platform-config.workspace = true -registry-platform-crypto.workspace = true +registry-platform-crypto = { workspace = true, features = ["transit"] } registry-platform-httputil.workspace = true registry-platform-script.workspace = true registry-platform-httpsec = { workspace = true, features = ["server"] } diff --git a/crates/registry-adapter/src/payments/g2p_model.rs b/crates/registry-adapter/src/payments/g2p_model.rs index 33bd4a4e00..d3f33fccf4 100644 --- a/crates/registry-adapter/src/payments/g2p_model.rs +++ b/crates/registry-adapter/src/payments/g2p_model.rs @@ -18,6 +18,7 @@ use registry_platform_yaml::SecretReference; use serde::{Deserialize, Serialize}; use serde_json::{Map, Value}; use sha2::{Digest, Sha256}; +use std::path::PathBuf; use uuid::Uuid; const MAX_TEXT: usize = 128; @@ -40,7 +41,7 @@ pub enum G2pError { RecoveryHeld, } -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub struct DisbursementInstruction { pub record_id: Uuid, @@ -107,15 +108,58 @@ impl DisbursementInstruction { /// these credentials or choose an authentication mechanism. #[derive(Clone)] pub enum G2pHttpAuth { - Bearer, + Bearer { + credential_identity: String, + credential_ref: SecretReference, + }, MifosLegacySignature { + tenant: String, signing_key_identity: String, - signing_key_ref: SecretReference, + signing_key: G2pTransitRsaNoOidKeyBinding, response_key_identity: String, - response_key_ref: SecretReference, + response_key: G2pTransitRsaNoOidKeyBinding, + operations_credential_identity: String, + operations_credential_ref: SecretReference, }, } +/// Exact Transit RSA key version and SPKI identity retained with an attempt. +/// Private key bytes never enter Adapter configuration or durable custody. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct G2pTransitRsaNoOidKeyBinding { + pub socket_path: PathBuf, + pub mount: String, + pub key: String, + pub version: registry_platform_yaml::BoundedU32<1, 2_147_483_647>, + pub public_key_digest: registry_platform_yaml::Digest, + pub attempt_timeout_milliseconds: registry_platform_yaml::BoundedU32<1, 30_000>, +} + +impl G2pTransitRsaNoOidKeyBinding { + pub fn public_key_sha256(&self) -> Result<[u8; 32], G2pError> { + let mut output = [0_u8; 32]; + for (index, pair) in self + .public_key_digest + .hex() + .as_bytes() + .chunks_exact(2) + .enumerate() + { + output[index] = (hex_digit(pair[0])? << 4) | hex_digit(pair[1])?; + } + Ok(output) + } + + fn validate(&self) -> Result<(), G2pError> { + if !self.socket_path.is_absolute() || !text(&self.mount, 256) || !text(&self.key, 256) { + return Err(G2pError::Unavailable); + } + self.public_key_sha256().map(|_| ()) + } +} + #[derive(Deserialize)] #[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] #[serde( @@ -126,12 +170,18 @@ pub enum G2pHttpAuth { )] #[cfg_attr(feature = "schema", schemars(!remote, tag = "type"))] enum G2pHttpAuthReader { - Bearer {}, + Bearer { + credential_identity: String, + credential_ref: SecretReference, + }, MifosLegacySignature { + tenant: String, signing_key_identity: String, - signing_key_ref: SecretReference, + signing_key: G2pTransitRsaNoOidKeyBinding, response_key_identity: String, - response_key_ref: SecretReference, + response_key: G2pTransitRsaNoOidKeyBinding, + operations_credential_identity: String, + operations_credential_ref: SecretReference, }, } registry_platform_yaml::tagged_union!(G2pHttpAuthReader); @@ -139,17 +189,29 @@ registry_platform_yaml::tagged_union!(G2pHttpAuthReader); impl<'de> Deserialize<'de> for G2pHttpAuth { fn deserialize>(deserializer: D) -> Result { ::deserialize(deserializer).map(|reader| match reader { - G2pHttpAuthReader::Bearer {} => Self::Bearer, + G2pHttpAuthReader::Bearer { + credential_identity, + credential_ref, + } => Self::Bearer { + credential_identity, + credential_ref, + }, G2pHttpAuthReader::MifosLegacySignature { + tenant, signing_key_identity, - signing_key_ref, + signing_key, response_key_identity, - response_key_ref, + response_key, + operations_credential_identity, + operations_credential_ref, } => Self::MifosLegacySignature { + tenant, signing_key_identity, - signing_key_ref, + signing_key, response_key_identity, - response_key_ref, + response_key, + operations_credential_identity, + operations_credential_ref, }, }) } @@ -162,29 +224,47 @@ impl<'de> Deserialize<'de> for G2pHttpAuth { rename_all_fields = "camelCase" )] enum G2pHttpAuthWire<'a> { - Bearer {}, + Bearer { + credential_identity: &'a str, + credential_ref: &'a SecretReference, + }, MifosLegacySignature { + tenant: &'a str, signing_key_identity: &'a str, - signing_key_ref: &'a SecretReference, + signing_key: &'a G2pTransitRsaNoOidKeyBinding, response_key_identity: &'a str, - response_key_ref: &'a SecretReference, + response_key: &'a G2pTransitRsaNoOidKeyBinding, + operations_credential_identity: &'a str, + operations_credential_ref: &'a SecretReference, }, } impl Serialize for G2pHttpAuth { fn serialize(&self, serializer: S) -> Result { match self { - Self::Bearer => G2pHttpAuthWire::Bearer {}, + Self::Bearer { + credential_identity, + credential_ref, + } => G2pHttpAuthWire::Bearer { + credential_identity, + credential_ref, + }, Self::MifosLegacySignature { + tenant, signing_key_identity, - signing_key_ref, + signing_key, response_key_identity, - response_key_ref, + response_key, + operations_credential_identity, + operations_credential_ref, } => G2pHttpAuthWire::MifosLegacySignature { + tenant, signing_key_identity, - signing_key_ref, + signing_key, response_key_identity, - response_key_ref, + response_key, + operations_credential_identity, + operations_credential_ref, }, } .serialize(serializer) @@ -205,34 +285,67 @@ impl schemars::JsonSchema for G2pHttpAuth { impl G2pHttpAuth { pub const fn profile(&self) -> PaymentProviderAuth { match self { - Self::Bearer => PaymentProviderAuth::Bearer, + Self::Bearer { .. } => PaymentProviderAuth::Bearer, Self::MifosLegacySignature { .. } => PaymentProviderAuth::MifosLegacySignature, } } - fn validate(&self) -> Result<(), G2pError> { + pub fn validate(&self) -> Result<(), G2pError> { match self { - Self::Bearer => Ok(()), + Self::Bearer { + credential_identity, + .. + } if text(credential_identity, 256) => Ok(()), + Self::Bearer { .. } => Err(G2pError::Unavailable), Self::MifosLegacySignature { + tenant, signing_key_identity, + signing_key, response_key_identity, + response_key, + operations_credential_identity, .. - } if text(signing_key_identity, 256) && text(response_key_identity, 256) => Ok(()), + } if text(tenant, 128) + && http::HeaderValue::try_from(tenant) + .is_ok_and(|value| value.to_str().is_ok()) + && text(signing_key_identity, 256) + && text(response_key_identity, 256) + && text(operations_credential_identity, 256) + && signing_key_identity != response_key_identity + && signing_key != response_key => + { + signing_key.validate()?; + response_key.validate() + } Self::MifosLegacySignature { .. } => Err(G2pError::Unavailable), } } fn identity(&self) -> Value { match self { - Self::Bearer => serde_json::json!({"type": "bearer"}), + Self::Bearer { + credential_identity, + .. + } => serde_json::json!({ + "type": "bearer", + "credentialIdentity": credential_identity, + }), Self::MifosLegacySignature { + tenant, signing_key_identity, + signing_key, response_key_identity, + response_key, + operations_credential_identity, .. } => serde_json::json!({ "type": "mifos-legacy-signature", + "tenant": tenant, "signingKeyIdentity": signing_key_identity, + "signingKey": signing_key, "responseKeyIdentity": response_key_identity, + "responseKey": response_key, + "operationsCredentialIdentity": operations_credential_identity, }), } } @@ -255,8 +368,6 @@ pub enum G2pProviderBinding { submit_base_url: String, #[cfg_attr(feature = "schema", schemars(with = "registry_platform_yaml::Url"))] status_base_url: String, - credential_identity: String, - credential_ref: SecretReference, auth: G2pHttpAuth, settings: Value, }, @@ -274,8 +385,6 @@ enum G2pProviderBindingWire<'a> { revision: &'a str, submit_base_url: &'a str, status_base_url: &'a str, - credential_identity: &'a str, - credential_ref: &'a SecretReference, auth: &'a G2pHttpAuth, settings: &'a Value, }, @@ -288,16 +397,12 @@ impl Serialize for G2pProviderBinding { revision, submit_base_url, status_base_url, - credential_identity, - credential_ref, auth, settings, } => G2pProviderBindingWire::Http { revision, submit_base_url, status_base_url, - credential_identity, - credential_ref, auth, settings, }, @@ -313,13 +418,11 @@ impl G2pProviderBinding { revision, submit_base_url, status_base_url, - credential_identity, auth, settings, .. } => { if !text(revision, 256) - || !text(credential_identity, 256) || !provider_base_url(submit_base_url) || !provider_base_url(status_base_url) || !non_secret_settings(settings) @@ -339,7 +442,13 @@ impl G2pProviderBinding { pub fn credential_ref(&self) -> &SecretReference { match self { - Self::Http { credential_ref, .. } => credential_ref, + Self::Http { auth, .. } => match auth { + G2pHttpAuth::Bearer { credential_ref, .. } => credential_ref, + G2pHttpAuth::MifosLegacySignature { + operations_credential_ref, + .. + } => operations_credential_ref, + }, } } @@ -380,7 +489,6 @@ impl G2pProviderBinding { revision, submit_base_url, status_base_url, - credential_identity, auth, settings, .. @@ -389,7 +497,6 @@ impl G2pProviderBinding { "revision": revision, "submitOrigin": canonical_origin(submit_base_url)?, "statusOrigin": canonical_origin(status_base_url)?, - "credentialIdentity": credential_identity, "auth": auth.identity(), "settings": settings, })), @@ -1017,6 +1124,14 @@ fn hex_lower(bytes: &[u8]) -> String { output } +fn hex_digit(byte: u8) -> Result { + match byte { + b'0'..=b'9' => Ok(byte - b'0'), + b'a'..=b'f' => Ok(byte - b'a' + 10), + _ => Err(G2pError::Unavailable), + } +} + fn digest_text(value: &str) -> bool { value.len() == 64 && value.bytes().all(|byte| byte.is_ascii_hexdigit()) } diff --git a/crates/registry-adapter/src/payments/g2p_service.rs b/crates/registry-adapter/src/payments/g2p_service.rs index 3d56fb5388..e1530d4e7b 100644 --- a/crates/registry-adapter/src/payments/g2p_service.rs +++ b/crates/registry-adapter/src/payments/g2p_service.rs @@ -4,7 +4,7 @@ use super::{ g2p_model::{ canonical_digest, G2pAttempt, G2pAttemptState, G2pConnectionSnapshot, G2pError, - G2pHttpAuth, G2pProviderBinding, + G2pHttpAuth, G2pProviderBinding, G2pProviderIntent, G2pTransitRsaNoOidKeyBinding, }, g2p_registry::{bind_inputs_for, confirmation_inputs, G2pInstructionState, G2pRegistryPort}, g2p_store::{DispatchAuthorization, G2pStore}, @@ -15,12 +15,17 @@ use super::{ }, }; use async_trait::async_trait; +use base64::{engine::general_purpose::STANDARD, Engine}; +use registry_payment_mifos_connector::{legacy_signature_digest, LegacySignatureHeaders}; use registry_platform_config::SecretResolver; +use registry_platform_crypto::transit_rsa_no_oid::{ + TransitRsaNoOidKeyConfig, TransitRsaNoOidSigner, TransitRsaNoOidVerifier, +}; use registry_platform_httputil::client::BearerToken; use registry_platform_httputil::{read_bounded, validate_response_headers, ServiceBaseUrl}; use serde::Serialize; use serde_json::Value; -use std::{future::Future, pin::Pin, sync::Arc, time::Duration}; +use std::{collections::BTreeMap, future::Future, pin::Pin, sync::Arc, time::Duration}; use uuid::Uuid; #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -62,18 +67,21 @@ pub trait G2pProviderPort: Send + Sync { async fn preflight_submit( &self, binding: &G2pProviderBinding, + intent: &G2pProviderIntent, request: &PreparedProviderRequest, ) -> Result; async fn recover_acceptance( &self, binding: &G2pProviderBinding, + intent: &G2pProviderIntent, request: &PreparedProviderRequest, ) -> Result, G2pProviderError>; async fn observe( &self, binding: &G2pProviderBinding, + intent: &G2pProviderIntent, request: &PreparedProviderRequest, ) -> Result; } @@ -130,31 +138,99 @@ impl G2pMappingPort for PaymentMappingRegistry { } } -/// Provider-neutral HTTP host. Bearer requests send only the exact retained -/// request plan. The Mifos legacy signature remains fail closed until its -/// signer and response verifier are integrated into this boundary. +struct LegacySignatureRuntime { + tenant: String, + signer: Arc, + verifier: Arc, +} + +enum ProviderResponseTrust { + ProviderReport, + SignedBulk(Arc), +} + +/// Provider-neutral HTTP host. It injects only host-owned authentication and +/// correlation headers around the exact retained request bytes. pub struct HttpG2pProvider { resolver: Arc, + signature_runtimes: BTreeMap>, } impl HttpG2pProvider { pub fn new(resolver: Arc) -> Self { - Self { resolver } + Self { + resolver, + signature_runtimes: BTreeMap::new(), + } + } + + pub async fn initialize( + resolver: Arc, + bindings: &[G2pProviderBinding], + ) -> Result { + let mut provider = Self::new(resolver); + for binding in bindings { + binding + .validate() + .map_err(|_| G2pProviderError::Unavailable)?; + let auth = binding.auth(); + if !matches!(auth, G2pHttpAuth::MifosLegacySignature { .. }) { + continue; + } + let identity = canonical_digest(auth).map_err(|_| G2pProviderError::Unavailable)?; + if provider.signature_runtimes.contains_key(&identity) { + continue; + } + provider.signature_runtimes.insert( + identity, + Arc::new(initialize_signature_runtime(auth).await?), + ); + } + Ok(provider) } fn bearer_token(&self, binding: &G2pProviderBinding) -> Result { + if !matches!(binding.auth(), G2pHttpAuth::Bearer { .. }) { + return Err(G2pProviderError::Unavailable); + } + self.resolve_bearer(binding) + } + + fn operations_bearer_token( + &self, + binding: &G2pProviderBinding, + ) -> Result { + if !matches!(binding.auth(), G2pHttpAuth::MifosLegacySignature { .. }) { + return Err(G2pProviderError::Unavailable); + } + self.resolve_bearer(binding) + } + + fn resolve_bearer( + &self, + binding: &G2pProviderBinding, + ) -> Result { let secret = self .resolver .resolve(binding.credential_ref().as_str()) .map_err(|_| G2pProviderError::Unavailable)?; let token = std::str::from_utf8(secret.expose_secret()) .map_err(|_| G2pProviderError::Unavailable)?; - match binding.auth() { - G2pHttpAuth::Bearer => { - BearerToken::new(token.to_owned()).map_err(|_| G2pProviderError::Unavailable) - } - G2pHttpAuth::MifosLegacySignature { .. } => Err(G2pProviderError::Unavailable), + BearerToken::new(token.to_owned()).map_err(|_| G2pProviderError::Unavailable) + } + + async fn signature_runtime( + &self, + binding: &G2pProviderBinding, + ) -> Result, G2pProviderError> { + let identity = + canonical_digest(binding.auth()).map_err(|_| G2pProviderError::Unavailable)?; + if let Some(runtime) = self.signature_runtimes.get(&identity) { + return Ok(runtime.clone()); } + initialize_signature_runtime(binding.auth()) + .await + .map(Arc::new) } fn prepare_url( @@ -182,16 +258,22 @@ impl HttpG2pProvider { Ok(url) } - async fn send_prepared( + async fn send_status( &self, binding: &G2pProviderBinding, + intent: &G2pProviderIntent, prepared: &PreparedProviderRequest, ) -> Result { + if prepared.role != PaymentEndpointRole::DisbursementStatus + || prepared.method != super::provider_mapping::PaymentHttpMethod::Get + || prepared.body.is_some() + { + return Err(G2pProviderError::Unavailable); + } binding .validate() .map_err(|_| G2pProviderError::Unavailable)?; let url = Self::prepare_url(binding, prepared)?; - let token = self.bearer_token(binding)?; let client = registry_platform_httputil::client::build_client( registry_platform_httputil::client::OutboundOptions { request_timeout: Duration::from_secs(15), @@ -206,41 +288,53 @@ impl HttpG2pProvider { super::provider_mapping::PaymentHttpMethod::Get => client.get(url), }; for (name, value) in &prepared.headers { + if host_owned_header(name) { + return Err(G2pProviderError::Unavailable); + } request = request.header(name, value); } - request = request.header( - http::header::AUTHORIZATION, - token.authorization_header_value(), - ); + match binding.auth() { + G2pHttpAuth::Bearer { .. } => { + let token = self.bearer_token(binding)?; + request = request.header( + http::header::AUTHORIZATION, + token.authorization_header_value(), + ); + request = request.header("X-CorrelationID", &intent.correlation_id); + } + G2pHttpAuth::MifosLegacySignature { tenant, .. } => { + let token = self.operations_bearer_token(binding)?; + request = request + .header("Platform-TenantId", tenant) + .header("X-CorrelationID", &intent.correlation_id) + .header( + http::header::AUTHORIZATION, + token.authorization_header_value(), + ); + } + } if let Some(body) = &prepared.body { request = request .header(http::header::CONTENT_TYPE, "application/json") .body(body.clone()); } - let mutation = prepared.role.is_submit(); - let response = request.send().await.map_err(|_| { - if mutation { - G2pProviderError::OutcomeUnknown - } else { - G2pProviderError::Unavailable - } - })?; - validate_response_headers(response.headers()).map_err(|_| { - if mutation { - G2pProviderError::OutcomeUnknown - } else { - G2pProviderError::Unavailable - } - })?; + let response = request + .send() + .await + .map_err(|_| G2pProviderError::Unavailable)?; + validate_response_headers(response.headers()).map_err(|_| G2pProviderError::Unavailable)?; let status = response.status().as_u16(); - let body = read_bounded(response, 131_072).await.map_err(|_| { - if mutation { - G2pProviderError::OutcomeUnknown - } else { - G2pProviderError::Unavailable - } - })?; - Ok(ProviderHttpResponse { status, body }) + let body = read_bounded(response, 131_072) + .await + .map_err(|_| G2pProviderError::Unavailable)?; + finish_provider_response( + status, + body, + None, + ProviderResponseTrust::ProviderReport, + false, + ) + .await } } @@ -249,6 +343,7 @@ impl G2pProviderPort for HttpG2pProvider { async fn preflight_submit( &self, binding: &G2pProviderBinding, + intent: &G2pProviderIntent, request: &PreparedProviderRequest, ) -> Result { binding @@ -258,7 +353,6 @@ impl G2pProviderPort for HttpG2pProvider { return Err(G2pProviderError::Unavailable); } let url = Self::prepare_url(binding, request)?; - let token = self.bearer_token(binding)?; let client = registry_platform_httputil::client::build_client( registry_platform_httputil::client::OutboundOptions { request_timeout: Duration::from_secs(15), @@ -270,13 +364,49 @@ impl G2pProviderPort for HttpG2pProvider { .map_err(|_| G2pProviderError::Unavailable)?; let mut builder = client.post(url); for (name, value) in &request.headers { + if host_owned_header(name) + || (matches!(binding.auth(), G2pHttpAuth::MifosLegacySignature { .. }) + && name.eq_ignore_ascii_case("x-batchid")) + { + return Err(G2pProviderError::Unavailable); + } builder = builder.header(name, value); } - builder = builder.header( - http::header::AUTHORIZATION, - token.authorization_header_value(), - ); let body = request.body.as_ref().ok_or(G2pProviderError::Unavailable)?; + let response_trust = match binding.auth() { + G2pHttpAuth::Bearer { .. } => { + let token = self.bearer_token(binding)?; + builder = builder.header( + http::header::AUTHORIZATION, + token.authorization_header_value(), + ); + builder = builder.header("X-CorrelationID", &intent.correlation_id); + ProviderResponseTrust::ProviderReport + } + G2pHttpAuth::MifosLegacySignature { .. } => { + let runtime = self.signature_runtime(binding).await?; + let digest = legacy_signature_digest( + LegacySignatureHeaders::bulk_request(&intent.correlation_id, &runtime.tenant), + body, + ) + .map_err(|_| G2pProviderError::Unavailable)?; + let signature = runtime + .signer + .sign_digest_hex(digest.as_bytes()) + .await + .map_err(|_| G2pProviderError::Unavailable)?; + let encoded_signature = STANDARD.encode(signature.as_bytes()); + let mut signature_header = + http::HeaderValue::from_bytes(encoded_signature.as_bytes()) + .map_err(|_| G2pProviderError::Unavailable)?; + signature_header.set_sensitive(true); + builder = builder + .header("Platform-TenantId", &runtime.tenant) + .header("X-CorrelationID", &intent.correlation_id) + .header("X-SIGNATURE", signature_header); + ProviderResponseTrust::SignedBulk(runtime) + } + }; let prepared = builder .header(http::header::CONTENT_TYPE, "application/json") .body(body.clone()) @@ -290,16 +420,24 @@ impl G2pProviderPort for HttpG2pProvider { validate_response_headers(response.headers()) .map_err(|_| G2pProviderError::OutcomeUnknown)?; let status = response.status().as_u16(); + let signature = match &response_trust { + ProviderResponseTrust::ProviderReport => None, + ProviderResponseTrust::SignedBulk(runtime) => Some( + signed_response_headers(response.headers(), &runtime.tenant) + .map_err(|_| G2pProviderError::OutcomeUnknown)?, + ), + }; let body = read_bounded(response, 131_072) .await .map_err(|_| G2pProviderError::OutcomeUnknown)?; - Ok(ProviderHttpResponse { status, body }) + finish_provider_response(status, body, signature, response_trust, true).await })) } async fn recover_acceptance( &self, _binding: &G2pProviderBinding, + _intent: &G2pProviderIntent, _request: &PreparedProviderRequest, ) -> Result, G2pProviderError> { Ok(None) @@ -308,15 +446,135 @@ impl G2pProviderPort for HttpG2pProvider { async fn observe( &self, binding: &G2pProviderBinding, + intent: &G2pProviderIntent, request: &PreparedProviderRequest, ) -> Result { if request.role != PaymentEndpointRole::DisbursementStatus { return Err(G2pProviderError::Unavailable); } - self.send_prepared(binding, request).await + self.send_status(binding, intent, request).await } } +async fn initialize_signature_runtime( + auth: &G2pHttpAuth, +) -> Result { + let G2pHttpAuth::MifosLegacySignature { + tenant, + signing_key, + response_key, + .. + } = auth + else { + return Err(G2pProviderError::Unavailable); + }; + let signer = TransitRsaNoOidSigner::initialize(transit_config(signing_key)?) + .await + .map_err(|_| G2pProviderError::Unavailable)?; + let verifier = TransitRsaNoOidVerifier::initialize(transit_config(response_key)?) + .await + .map_err(|_| G2pProviderError::Unavailable)?; + Ok(LegacySignatureRuntime { + tenant: tenant.clone(), + signer: Arc::new(signer), + verifier: Arc::new(verifier), + }) +} + +fn transit_config( + binding: &G2pTransitRsaNoOidKeyBinding, +) -> Result { + TransitRsaNoOidKeyConfig::new( + binding.socket_path.clone(), + binding.mount.clone(), + binding.key.clone(), + binding.version.get(), + binding + .public_key_sha256() + .map_err(|_| G2pProviderError::Unavailable)?, + Duration::from_millis(u64::from(binding.attempt_timeout_milliseconds.get())), + ) + .map_err(|_| G2pProviderError::Unavailable) +} + +fn host_owned_header(name: &str) -> bool { + [ + http::header::AUTHORIZATION.as_str(), + "platform-tenantid", + "x-correlationid", + "x-signature", + ] + .iter() + .any(|protected| name.eq_ignore_ascii_case(protected)) +} + +fn signed_response_headers( + headers: &http::HeaderMap, + expected_tenant: &str, +) -> Result, G2pProviderError> { + let tenants = headers + .get_all("Platform-TenantId") + .iter() + .collect::>(); + let signatures = headers.get_all("X-SIGNATURE").iter().collect::>(); + if tenants.len() != 1 + || signatures.len() != 1 + || tenants[0].as_bytes() != expected_tenant.as_bytes() + { + return Err(G2pProviderError::Unavailable); + } + let encoded = signatures[0] + .to_str() + .map_err(|_| G2pProviderError::Unavailable)?; + let signature = STANDARD + .decode(encoded) + .map_err(|_| G2pProviderError::Unavailable)?; + if STANDARD.encode(&signature) != encoded { + return Err(G2pProviderError::Unavailable); + } + Ok(signature) +} + +async fn verify_response( + runtime: &LegacySignatureRuntime, + body: &[u8], + signature: &[u8], +) -> Result<(), G2pProviderError> { + let digest = legacy_signature_digest(LegacySignatureHeaders::empty(), body) + .map_err(|_| G2pProviderError::Unavailable)?; + runtime + .verifier + .verify_digest_hex(digest.as_bytes(), signature) + .await + .map_err(|_| G2pProviderError::Unavailable) +} + +async fn finish_provider_response( + status: u16, + body: Vec, + signature: Option>, + trust: ProviderResponseTrust, + mutation: bool, +) -> Result { + let failure = || { + if mutation { + G2pProviderError::OutcomeUnknown + } else { + G2pProviderError::Unavailable + } + }; + match (trust, signature) { + (ProviderResponseTrust::ProviderReport, None) => {} + (ProviderResponseTrust::SignedBulk(runtime), Some(signature)) => { + verify_response(&runtime, &body, &signature) + .await + .map_err(|_| failure())?; + } + _ => return Err(failure()), + } + Ok(ProviderHttpResponse { status, body }) +} + pub struct G2pService { store: G2pStore, registry: Arc, @@ -474,7 +732,11 @@ impl G2pService { if attempt.state == G2pAttemptState::DispatchStarted { let recovered = self .provider - .recover_acceptance(&attempt.binding.provider, &attempt.prepared_submit) + .recover_acceptance( + &attempt.binding.provider, + &attempt.provider_intent, + &attempt.prepared_submit, + ) .await .map_err(provider_read_error)?; let Some(accepted) = recovered else { @@ -512,7 +774,11 @@ impl G2pService { .map_err(mapping_read_error)?; let response = self .provider - .observe(&attempt.binding.provider, &status_request) + .observe( + &attempt.binding.provider, + &attempt.provider_intent, + &status_request, + ) .await .map_err(provider_read_error)?; let mapped = mapping @@ -630,7 +896,11 @@ impl G2pService { .map_err(mapping_read_error)?; Some( self.provider - .preflight_submit(&attempt.binding.provider, &attempt.prepared_submit) + .preflight_submit( + &attempt.binding.provider, + &attempt.provider_intent, + &attempt.prepared_submit, + ) .await .map_err(provider_read_error)?, ) @@ -677,7 +947,11 @@ impl G2pService { } let recovered = self .provider - .recover_acceptance(&held.binding.provider, &held.prepared_submit) + .recover_acceptance( + &held.binding.provider, + &held.provider_intent, + &held.prepared_submit, + ) .await .map_err(provider_read_error)?; match recovered { diff --git a/crates/registry-adapter/src/payments/http.rs b/crates/registry-adapter/src/payments/http.rs index 9a3d4a2746..f5fbc32d15 100644 --- a/crates/registry-adapter/src/payments/http.rs +++ b/crates/registry-adapter/src/payments/http.rs @@ -135,7 +135,10 @@ fn mapping_auth_matches( } fn live_disbursement_auth_supported(auth: PaymentProviderAuth) -> bool { - matches!(auth, PaymentProviderAuth::Bearer) + matches!( + auth, + PaymentProviderAuth::Bearer | PaymentProviderAuth::MifosLegacySignature + ) } const MAX_PAYMENT_PROVIDER_PACKS: usize = 32; @@ -294,10 +297,11 @@ pub async fn load_router( } } for connection in &config.disbursements { - for reference in [ + let references = [ connection.binding.provider.credential_ref(), &connection.binding.registry.credential_ref, - ] { + ]; + for reference in references { let value = resolver .resolve(reference.as_str()) .map_err(|_| refused("a payment credential could not be resolved"))?; @@ -333,10 +337,18 @@ pub async fn load_router( .await .map_err(|_| refused("G2P runtime role lacks required table or sequence privileges"))?; } + let g2p_provider_bindings = config + .disbursements + .iter() + .map(|connection| connection.binding.provider.clone()) + .collect::>(); + let g2p_provider = HttpG2pProvider::initialize(resolver.clone(), &g2p_provider_bindings) + .await + .map_err(|_| refused("payment disbursement authentication initialization failed"))?; let g2p = G2pService::new( g2p_store, Arc::new(BregG2pBridge::new(resolver.clone())), - Arc::new(HttpG2pProvider::new(resolver.clone())), + Arc::new(g2p_provider), ); let g2p = if let Some(mapping) = packs.mapping.clone() { g2p.with_mapping(mapping) @@ -958,11 +970,11 @@ mapping: } #[test] - fn startup_refuses_disbursement_auth_without_a_runtime_signer_and_verifier() { + fn startup_accepts_only_authentication_profiles_with_host_implementations() { assert!(live_disbursement_auth_supported( PaymentProviderAuth::Bearer )); - assert!(!live_disbursement_auth_supported( + assert!(live_disbursement_auth_supported( PaymentProviderAuth::MifosLegacySignature )); } diff --git a/crates/registry-adapter/src/payments/provider_mapping.rs b/crates/registry-adapter/src/payments/provider_mapping.rs index eaed3d6f1c..57e5b82ad7 100644 --- a/crates/registry-adapter/src/payments/provider_mapping.rs +++ b/crates/registry-adapter/src/payments/provider_mapping.rs @@ -801,6 +801,7 @@ fn forbidden_header(name: &str) -> bool { | "trailer" | "upgrade" | "x-api-key" + | "x-signature" | "api-key" | "x-auth-token" | "x-access-token" diff --git a/crates/registry-adapter/tests/g2p_model.rs b/crates/registry-adapter/tests/g2p_model.rs index a01f3da096..e940e2565b 100644 --- a/crates/registry-adapter/tests/g2p_model.rs +++ b/crates/registry-adapter/tests/g2p_model.rs @@ -2,7 +2,8 @@ use registry_adapter::payments::g2p_model::{ DisbursementInstruction, G2pAttempt, G2pConnectionSnapshot, G2pError, G2pHttpAuth, - G2pProviderBinding, G2pRegistryBinding, PreparedG2pRegistryAction, + G2pProviderBinding, G2pRegistryBinding, G2pTransitRsaNoOidKeyBinding, + PreparedG2pRegistryAction, }; use registry_adapter::payments::pack::{PaymentProviderAuth, ProviderPackPin}; use registry_adapter::payments::provider_mapping::{ @@ -336,10 +337,14 @@ fn provider_binding_exposes_the_exact_pack_auth_profile() { assert_eq!(provider.auth_profile(), PaymentProviderAuth::Bearer); let G2pProviderBinding::Http { auth, .. } = &mut provider; *auth = G2pHttpAuth::MifosLegacySignature { + tenant: "default".to_owned(), signing_key_identity: "mifos-signing-key".to_owned(), - signing_key_ref: SecretReference::new("secret:env/MIFOS_SIGNING_KEY").unwrap(), + signing_key: transit_key("mifos-request", 7, 'a'), response_key_identity: "mifos-response-key".to_owned(), - response_key_ref: SecretReference::new("secret:env/MIFOS_RESPONSE_KEY").unwrap(), + response_key: transit_key("mifos-response", 4, 'b'), + operations_credential_identity: "mifos-operations-client".to_owned(), + operations_credential_ref: SecretReference::new("secret:env/MIFOS_OPERATIONS_TOKEN") + .unwrap(), }; assert_eq!( provider.auth_profile(), @@ -347,28 +352,181 @@ fn provider_binding_exposes_the_exact_pack_auth_profile() { ); } +#[test] +fn provider_identity_freezes_transit_versions_and_logical_operations_identity() { + let mut first = binding(); + let G2pProviderBinding::Http { auth, .. } = &mut first.provider; + *auth = G2pHttpAuth::MifosLegacySignature { + tenant: "default".to_owned(), + signing_key_identity: "mifos-signing-key".to_owned(), + signing_key: transit_key("mifos-request", 7, 'a'), + response_key_identity: "mifos-response-key".to_owned(), + response_key: transit_key("mifos-response", 4, 'b'), + operations_credential_identity: "mifos-operations-client".to_owned(), + operations_credential_ref: SecretReference::new("secret:env/MIFOS_OPERATIONS_TOKEN") + .unwrap(), + }; + let instruction = instruction(); + let first_correlation = first.provider_intent(&instruction).unwrap().correlation_id; + + let mut rotated_secret = first.clone(); + let G2pProviderBinding::Http { + auth: + G2pHttpAuth::MifosLegacySignature { + operations_credential_ref, + .. + }, + .. + } = &mut rotated_secret.provider + else { + unreachable!() + }; + *operations_credential_ref = + SecretReference::new("secret:env/MIFOS_OPERATIONS_TOKEN_NEXT").unwrap(); + assert_eq!( + rotated_secret + .provider_intent(&instruction) + .unwrap() + .correlation_id, + first_correlation + ); + + let mut new_signing_version = first.clone(); + let G2pProviderBinding::Http { + auth: G2pHttpAuth::MifosLegacySignature { signing_key, .. }, + .. + } = &mut new_signing_version.provider + else { + unreachable!() + }; + *signing_key = transit_key("mifos-request", 8, 'a'); + assert_ne!( + new_signing_version + .provider_intent(&instruction) + .unwrap() + .correlation_id, + first_correlation + ); + + let mut other_operations_identity = first.clone(); + let G2pProviderBinding::Http { + auth: + G2pHttpAuth::MifosLegacySignature { + operations_credential_identity, + .. + }, + .. + } = &mut other_operations_identity.provider + else { + unreachable!() + }; + *operations_credential_identity = "other-operations-client".to_owned(); + assert_ne!( + other_operations_identity + .provider_intent(&instruction) + .unwrap() + .correlation_id, + first_correlation + ); +} + #[test] fn provider_auth_and_binding_use_strict_camel_case_authored_fields() { let signature = json!({ "type": "mifos-legacy-signature", + "tenant": "default", "signingKeyIdentity": "mifos-signing-key", - "signingKeyRef": "secret:env/MIFOS_SIGNING_KEY", + "signingKey": { + "socketPath": "/run/registry/transit.sock", + "mount": "transit", + "key": "mifos-request", + "version": 7, + "publicKeyDigest": format!("sha256:{}", "a".repeat(64)), + "attemptTimeoutMilliseconds": 2000 + }, "responseKeyIdentity": "mifos-response-key", - "responseKeyRef": "secret:env/MIFOS_RESPONSE_KEY" + "responseKey": { + "socketPath": "/run/registry/transit.sock", + "mount": "transit", + "key": "mifos-response", + "version": 4, + "publicKeyDigest": format!("sha256:{}", "b".repeat(64)), + "attemptTimeoutMilliseconds": 2000 + }, + "operationsCredentialIdentity": "mifos-operations-client", + "operationsCredentialRef": "secret:env/MIFOS_OPERATIONS_TOKEN" }); let auth: G2pHttpAuth = serde_json::from_value(signature.clone()).unwrap(); assert_eq!(serde_json::to_value(&auth).unwrap(), signature); + let mut invalid_tenant = signature.clone(); + invalid_tenant["tenant"] = json!("pilot-🙂"); + let invalid_tenant: G2pHttpAuth = serde_json::from_value(invalid_tenant).unwrap(); + assert_eq!(invalid_tenant.validate(), Err(G2pError::Unavailable)); assert!(serde_json::from_value::(json!({ "type": "mifos-legacy-signature", "signing_key_identity": "mifos-signing-key", - "signingKeyRef": "secret:env/MIFOS_SIGNING_KEY", + "tenant": "default", + "signingKey": signature["signingKey"].clone(), "responseKeyIdentity": "mifos-response-key", - "responseKeyRef": "secret:env/MIFOS_RESPONSE_KEY" + "responseKey": signature["responseKey"].clone(), + "operationsCredentialIdentity": "mifos-operations-client", + "operationsCredentialRef": "secret:env/MIFOS_OPERATIONS_TOKEN" })) .is_err()); + + for invalid in [ + json!({ + "type": "mifos-legacy-signature", + "tenant": "default", + "signingKeyIdentity": "same-key", + "signingKey": signature["signingKey"].clone(), + "responseKeyIdentity": "same-key", + "responseKey": signature["responseKey"].clone(), + "operationsCredentialIdentity": "mifos-operations-client", + "operationsCredentialRef": "secret:env/MIFOS_OPERATIONS_TOKEN" + }), + json!({ + "type": "mifos-legacy-signature", + "tenant": "default", + "signingKeyIdentity": "mifos-signing-key", + "signingKey": { + "socketPath": "run/registry/transit.sock", + "mount": "transit", + "key": "mifos-request", + "version": 7, + "publicKeyDigest": format!("sha256:{}", "a".repeat(64)), + "attemptTimeoutMilliseconds": 2000 + }, + "responseKeyIdentity": "mifos-response-key", + "responseKey": signature["responseKey"].clone(), + "operationsCredentialIdentity": "mifos-operations-client", + "operationsCredentialRef": "secret:env/MIFOS_OPERATIONS_TOKEN" + }), + json!({ + "type": "mifos-legacy-signature", + "tenant": "default", + "signingKeyIdentity": "mifos-signing-key", + "signingKey": signature["signingKey"].clone(), + "responseKeyIdentity": "mifos-response-key", + "responseKey": { + "socketPath": "/run/registry/transit.sock", + "mount": "transit", + "key": "mifos-response", + "version": 4, + "publicKeyDigest": format!("sha256:{}", "B".repeat(64)), + "attemptTimeoutMilliseconds": 2000 + }, + "operationsCredentialIdentity": "mifos-operations-client", + "operationsCredentialRef": "secret:env/MIFOS_OPERATIONS_TOKEN" + }), + ] { + if let Ok(auth) = serde_json::from_value::(invalid) { + assert_eq!(auth.validate(), Err(G2pError::Unavailable)); + } + } assert!(serde_json::from_value::(json!({ "type": "bearer", - "credentialRef": "secret:env/NOT_ALLOWED" + "credentialIdentity": "mifos-test-client" })) .is_err()); @@ -376,13 +534,27 @@ fn provider_auth_and_binding_use_strict_camel_case_authored_fields() { let encoded = serde_json::to_value(&provider).unwrap(); assert!(encoded.get("submitBaseUrl").is_some()); assert!(encoded.get("statusBaseUrl").is_some()); - assert!(encoded.get("credentialIdentity").is_some()); - assert!(encoded.get("credentialRef").is_some()); + assert!(encoded.get("credentialIdentity").is_none()); + assert!(encoded.get("credentialRef").is_none()); + assert!(encoded["auth"].get("credentialIdentity").is_some()); + assert!(encoded["auth"].get("credentialRef").is_some()); assert!(encoded.get("submit_base_url").is_none()); let decoded: G2pProviderBinding = serde_json::from_value(encoded).unwrap(); assert_eq!(decoded.auth_profile(), PaymentProviderAuth::Bearer); } +fn transit_key(key: &str, version: u32, digest_digit: char) -> G2pTransitRsaNoOidKeyBinding { + serde_json::from_value(json!({ + "socketPath": "/run/registry/transit.sock", + "mount": "transit", + "key": key, + "version": version, + "publicKeyDigest": format!("sha256:{}", digest_digit.to_string().repeat(64)), + "attemptTimeoutMilliseconds": 2000 + })) + .unwrap() +} + fn instruction() -> DisbursementInstruction { DisbursementInstruction { record_id: Uuid::parse_str("00000000-0000-4000-8000-000000000100").unwrap(), @@ -421,9 +593,10 @@ fn binding() -> G2pConnectionSnapshot { revision: "mifos-test-v1".to_owned(), submit_base_url: "http://127.0.0.1:31002/".to_owned(), status_base_url: "http://127.0.0.1:31003/".to_owned(), - credential_identity: "mifos-test-client".to_owned(), - credential_ref: SecretReference::new("secret:env/MIFOS_TEST_TOKEN").unwrap(), - auth: G2pHttpAuth::Bearer, + auth: G2pHttpAuth::Bearer { + credential_identity: "mifos-test-client".to_owned(), + credential_ref: SecretReference::new("secret:env/MIFOS_TEST_TOKEN").unwrap(), + }, settings: json!({"tenant": "default", "purpose": "GOVERNMENT_TRANSFER"}), }, registry: G2pRegistryBinding { diff --git a/crates/registry-adapter/tests/g2p_postgres.rs b/crates/registry-adapter/tests/g2p_postgres.rs index 6f36e89e39..bb9d11fac1 100644 --- a/crates/registry-adapter/tests/g2p_postgres.rs +++ b/crates/registry-adapter/tests/g2p_postgres.rs @@ -447,9 +447,10 @@ fn attempt_for_registry( revision: "http-test-v1".to_owned(), submit_base_url: "http://127.0.0.1:31002/".to_owned(), status_base_url: "http://127.0.0.1:31003/".to_owned(), - credential_identity: "provider-test-client".to_owned(), - credential_ref: SecretReference::new("secret:env/PROVIDER_TEST_TOKEN").unwrap(), - auth: G2pHttpAuth::Bearer, + auth: G2pHttpAuth::Bearer { + credential_identity: "provider-test-client".to_owned(), + credential_ref: SecretReference::new("secret:env/PROVIDER_TEST_TOKEN").unwrap(), + }, settings: json!({"tenant": "default"}), }, registry, @@ -512,6 +513,7 @@ impl G2pProviderPort for PreflightFailureProvider { async fn preflight_submit( &self, _binding: &G2pProviderBinding, + _intent: ®istry_adapter::payments::g2p_model::G2pProviderIntent, _request: &PreparedProviderRequest, ) -> Result { self.preflights.fetch_add(1, Ordering::SeqCst); @@ -521,6 +523,7 @@ impl G2pProviderPort for PreflightFailureProvider { async fn recover_acceptance( &self, _binding: &G2pProviderBinding, + _intent: ®istry_adapter::payments::g2p_model::G2pProviderIntent, _request: &PreparedProviderRequest, ) -> Result, G2pProviderError> { panic!("preflight failure must not enter recovery") @@ -529,6 +532,7 @@ impl G2pProviderPort for PreflightFailureProvider { async fn observe( &self, _binding: &G2pProviderBinding, + _intent: ®istry_adapter::payments::g2p_model::G2pProviderIntent, _request: &PreparedProviderRequest, ) -> Result { panic!("preflight failure must not observe the provider") diff --git a/crates/registry-adapter/tests/g2p_provider.rs b/crates/registry-adapter/tests/g2p_provider.rs index 9b1d00faac..3066744f1f 100644 --- a/crates/registry-adapter/tests/g2p_provider.rs +++ b/crates/registry-adapter/tests/g2p_provider.rs @@ -1,17 +1,20 @@ // SPDX-License-Identifier: Apache-2.0 use axum::{ - body::Bytes, + body::{Body, Bytes}, extract::State, - http::{HeaderMap, Uri}, + http::{HeaderMap, HeaderValue, StatusCode, Uri}, response::IntoResponse, + response::Response, routing::{get, post}, Router, }; +use base64::{engine::general_purpose::STANDARD, Engine}; use registry_adapter::payments::{ g2p_model::{ DisbursementInstruction, G2pAttempt, G2pConnectionSnapshot, G2pError, G2pHttpAuth, - G2pProviderBinding, G2pRegistryBinding, PreparedG2pRegistryAction, + G2pProviderBinding, G2pRegistryBinding, G2pTransitRsaNoOidKeyBinding, + PreparedG2pRegistryAction, }, g2p_service::{G2pProviderError, G2pProviderPort, HttpG2pProvider}, pack::ProviderPackPin, @@ -21,14 +24,20 @@ use registry_adapter::payments::{ ProviderObservedParty, ProviderPartyRole, }, }; +use registry_payment_mifos_connector::{legacy_signature_digest, LegacySignatureHeaders}; use registry_platform_config::{SecretProvider, SecretResolver}; use registry_platform_yaml::SecretReference; -use serde_json::json; +use serde_json::{json, Value}; use std::{ collections::BTreeMap, os::unix::fs::PermissionsExt, + path::{Path, PathBuf}, sync::{Arc, Mutex}, }; +use tokio::{ + io::{AsyncReadExt, AsyncWriteExt}, + net::UnixListener, +}; use uuid::Uuid; #[derive(Clone, Debug, PartialEq, Eq)] @@ -36,7 +45,9 @@ struct SeenRequest { method: &'static str, path_and_query: String, tenant: Option, - authorization_ok: bool, + correlation_id: Option, + signature: Option, + authorization: Option, body: Vec, } @@ -65,7 +76,13 @@ async fn bearer_http_host_preserves_one_send_and_validates_wire_observations() { SecretResolver::new([SecretProvider::File], secrets.path()).expect("file resolver"), ); let provider = HttpG2pProvider::new(resolver); - let provider_binding = binding(&origin, G2pHttpAuth::Bearer); + let provider_binding = binding( + &origin, + G2pHttpAuth::Bearer { + credential_identity: "second-provider-operator".to_owned(), + credential_ref: SecretReference::new("secret:file/provider-token").unwrap(), + }, + ); let pack = pin(); let instruction = instruction(); let snapshot = snapshot(provider_binding.clone(), pack.clone()); @@ -85,7 +102,7 @@ async fn bearer_http_host_preserves_one_send_and_validates_wire_observations() { body: Some(exact_body.clone()), }; let prepared_send = provider - .preflight_submit(&provider_binding, &submit) + .preflight_submit(&provider_binding, &intent, &submit) .await .unwrap(); let accepted = prepared_send.send().await.unwrap(); @@ -119,7 +136,10 @@ async fn bearer_http_host_preserves_one_send_and_validates_wire_observations() { headers: BTreeMap::new(), body: None, }; - let observed = provider.observe(&provider_binding, &status).await.unwrap(); + let observed = provider + .observe(&provider_binding, &attempt.provider_intent, &status) + .await + .unwrap(); assert_eq!(observed.status, 200); let exact_observation = observation(&attempt.provider_intent.correlation_id); attempt @@ -157,7 +177,9 @@ async fn bearer_http_host_preserves_one_send_and_validates_wire_observations() { method: "POST", path_and_query: "/v2/payouts?channel=benefits".to_owned(), tenant: Some("pilot-beta".to_owned()), - authorization_ok: true, + correlation_id: Some(attempt.provider_intent.correlation_id.clone()), + signature: None, + authorization: Some("Bearer test-only-bearer".to_owned()), body: exact_body, } ); @@ -167,7 +189,9 @@ async fn bearer_http_host_preserves_one_send_and_validates_wire_observations() { method: "GET", path_and_query: "/v2/payouts/provider-001?view=settlement".to_owned(), tenant: None, - authorization_ok: true, + correlation_id: Some(attempt.provider_intent.correlation_id.clone()), + signature: None, + authorization: Some("Bearer test-only-bearer".to_owned()), body: Vec::new(), } ); @@ -176,14 +200,17 @@ async fn bearer_http_host_preserves_one_send_and_validates_wire_observations() { let legacy = binding( &origin, G2pHttpAuth::MifosLegacySignature { + tenant: "pilot-beta".to_owned(), signing_key_identity: "test-signing-key".to_owned(), - signing_key_ref: SecretReference::new("secret:file/signing-key").unwrap(), + signing_key: transit_key("test-signing-key", 7, 'a'), response_key_identity: "test-response-key".to_owned(), - response_key_ref: SecretReference::new("secret:file/response-key").unwrap(), + response_key: transit_key("test-response-key", 4, 'b'), + operations_credential_identity: "test-operations-client".to_owned(), + operations_credential_ref: SecretReference::new("secret:file/provider-token").unwrap(), }, ); assert!(matches!( - provider.preflight_submit(&legacy, &submit).await, + provider.preflight_submit(&legacy, &intent, &submit).await, Err(G2pProviderError::Unavailable) )); assert_eq!(seen.lock().unwrap().len(), 2); @@ -191,7 +218,7 @@ async fn bearer_http_host_preserves_one_send_and_validates_wire_observations() { let mut uncertain = submit.clone(); uncertain.path = "/v2/uncertain".to_owned(); let uncertain_send = provider - .preflight_submit(&provider_binding, &uncertain) + .preflight_submit(&provider_binding, &intent, &uncertain) .await .unwrap(); assert!(matches!( @@ -200,7 +227,7 @@ async fn bearer_http_host_preserves_one_send_and_validates_wire_observations() { )); assert_eq!( provider - .recover_acceptance(&provider_binding, &uncertain) + .recover_acceptance(&provider_binding, &intent, &uncertain) .await .unwrap(), None @@ -217,6 +244,246 @@ async fn bearer_http_host_preserves_one_send_and_validates_wire_observations() { server.abort(); } +#[derive(Clone)] +struct LegacyHttpState { + fixture: Arc, + seen: Arc>>, +} + +#[tokio::test] +async fn mifos_legacy_signature_host_signs_exact_requests_and_verifies_before_mapping() { + let fixture = Arc::new(legacy_fixture()); + let (_transit_directory, socket_path, transit_digests, transit_server) = + spawn_legacy_transit(fixture.clone()); + let seen = Arc::new(Mutex::new(Vec::new())); + let router = Router::new() + .route("/legacy/submit", post(legacy_valid)) + .route("/legacy/status", get(legacy_operations_status)) + .route("/legacy/rs256", post(legacy_rs256)) + .route("/legacy/changed", post(legacy_changed_body)) + .route("/legacy/wrong-tenant", post(legacy_wrong_tenant)) + .route("/legacy/missing-signature", post(legacy_missing_signature)) + .route( + "/legacy/repeated-signature", + post(legacy_repeated_signature), + ) + .route("/legacy/missing-tenant", post(legacy_missing_tenant)) + .route("/legacy/repeated-tenant", post(legacy_repeated_tenant)) + .with_state(LegacyHttpState { + fixture: fixture.clone(), + seen: seen.clone(), + }); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let origin = format!("http://{}/", listener.local_addr().unwrap()); + let http_server = tokio::spawn(async move { + axum::serve(listener, router).await.unwrap(); + }); + + let secret_directory = tempfile::tempdir().unwrap(); + write_secret( + secret_directory.path().join("operations-token"), + b"test-only-operations-bearer", + ); + let resolver = + Arc::new(SecretResolver::new([SecretProvider::File], secret_directory.path()).unwrap()); + let provider_binding = binding( + &origin, + G2pHttpAuth::MifosLegacySignature { + tenant: fixture_text(&fixture, "tenant").to_owned(), + signing_key_identity: "transit:mifos-request:v7".to_owned(), + signing_key: released_transit_key(&socket_path, "mifos-request", &fixture), + response_key_identity: "transit:mifos-response:v7".to_owned(), + response_key: released_transit_key(&socket_path, "mifos-response", &fixture), + operations_credential_identity: "mifos-operations-client".to_owned(), + operations_credential_ref: SecretReference::new("secret:file/operations-token") + .unwrap(), + }, + ); + assert_eq!( + provider_binding.credential_ref().as_str(), + "secret:file/operations-token" + ); + let provider = + HttpG2pProvider::initialize(resolver.clone(), std::slice::from_ref(&provider_binding)) + .await + .unwrap(); + let pack = pin(); + let snapshot = snapshot(provider_binding.clone(), pack.clone()); + let intent = snapshot.provider_intent(&instruction()).unwrap(); + let exact_body = registry_platform_canonical_json::canonicalize_json(&json!({ + "requestId": "batch-request-1", + "correlationId": intent.correlation_id, + "amount": "1000.00" + })) + .unwrap(); + let submit = legacy_request( + pack.clone(), + PaymentEndpointRole::DisbursementSubmit, + PaymentHttpMethod::Post, + "/legacy/submit", + Some(exact_body.clone()), + ); + let retained_preflight = HttpG2pProvider::new(resolver.clone()) + .preflight_submit(&provider_binding, &intent, &submit) + .await + .expect("a retained pre-dispatch binding initializes its exact pinned keys after restart"); + assert!(seen.lock().unwrap().is_empty()); + drop(retained_preflight); + let prepared = provider + .preflight_submit(&provider_binding, &intent, &submit) + .await + .unwrap(); + assert!(seen.lock().unwrap().is_empty()); + let response = prepared.send().await.unwrap(); + assert_eq!(response.status, 202); + assert_eq!(response.body, fixture_text(&fixture, "body").as_bytes()); + + let status = legacy_request( + pack.clone(), + PaymentEndpointRole::DisbursementStatus, + PaymentHttpMethod::Get, + "/legacy/status", + None, + ); + provider + .observe(&provider_binding, &intent, &status) + .await + .unwrap(); + HttpG2pProvider::new(resolver) + .observe(&provider_binding, &intent, &status) + .await + .expect("accepted attempts do not need the retired Bulk signing runtime for status"); + + let rs256 = legacy_request( + pack.clone(), + PaymentEndpointRole::DisbursementSubmit, + PaymentHttpMethod::Post, + "/legacy/rs256", + Some(exact_body.clone()), + ); + let prepared = provider + .preflight_submit(&provider_binding, &intent, &rs256) + .await + .unwrap(); + assert!(matches!( + prepared.send().await, + Err(G2pProviderError::OutcomeUnknown) + )); + + for path in [ + "/legacy/changed", + "/legacy/wrong-tenant", + "/legacy/missing-signature", + "/legacy/repeated-signature", + "/legacy/missing-tenant", + "/legacy/repeated-tenant", + ] { + let request = legacy_request( + pack.clone(), + PaymentEndpointRole::DisbursementSubmit, + PaymentHttpMethod::Post, + path, + Some(exact_body.clone()), + ); + let prepared = provider + .preflight_submit(&provider_binding, &intent, &request) + .await + .unwrap(); + assert!(matches!( + prepared.send().await, + Err(G2pProviderError::OutcomeUnknown) + )); + } + + let request_count = seen.lock().unwrap().len(); + let transit_request_count = transit_digests.lock().unwrap().len(); + let mut mapped_batch_id = submit.clone(); + mapped_batch_id.headers.insert( + "x-batchid".to_owned(), + "mapping-must-not-select-signed-batch-id".to_owned(), + ); + assert!(matches!( + provider + .preflight_submit(&provider_binding, &intent, &mapped_batch_id) + .await, + Err(G2pProviderError::Unavailable) + )); + assert_eq!(transit_digests.lock().unwrap().len(), transit_request_count); + assert_eq!(seen.lock().unwrap().len(), request_count); + + let mut mapped_submit_auth = submit.clone(); + mapped_submit_auth.headers.insert( + "x-signature".to_owned(), + "mapping-must-not-select-signatures".to_owned(), + ); + assert!(matches!( + provider + .preflight_submit(&provider_binding, &intent, &mapped_submit_auth) + .await, + Err(G2pProviderError::Unavailable) + )); + let mut mapped_status_auth = status.clone(); + mapped_status_auth.headers.insert( + "authorization".to_owned(), + "mapping-must-not-select-bearer".to_owned(), + ); + assert!(matches!( + provider + .observe(&provider_binding, &intent, &mapped_status_auth) + .await, + Err(G2pProviderError::Unavailable) + )); + assert_eq!(seen.lock().unwrap().len(), request_count); + + let requests = seen.lock().unwrap(); + assert_eq!(requests.len(), 10); + for request in requests.iter().filter(|request| request.method == "POST") { + assert_eq!(request.tenant.as_deref(), Some("pilot")); + assert_eq!( + request.correlation_id.as_deref(), + Some(intent.correlation_id.as_str()) + ); + assert_eq!( + request.signature.as_deref(), + Some(fixture_text(&fixture, "signatureBase64")) + ); + assert!(request.authorization.is_none()); + } + assert_eq!(requests[1].method, "GET"); + assert_eq!(requests[1].tenant.as_deref(), Some("pilot")); + assert_eq!( + requests[1].correlation_id.as_deref(), + Some(intent.correlation_id.as_str()) + ); + assert!(requests[1].signature.is_none()); + assert_eq!( + requests[1].authorization.as_deref(), + Some("Bearer test-only-operations-bearer") + ); + assert_eq!(requests[2], requests[1]); + assert_eq!(requests[0].body, exact_body); + assert!(requests[1].body.is_empty()); + + let submit_digest = legacy_signature_digest( + LegacySignatureHeaders::bulk_request(&intent.correlation_id, "pilot"), + &requests[0].body, + ) + .unwrap(); + let transit_digests = transit_digests.lock().unwrap(); + assert!(transit_digests + .iter() + .any(|digest| digest == submit_digest.as_str())); + assert!(transit_digests + .iter() + .any(|digest| digest == fixture_text(&fixture, "bodyOnlySha3Hex"))); + assert!(!transit_digests + .iter() + .any(|digest| digest == fixture_text(&fixture, "uppercaseSha3Hex"))); + + http_server.abort(); + transit_server.abort(); +} + async fn capture_submit( State(seen): State>>>, uri: Uri, @@ -247,6 +514,162 @@ async fn capture_uncertain( vec![b'x'; 131_073] } +async fn legacy_valid( + State(state): State, + uri: Uri, + headers: HeaderMap, + body: Bytes, +) -> Response { + capture(&state.seen, "POST", uri, headers, body); + legacy_response( + StatusCode::ACCEPTED, + fixture_text(&state.fixture, "body"), + &["pilot"], + &[fixture_text(&state.fixture, "signatureBase64")], + ) +} + +async fn legacy_operations_status( + State(state): State, + uri: Uri, + headers: HeaderMap, + body: Bytes, +) -> Response { + capture(&state.seen, "GET", uri, headers, body); + let mut response = Response::new(Body::from(fixture_text(&state.fixture, "body").to_owned())); + *response.status_mut() = StatusCode::OK; + response +} + +async fn legacy_rs256( + State(state): State, + uri: Uri, + headers: HeaderMap, + body: Bytes, +) -> Response { + capture(&state.seen, "POST", uri, headers, body); + legacy_response( + StatusCode::BAD_REQUEST, + fixture_text(&state.fixture, "body"), + &["pilot"], + &[fixture_text(&state.fixture, "rs256SignatureBase64")], + ) +} + +async fn legacy_changed_body( + State(state): State, + uri: Uri, + headers: HeaderMap, + body: Bytes, +) -> Response { + capture(&state.seen, "POST", uri, headers, body); + legacy_response( + StatusCode::OK, + fixture_text(&state.fixture, "changedBody"), + &["pilot"], + &[fixture_text(&state.fixture, "signatureBase64")], + ) +} + +async fn legacy_wrong_tenant( + State(state): State, + uri: Uri, + headers: HeaderMap, + body: Bytes, +) -> Response { + capture(&state.seen, "POST", uri, headers, body); + legacy_response( + StatusCode::OK, + fixture_text(&state.fixture, "body"), + &["other"], + &[fixture_text(&state.fixture, "signatureBase64")], + ) +} + +async fn legacy_missing_signature( + State(state): State, + uri: Uri, + headers: HeaderMap, + body: Bytes, +) -> Response { + capture(&state.seen, "POST", uri, headers, body); + legacy_response( + StatusCode::OK, + fixture_text(&state.fixture, "body"), + &["pilot"], + &[], + ) +} + +async fn legacy_repeated_signature( + State(state): State, + uri: Uri, + headers: HeaderMap, + body: Bytes, +) -> Response { + capture(&state.seen, "POST", uri, headers, body); + legacy_response( + StatusCode::OK, + fixture_text(&state.fixture, "body"), + &["pilot"], + &[ + fixture_text(&state.fixture, "signatureBase64"), + fixture_text(&state.fixture, "signatureBase64"), + ], + ) +} + +async fn legacy_missing_tenant( + State(state): State, + uri: Uri, + headers: HeaderMap, + body: Bytes, +) -> Response { + capture(&state.seen, "POST", uri, headers, body); + legacy_response( + StatusCode::OK, + fixture_text(&state.fixture, "body"), + &[], + &[fixture_text(&state.fixture, "signatureBase64")], + ) +} + +async fn legacy_repeated_tenant( + State(state): State, + uri: Uri, + headers: HeaderMap, + body: Bytes, +) -> Response { + capture(&state.seen, "POST", uri, headers, body); + legacy_response( + StatusCode::OK, + fixture_text(&state.fixture, "body"), + &["pilot", "pilot"], + &[fixture_text(&state.fixture, "signatureBase64")], + ) +} + +fn legacy_response( + status: StatusCode, + body: &str, + tenants: &[&str], + signatures: &[&str], +) -> Response { + let mut response = Response::new(Body::from(body.to_owned())); + *response.status_mut() = status; + for tenant in tenants { + response + .headers_mut() + .append("Platform-TenantId", HeaderValue::from_str(tenant).unwrap()); + } + for signature in signatures { + response + .headers_mut() + .append("X-SIGNATURE", HeaderValue::from_str(signature).unwrap()); + } + response +} + fn capture( seen: &Mutex>, method: &'static str, @@ -263,27 +686,242 @@ fn capture( .to_owned(), tenant: headers .get("x-provider-tenant") + .or_else(|| headers.get("platform-tenantid")) + .and_then(|value| value.to_str().ok()) + .map(str::to_owned), + correlation_id: headers + .get("x-correlationid") .and_then(|value| value.to_str().ok()) .map(str::to_owned), - authorization_ok: headers + signature: headers + .get("x-signature") + .and_then(|value| value.to_str().ok()) + .map(str::to_owned), + authorization: headers .get(axum::http::header::AUTHORIZATION) - .is_some_and(|value| value.as_bytes() == b"Bearer test-only-bearer"), + .and_then(|value| value.to_str().ok()) + .map(str::to_owned), body: body.to_vec(), }); } +fn legacy_request( + provider_pack: ProviderPackPin, + role: PaymentEndpointRole, + method: PaymentHttpMethod, + path: &str, + body: Option>, +) -> PreparedProviderRequest { + PreparedProviderRequest { + provider_pack, + role, + method, + path: path.to_owned(), + query: BTreeMap::new(), + headers: BTreeMap::new(), + body, + } +} + +fn legacy_fixture() -> Value { + serde_json::from_str(include_str!( + "../../registry-platform-crypto/tests/fixtures/mifos-bulk-v1.12.1-response-signatures.json" + )) + .unwrap() +} + +fn fixture_text<'a>(fixture: &'a Value, key: &str) -> &'a str { + fixture[key].as_str().unwrap() +} + +fn released_transit_key( + socket_path: &Path, + key: &str, + fixture: &Value, +) -> G2pTransitRsaNoOidKeyBinding { + serde_json::from_value(json!({ + "socketPath": socket_path, + "mount": "transit", + "key": key, + "version": 7, + "publicKeyDigest": format!("sha256:{}", fixture_text(fixture, "publicKeySpkiSha256")), + "attemptTimeoutMilliseconds": 2000 + })) + .unwrap() +} + +fn public_key_pem(encoded: &str) -> String { + let mut pem = String::from("-----BEGIN PUBLIC KEY-----\n"); + for line in encoded.as_bytes().chunks(64) { + pem.push_str(std::str::from_utf8(line).unwrap()); + pem.push('\n'); + } + pem.push_str("-----END PUBLIC KEY-----\n"); + pem +} + +fn spawn_legacy_transit( + fixture: Arc, +) -> ( + tempfile::TempDir, + PathBuf, + Arc>>, + tokio::task::JoinHandle<()>, +) { + let directory = tempfile::tempdir().unwrap(); + let socket_path = directory.path().join("transit.sock"); + let listener = UnixListener::bind(&socket_path).unwrap(); + let digests = Arc::new(Mutex::new(Vec::new())); + let observed = digests.clone(); + let task = tokio::spawn(async move { + loop { + let (mut stream, _) = listener.accept().await.unwrap(); + let fixture = fixture.clone(); + let observed = observed.clone(); + tokio::spawn(async move { + let (method, path, body) = read_transit_request(&mut stream).await; + let response = match (method.as_str(), path.as_str()) { + ("GET", "/v1/transit/keys/mifos-request") => transit_metadata(&fixture, false), + ("GET", "/v1/transit/keys/mifos-response") => transit_metadata(&fixture, true), + ("POST", "/v1/transit/sign/mifos-request/none") => { + let document: Value = serde_json::from_slice(&body).unwrap(); + assert_eq!(document["key_version"], 7); + assert_eq!(document["prehashed"], true); + assert_eq!(document["signature_algorithm"], "pkcs1v15"); + let digest = transit_digest(&document); + observed.lock().unwrap().push(digest); + json!({"data": {"signature": format!( + "vault:v7:{}", + fixture_text(&fixture, "signatureBase64") + )}}) + } + ("POST", path) if path.starts_with("/v1/transit/verify/") => { + let document: Value = serde_json::from_slice(&body).unwrap(); + assert_eq!(document["prehashed"], true); + assert_eq!(document["signature_algorithm"], "pkcs1v15"); + let digest = transit_digest(&document); + observed.lock().unwrap().push(digest.clone()); + let encoded = document["signature"] + .as_str() + .unwrap() + .strip_prefix("vault:v7:") + .unwrap(); + let candidate = STANDARD.decode(encoded).unwrap(); + let valid = if path.contains("mifos-response") { + digest == fixture_text(&fixture, "bodyOnlySha3Hex") + && encoded == fixture_text(&fixture, "signatureBase64") + } else { + candidate.iter().any(|byte| *byte != 0) + }; + json!({"data": {"valid": valid}}) + } + _ => panic!("unexpected Transit request {method} {path}"), + }; + write_transit_response(&mut stream, &response).await; + }); + } + }); + (directory, socket_path, digests, task) +} + +fn transit_metadata(fixture: &Value, imported_key: bool) -> Value { + json!({ + "data": { + "type": "rsa-2048", + "derived": false, + "exportable": false, + "allow_plaintext_backup": false, + "supports_signing": true, + "latest_version": 7, + "min_encryption_version": 1, + "min_decryption_version": 1, + "imported_key": imported_key, + "keys": {"7": {"public_key": public_key_pem(fixture_text(fixture, "publicKeySpkiBase64"))}} + } + }) +} + +fn transit_digest(document: &Value) -> String { + let decoded = STANDARD + .decode(document["input"].as_str().unwrap()) + .unwrap(); + let digest = String::from_utf8(decoded).unwrap(); + assert_eq!(digest.len(), 64); + assert!(digest + .bytes() + .all(|byte| byte.is_ascii_digit() || matches!(byte, b'a'..=b'f'))); + digest +} + +async fn read_transit_request(stream: &mut tokio::net::UnixStream) -> (String, String, Vec) { + let mut request = Vec::new(); + let header_end = loop { + let mut chunk = [0_u8; 4096]; + let read = stream.read(&mut chunk).await.unwrap(); + assert_ne!(read, 0); + request.extend_from_slice(&chunk[..read]); + if let Some(position) = request.windows(4).position(|bytes| bytes == b"\r\n\r\n") { + break position + 4; + } + }; + let headers = std::str::from_utf8(&request[..header_end]).unwrap(); + assert!(headers + .to_ascii_lowercase() + .contains("x-vault-request: true")); + let mut lines = headers.lines(); + let mut request_line = lines.next().unwrap().split_whitespace(); + let method = request_line.next().unwrap().to_owned(); + let path = request_line.next().unwrap().to_owned(); + let content_length = lines + .filter_map(|line| line.split_once(':')) + .find(|(name, _)| name.eq_ignore_ascii_case("content-length")) + .map(|(_, value)| value.trim().parse::().unwrap()) + .unwrap_or(0); + while request.len() < header_end + content_length { + let mut chunk = [0_u8; 4096]; + let read = stream.read(&mut chunk).await.unwrap(); + assert_ne!(read, 0); + request.extend_from_slice(&chunk[..read]); + } + ( + method, + path, + request[header_end..header_end + content_length].to_vec(), + ) +} + +async fn write_transit_response(stream: &mut tokio::net::UnixStream, response: &Value) { + let body = serde_json::to_vec(response).unwrap(); + let headers = format!( + "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", + body.len() + ); + stream.write_all(headers.as_bytes()).await.unwrap(); + stream.write_all(&body).await.unwrap(); +} + fn binding(origin: &str, auth: G2pHttpAuth) -> G2pProviderBinding { G2pProviderBinding::Http { revision: "second-provider-v1".to_owned(), submit_base_url: origin.to_owned(), status_base_url: origin.to_owned(), - credential_identity: "second-provider-operator".to_owned(), - credential_ref: SecretReference::new("secret:file/provider-token").unwrap(), auth, settings: json!({"tenant": "pilot-beta"}), } } +fn transit_key(key: &str, version: u32, digest_digit: char) -> G2pTransitRsaNoOidKeyBinding { + serde_json::from_value(json!({ + "socketPath": "/run/registry/transit.sock", + "mount": "transit", + "key": key, + "version": version, + "publicKeyDigest": format!("sha256:{}", digest_digit.to_string().repeat(64)), + "attemptTimeoutMilliseconds": 2000 + })) + .unwrap() +} + fn pin() -> ProviderPackPin { ProviderPackPin { id: "second-provider".to_owned(), diff --git a/crates/registry-adapter/tests/payment_provider_mapping.rs b/crates/registry-adapter/tests/payment_provider_mapping.rs index 7477b9ab5a..c2222d489a 100644 --- a/crates/registry-adapter/tests/payment_provider_mapping.rs +++ b/crates/registry-adapter/tests/payment_provider_mapping.rs @@ -549,6 +549,8 @@ fn response(intent, settings, acceptance, response) { "#; for header in [ "authorization", + "x-signature", + "X-SIGNATURE", "x-http-method-override", "x-method-override", "x-original-url", diff --git a/crates/registry-adapterctl/tests/payments.rs b/crates/registry-adapterctl/tests/payments.rs index 1c901dde4a..0f85e8bc3e 100644 --- a/crates/registry-adapterctl/tests/payments.rs +++ b/crates/registry-adapterctl/tests/payments.rs @@ -449,3 +449,86 @@ fn payment_check_refuses_ambiguous_multi_pack_fixture_replay() { "adapter.payment.fixture-pack-ambiguous" ); } + +fn collection_example() -> String { + std::fs::read_to_string( + PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("../../products/adapter/examples/payment-collections/payments.example.yaml"), + ) + .unwrap() +} + +#[test] +fn payment_check_counts_collection_and_disbursement_connections() { + let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("../../products/adapter/examples/payment-collections/payments.mifos.example.yaml"); + let mut stdout = Vec::new(); + let mut stderr = Vec::new(); + let code = registry_adapterctl::main_entry_from( + [ + "adapterctl", + "--format", + "json", + "payments", + "check", + path.to_str().unwrap(), + ], + &mut stdout, + &mut stderr, + ); + assert_eq!(code, ExitCode::from(1)); + let report: serde_json::Value = serde_json::from_slice(&stdout).unwrap(); + assert_eq!(report["connectionCount"], 2); + assert!(report["diagnostics"] + .as_array() + .unwrap() + .iter() + .any(|diagnostic| diagnostic["code"] == "adapter.payment.provider-pack-required")); + assert!(stderr.is_empty()); +} + +#[test] +fn payment_check_skips_an_unpinned_synthetic_connection_when_a_pack_is_supplied() { + let directory = tempfile::tempdir().unwrap(); + let pack_file = directory.path().join("pack.yaml"); + let pack = "apiVersion: id.registrystack.org/formats/adapter/payment-provider-pack/v1alpha1\nkind: AdapterPaymentProviderPack\nid: simulator\nversion: '1'\nconnector: simulator-p2g/v1\ncapabilities: [collection]\n"; + std::fs::write(&pack_file, pack).unwrap(); + let pinned = collection_example().replacen( + " binding:\n", + &format!( + " binding:\n providerPack: {{id: simulator, version: '1', digest: {}}}\n", + registry_platform_config::sha256_uri(pack.as_bytes()) + ), + 1, + ); + let synthetic = collection_example() + .split_once("connections:\n") + .unwrap() + .1 + .replace("licence-fees", "other-fees") + .replace("licence-issuance", "other-service") + .replace("coordinator-payments", "other-coordinator"); + let file = directory.path().join("payments.yaml"); + std::fs::write(&file, format!("{pinned}\n{synthetic}")).unwrap(); + let mut stdout = Vec::new(); + let mut stderr = Vec::new(); + let code = registry_adapterctl::main_entry_from( + [ + "adapterctl", + "--format", + "json", + "payments", + "check", + file.to_str().unwrap(), + "--provider-pack", + pack_file.to_str().unwrap(), + ], + &mut stdout, + &mut stderr, + ); + let report: serde_json::Value = serde_json::from_slice(&stdout).unwrap(); + assert_eq!(code, ExitCode::SUCCESS, "{report}"); + assert_eq!(report["connectionCount"], 2); + assert_eq!(report["diagnostics"], serde_json::json!([])); + assert!(stderr.is_empty()); +} diff --git a/products/adapter/README.md b/products/adapter/README.md index c114f7bb7d..223907d504 100644 --- a/products/adapter/README.md +++ b/products/adapter/README.md @@ -17,11 +17,25 @@ reads an authoritative [BReg instruction](../breg/examples/g2p-disbursement/READ Operator configuration binds restricted registry Actions and an exact provider pack. The host fixes credentials, origins and mutation methods while the pack maps the provider's wire shape. The simulator remains synthetic. The Mifos -Payment Hub EE pack is a candidate: its released bulk signature is not yet -implemented by the host, so a direct Mifos G2P connection is refused at -startup before any instruction is bound. Mifos Operations completion is a -provider report and does not authorize a paid -fee-bill receipt. +Payment Hub EE disbursement host signs exact retained Bulk requests through a +pinned Transit RSA key and verifies the released body-only Bulk response +signature with a separate pinned public key. Status reads use a distinct +operator-owned bearer credential against the configured HTTPS Operations +origin. Released Operations v1.17.1 does not enable route authorization by +default, so the deployment must enable and verify bearer authorization or +enforce it at a trusted gateway. Its unsigned status body remains a provider +report: the host independently compares its correlation, amount, currency, +funding party and recipient with the authoritative BReg instruction before +reporting confirmation. A missing Bulk response leaves the original send held +for operator or provider reconciliation because no accepted batch reference +exists for an Operations lookup; the host never submits it again. Mifos +Operations completion does not authorize a paid fee-bill receipt. + +The Transit Unix socket must be an absolute local path protected by deployment +ACLs and a trusted proxy policy. Adapter pins the mount, key name, version and +SPKI SHA-256 digest for separate signing and response-verification keys. The +repository's fake Transit regression checks the wire contract, but does not +establish live OpenBao `/none` plus `prehashed` interoperability. For a provider pack upgrade, repeat `--payment-provider-pack` with the current pack and every retained pack still needed by an unfinished attempt. The host diff --git a/products/adapter/examples/payment-collections/README.md b/products/adapter/examples/payment-collections/README.md index 2d6b067c0e..f53e4aa773 100644 --- a/products/adapter/examples/payment-collections/README.md +++ b/products/adapter/examples/payment-collections/README.md @@ -1,11 +1,14 @@ -# Synthetic payment collection +# Payment collection and G2P configuration -This source example combines the Adapter payment host with the maintained +The baseline `payments.example.yaml` combines the Adapter payment host with the maintained [service-fee BReg project](../../../breg/examples/payment-fee-issuance/README.md). The first provider is the repository's [P2G simulator](../../../../tools/payment-simulator/README.md). It does not accept real payments or claim general GovStack Payments conformance. The [contract and capability comparison](CONTRACT.md) names the exact HTTP surface, ownership and differences from the earlier composition capability. +The separate `payments.mifos.example.yaml` adds an authoritative G2P +disbursement connection pinned to the public `mifos-payment-hub` pack. It is +an operator configuration example, not evidence of a live Mifos deployment. A service creates the authoritative bill. The Coordinator workflow then uses native payment operations: @@ -27,10 +30,12 @@ and [connection setup](../../../coordinator/DEPLOYMENT.md). ## Bind the connection Copy `payments.example.yaml` and `runtime.example.yaml` into the operator's -configuration directory. `payments.yaml` binds the service to one provider -tenant/biller and one registry. Its caller policy must agree with the shared -runtime's OIDC issuer, audience and admitted clients. Its currency and scale -must agree with the authoritative bill. +configuration directory for the simulator-only baseline. Copy +`payments.mifos.example.yaml` instead when configuring the mixed P2G and G2P +deployment. The resulting `payments.yaml` binds each service to its provider +and registry. Its caller policy must agree with the shared runtime's OIDC +issuer, audience and admitted clients. Its currency and scale must agree with +the authoritative bill or disbursement instruction. The provider token identifies the synthetic producer. The BReg token belongs to `payment-adapter`, with `registry:payment-attempt:bind` and @@ -41,13 +46,36 @@ renew externally supplied bearer tokens at those references; the host resolves them on each exchange. Rotation must preserve the original logical provider or registry identity. +The disbursement binding separates the two released Mifos roles. Bulk POSTs +carry no bearer token: Adapter signs the exact retained body, tenant and +correlation through the configured Transit key, then verifies the signed Bulk +response through the distinct response key. Operations GETs carry the separate +`operationsCredentialRef` bearer token and host-owned tenant and correlation +headers. Released Operations v1.17.1 permits `/api/v1/**` by default unless +route authorization is enabled, so the deployment must enable and verify +bearer authorization or enforce it at a trusted gateway. The status response +is not signed; Adapter treats it only as a bounded provider report and compares +its batch, correlation, amount, currency, funding party and recipient with the +retained BReg instruction before reporting confirmation. + +Replace the example Transit SPKI digests, key versions, key names, socket path, +origins and secret references with deployment-owned values. The socket must be +an absolute local Unix socket protected by ACLs and a trusted proxy policy. +The host validates the pinned key metadata at startup and never receives +private key bytes. Repository tests use a fake Transit endpoint and do not +establish live OpenBao `/none` plus `prehashed` interoperability. + Build matching `adapter` and `adapterctl` binaries from this checkout, using the repository's external Cargo target directory. Check the configuration -without resolving credentials or contacting a provider: +against the exact pack pinned in `providerPack`, without resolving credentials +or contacting a provider. The pack path must contain bytes whose id, version +and digest match that pin: ```sh -adapterctl payments check /absolute/path/payments.yaml -adapterctl --format json payments contract /absolute/path/payments.yaml +adapterctl payments check /absolute/path/payments.mifos.yaml \ + --provider-pack /absolute/path/mifos-payment-hub/pack.yaml +adapterctl --format json payments contract /absolute/path/payments.mifos.yaml \ + --provider-pack /absolute/path/mifos-payment-hub/pack.yaml ``` Start the payment-only host with the configured PostgreSQL and OIDC service: @@ -93,6 +121,13 @@ and connection revision. Recovery may resend only inside the original replay window. After that window, the attempt remains held. A changed connection config applies to new attempts; it does not redirect retained ones. +G2P Bulk sends are never replayed. If the first response is lost, the attempt +stays held because no accepted batch reference exists for the Operations +status query. An operator must reconcile it with the provider; an unknown send +cannot become a failure or authorize a fresh submission. After a signed Bulk +acceptance supplies the retained batch reference, status recovery is read-only +through the Operations bearer path. + The host persists bind and receipt commands before sending them. A lost BReg acknowledgement is recovered through the same command/key or exact bill and receipt readback. A paid flag alone is insufficient. Every lookup remains diff --git a/products/adapter/examples/payment-collections/payments.mifos.example.yaml b/products/adapter/examples/payment-collections/payments.mifos.example.yaml new file mode 100644 index 0000000000..db61ed22be --- /dev/null +++ b/products/adapter/examples/payment-collections/payments.mifos.example.yaml @@ -0,0 +1,99 @@ +# yaml-language-server: $schema=https://id.registrystack.org/schemas/adapter/payments/payments.v1alpha1.schema.json +apiVersion: id.registrystack.org/formats/adapter/payments/v1alpha1 +kind: AdapterPayments +connections: + - id: licence-fees + institutionId: institution-a + serviceId: licence-issuance + allowedClients: [coordinator-payments] + requiredScope: payments:collect + binding: + simulation: true + currency: USD + currencyScale: 2 + providerCredentialRef: secret:env/PAYMENT_SIMULATOR_TOKEN + providerCredentialIdentity: registry + # The simulator retains commands in its database. The host permits + # recovery sends for only this bounded window after the first dispatch. + replayWindowSeconds: 3600 + provider: + type: simulator + connection: + baseUrl: http://127.0.0.1:8099/ + tenant: pilot + biller: ministry + billerName: Ministry + callbackUrl: https://programme.example.test/callback + payerFiBic: SIMBANK + registry: + baseUrl: http://127.0.0.1:8080/ + recordType: service-fee-bill + recordRoute: service-fee-bills + readProfile: payment-adapter-reporter + bindProfile: payment-adapter-binder + receiptProfile: payment-adapter-reporter + bindAction: bind-payment-attempt + receiptAction: record-payment-receipt + credentialRef: secret:env/PAYMENT_ADAPTER_BREG_TOKEN + credentialIdentity: payment-adapter +disbursements: + - id: cash-transfers + allowedClients: [coordinator-g2p] + requiredScope: payments:disburse + binding: + institutionId: ministry-social-protection + serviceId: cash-transfer + programmeId: cash-programme + fundingAccountId: programme-account + currency: KES + currencyScale: 2 + providerPack: + id: mifos-payment-hub + version: '1' + digest: sha256:2130ab2942bb7acc3929ab670099f28d714e0a885e2b866844b0f655cfeb7978 + fundingPartyKey: ACCOUNT_ID + recipientPartyKey: MSISDN + provider: + type: http + revision: mifos-bulk-v1.12.1-operations-v1.17.1 + submitBaseUrl: https://mifos-bulk.example.test/ + statusBaseUrl: https://mifos-operations.example.test/ + auth: + type: mifos-legacy-signature + tenant: pilot + signingKeyIdentity: transit:mifos-bulk-request:v7 + signingKey: + socketPath: /run/registry-adapter/transit.sock + mount: transit + key: mifos-bulk-request + version: 7 + publicKeyDigest: sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa + attemptTimeoutMilliseconds: 2000 + responseKeyIdentity: transit:mifos-bulk-response:v4 + responseKey: + socketPath: /run/registry-adapter/transit.sock + mount: transit + key: mifos-bulk-response + version: 4 + publicKeyDigest: sha256:bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb + attemptTimeoutMilliseconds: 2000 + operationsCredentialIdentity: mifos-operations-client + operationsCredentialRef: secret:env/MIFOS_OPERATIONS_TOKEN + settings: + tenant: pilot + fundingPartyKey: ACCOUNT_ID + recipientPartyKey: MSISDN + purpose: GOVERNMENT_TRANSFER + subType: BENEFIT + descriptionText: Social protection disbursement + registry: + baseUrl: https://breg.example.test/ + credentialIdentity: g2p-payment-adapter + credentialRef: secret:env/G2P_PAYMENT_ADAPTER_BREG_TOKEN + recordRoute: disbursement-instructions + recordType: disbursement-instruction + readProfile: g2p-adapter-read + bindAction: bind-payout-attempt + bindProfile: g2p-adapter-bind + reportAction: record-provider-confirmation + reportProfile: g2p-adapter-report diff --git a/products/adapter/schemas/payments.v1alpha1.schema.json b/products/adapter/schemas/payments.v1alpha1.schema.json index 7ea46ef5ab..036f22f45d 100644 --- a/products/adapter/schemas/payments.v1alpha1.schema.json +++ b/products/adapter/schemas/payments.v1alpha1.schema.json @@ -165,30 +165,47 @@ { "additionalProperties": false, "properties": { + "credentialIdentity": { + "type": "string" + }, + "credentialRef": { + "$ref": "#/$defs/SecretReference" + }, "type": { "const": "bearer", "type": "string" } }, "required": [ - "type" + "type", + "credentialIdentity", + "credentialRef" ], "type": "object" }, { "additionalProperties": false, "properties": { - "responseKeyIdentity": { + "operationsCredentialIdentity": { "type": "string" }, - "responseKeyRef": { + "operationsCredentialRef": { "$ref": "#/$defs/SecretReference" }, + "responseKey": { + "$ref": "#/$defs/G2pTransitRsaNoOidKeyBinding" + }, + "responseKeyIdentity": { + "type": "string" + }, + "signingKey": { + "$ref": "#/$defs/G2pTransitRsaNoOidKeyBinding" + }, "signingKeyIdentity": { "type": "string" }, - "signingKeyRef": { - "$ref": "#/$defs/SecretReference" + "tenant": { + "type": "string" }, "type": { "const": "mifos-legacy-signature", @@ -197,10 +214,13 @@ }, "required": [ "type", + "tenant", "signingKeyIdentity", - "signingKeyRef", + "signingKey", "responseKeyIdentity", - "responseKeyRef" + "responseKey", + "operationsCredentialIdentity", + "operationsCredentialRef" ], "type": "object" } @@ -215,12 +235,6 @@ "auth": { "$ref": "#/$defs/G2pHttpAuth" }, - "credentialIdentity": { - "type": "string" - }, - "credentialRef": { - "$ref": "#/$defs/SecretReference" - }, "revision": { "type": "string" }, @@ -241,8 +255,6 @@ "revision", "submitBaseUrl", "statusBaseUrl", - "credentialIdentity", - "credentialRef", "auth", "settings" ], @@ -299,6 +311,45 @@ ], "type": "object" }, + "G2pTransitRsaNoOidKeyBinding": { + "additionalProperties": false, + "description": "Exact Transit RSA key version and SPKI identity retained with an attempt.\nPrivate key bytes never enter Adapter configuration or durable custody.", + "properties": { + "attemptTimeoutMilliseconds": { + "format": "uint32", + "maximum": 30000, + "minimum": 1, + "type": "integer" + }, + "key": { + "type": "string" + }, + "mount": { + "type": "string" + }, + "publicKeyDigest": { + "$ref": "#/$defs/Digest" + }, + "socketPath": { + "type": "string" + }, + "version": { + "format": "uint32", + "maximum": 2147483647, + "minimum": 1, + "type": "integer" + } + }, + "required": [ + "socketPath", + "mount", + "key", + "version", + "publicKeyDigest", + "attemptTimeoutMilliseconds" + ], + "type": "object" + }, "LocalId": { "description": "A local identifier: a lowercase letter, then up to 63 lowercase letters, digits, `_`, or `-`.", "pattern": "^[a-z][a-z0-9_-]{0,63}$", diff --git a/products/platform/config-formats.yaml b/products/platform/config-formats.yaml index 114484c325..6ebbfa255c 100644 --- a/products/platform/config-formats.yaml +++ b/products/platform/config-formats.yaml @@ -4647,7 +4647,53 @@ formats: - {pointer: /connections/*/binding/registry/receiptProfile, whenOmitted: refused} - {pointer: /connections/*/binding/registry/bindAction, whenOmitted: refused} - {pointer: /connections/*/binding/registry/receiptAction, whenOmitted: refused} - restrictingMembers: [/connections/*/allowedClients, /connections/*/requiredScope, /connections/*/institutionId, /connections/*/serviceId, /connections/*/binding/simulation] + - {pointer: /disbursements, whenOmitted: closed} + - {pointer: /disbursements/*/allowedClients, whenOmitted: refused} + - {pointer: /disbursements/*/requiredScope, whenOmitted: refused} + - {pointer: /disbursements/*/binding/institutionId, whenOmitted: refused} + - {pointer: /disbursements/*/binding/serviceId, whenOmitted: refused} + - {pointer: /disbursements/*/binding/programmeId, whenOmitted: refused} + - {pointer: /disbursements/*/binding/fundingAccountId, whenOmitted: refused} + - {pointer: /disbursements/*/binding/currency, whenOmitted: refused} + - {pointer: /disbursements/*/binding/currencyScale, whenOmitted: refused} + - {pointer: /disbursements/*/binding/providerPack, whenOmitted: refused} + - {pointer: /disbursements/*/binding/fundingPartyKey, whenOmitted: refused} + - {pointer: /disbursements/*/binding/recipientPartyKey, whenOmitted: refused} + - {pointer: /disbursements/*/binding/provider/type, whenOmitted: refused} + - {pointer: /disbursements/*/binding/provider/revision, whenOmitted: refused} + - {pointer: /disbursements/*/binding/provider/submitBaseUrl, whenOmitted: refused} + - {pointer: /disbursements/*/binding/provider/statusBaseUrl, whenOmitted: refused} + - {pointer: /disbursements/*/binding/provider/auth/type, whenOmitted: refused} + - {pointer: /disbursements/*/binding/provider/auth/credentialIdentity, whenOmitted: refused} + - {pointer: /disbursements/*/binding/provider/auth/credentialRef, whenOmitted: refused} + - {pointer: /disbursements/*/binding/provider/auth/tenant, whenOmitted: refused} + - {pointer: /disbursements/*/binding/provider/auth/signingKeyIdentity, whenOmitted: refused} + - {pointer: /disbursements/*/binding/provider/auth/signingKey/socketPath, whenOmitted: refused} + - {pointer: /disbursements/*/binding/provider/auth/signingKey/mount, whenOmitted: refused} + - {pointer: /disbursements/*/binding/provider/auth/signingKey/key, whenOmitted: refused} + - {pointer: /disbursements/*/binding/provider/auth/signingKey/version, whenOmitted: refused} + - {pointer: /disbursements/*/binding/provider/auth/signingKey/publicKeyDigest, whenOmitted: refused} + - {pointer: /disbursements/*/binding/provider/auth/signingKey/attemptTimeoutMilliseconds, whenOmitted: refused} + - {pointer: /disbursements/*/binding/provider/auth/responseKeyIdentity, whenOmitted: refused} + - {pointer: /disbursements/*/binding/provider/auth/responseKey/socketPath, whenOmitted: refused} + - {pointer: /disbursements/*/binding/provider/auth/responseKey/mount, whenOmitted: refused} + - {pointer: /disbursements/*/binding/provider/auth/responseKey/key, whenOmitted: refused} + - {pointer: /disbursements/*/binding/provider/auth/responseKey/version, whenOmitted: refused} + - {pointer: /disbursements/*/binding/provider/auth/responseKey/publicKeyDigest, whenOmitted: refused} + - {pointer: /disbursements/*/binding/provider/auth/responseKey/attemptTimeoutMilliseconds, whenOmitted: refused} + - {pointer: /disbursements/*/binding/provider/auth/operationsCredentialIdentity, whenOmitted: refused} + - {pointer: /disbursements/*/binding/provider/auth/operationsCredentialRef, whenOmitted: refused} + - {pointer: /disbursements/*/binding/registry/baseUrl, whenOmitted: refused} + - {pointer: /disbursements/*/binding/registry/credentialIdentity, whenOmitted: refused} + - {pointer: /disbursements/*/binding/registry/credentialRef, whenOmitted: refused} + - {pointer: /disbursements/*/binding/registry/recordRoute, whenOmitted: refused} + - {pointer: /disbursements/*/binding/registry/recordType, whenOmitted: refused} + - {pointer: /disbursements/*/binding/registry/readProfile, whenOmitted: refused} + - {pointer: /disbursements/*/binding/registry/bindProfile, whenOmitted: refused} + - {pointer: /disbursements/*/binding/registry/reportProfile, whenOmitted: refused} + - {pointer: /disbursements/*/binding/registry/bindAction, whenOmitted: refused} + - {pointer: /disbursements/*/binding/registry/reportAction, whenOmitted: refused} + restrictingMembers: [/connections/*/allowedClients, /connections/*/requiredScope, /connections/*/institutionId, /connections/*/serviceId, /connections/*/binding/simulation, /disbursements/*/allowedClients, /disbursements/*/requiredScope, /disbursements/*/binding/institutionId, /disbursements/*/binding/serviceId, /disbursements/*/binding/programmeId, /disbursements/*/binding/fundingAccountId] - id: adapter/job-runtime product: adapter From 43b678607ffb9742cd5a5d04753c0e4698541b14 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 13 Nov 2026 04:57:43 +0700 Subject: [PATCH 11/40] fix(identifiers): register payment provider schemas Signed-off-by: Jeremi Joslin --- .../identifiers/generated/catalog.v1.json | 62 +++++++++++++++---- 1 file changed, 49 insertions(+), 13 deletions(-) diff --git a/products/identifiers/generated/catalog.v1.json b/products/identifiers/generated/catalog.v1.json index 163328395b..b7ca668d31 100644 --- a/products/identifiers/generated/catalog.v1.json +++ b/products/identifiers/generated/catalog.v1.json @@ -4581,7 +4581,7 @@ "description": "Registry Adapter project, profile, pack, fixture, runtime configuration, payment connections, ingestion job, job runtime configuration, and effective contract JSON Schema.", "source": { "path": "crates/registry-adapterctl/src/schemas.rs", - "sha256": "5a7292b400c08e61c1a64d98c5bb008b577898c341235d4b16b9c892fa147e60" + "sha256": "d3ae2236da999886ec80d3c8e18e2e0c6cb71eda7fbcdd2e134089cf51199cc0" }, "artifact": { "path": "products/adapter/schemas/effective-contract.v1alpha1.schema.json", @@ -4599,7 +4599,7 @@ "description": "Registry Adapter project, profile, pack, fixture, runtime configuration, payment connections, ingestion job, job runtime configuration, and effective contract JSON Schema.", "source": { "path": "crates/registry-adapterctl/src/schemas.rs", - "sha256": "5a7292b400c08e61c1a64d98c5bb008b577898c341235d4b16b9c892fa147e60" + "sha256": "d3ae2236da999886ec80d3c8e18e2e0c6cb71eda7fbcdd2e134089cf51199cc0" }, "artifact": { "path": "products/adapter/schemas/fixture.v1alpha1.schema.json", @@ -4617,7 +4617,7 @@ "description": "Registry Adapter project, profile, pack, fixture, runtime configuration, payment connections, ingestion job, job runtime configuration, and effective contract JSON Schema.", "source": { "path": "crates/registry-adapterctl/src/schemas.rs", - "sha256": "5a7292b400c08e61c1a64d98c5bb008b577898c341235d4b16b9c892fa147e60" + "sha256": "d3ae2236da999886ec80d3c8e18e2e0c6cb71eda7fbcdd2e134089cf51199cc0" }, "artifact": { "path": "products/adapter/schemas/job-runtime.v1alpha1.schema.json", @@ -4635,7 +4635,7 @@ "description": "Registry Adapter project, profile, pack, fixture, runtime configuration, payment connections, ingestion job, job runtime configuration, and effective contract JSON Schema.", "source": { "path": "crates/registry-adapterctl/src/schemas.rs", - "sha256": "5a7292b400c08e61c1a64d98c5bb008b577898c341235d4b16b9c892fa147e60" + "sha256": "d3ae2236da999886ec80d3c8e18e2e0c6cb71eda7fbcdd2e134089cf51199cc0" }, "artifact": { "path": "products/adapter/schemas/job.v1alpha1.schema.json", @@ -4653,7 +4653,7 @@ "description": "Registry Adapter project, profile, pack, fixture, runtime configuration, payment connections, ingestion job, job runtime configuration, and effective contract JSON Schema.", "source": { "path": "crates/registry-adapterctl/src/schemas.rs", - "sha256": "5a7292b400c08e61c1a64d98c5bb008b577898c341235d4b16b9c892fa147e60" + "sha256": "d3ae2236da999886ec80d3c8e18e2e0c6cb71eda7fbcdd2e134089cf51199cc0" }, "artifact": { "path": "products/adapter/schemas/mapping.v1alpha1.schema.json", @@ -4671,7 +4671,7 @@ "description": "Registry Adapter project, profile, pack, fixture, runtime configuration, payment connections, ingestion job, job runtime configuration, and effective contract JSON Schema.", "source": { "path": "crates/registry-adapterctl/src/schemas.rs", - "sha256": "5a7292b400c08e61c1a64d98c5bb008b577898c341235d4b16b9c892fa147e60" + "sha256": "d3ae2236da999886ec80d3c8e18e2e0c6cb71eda7fbcdd2e134089cf51199cc0" }, "artifact": { "path": "products/adapter/schemas/pack.v1alpha1.schema.json", @@ -4679,6 +4679,42 @@ "mediaType": "application/schema+json" } }, + { + "uri": "https://id.registrystack.org/schemas/adapter/payment-provider-fixture/payment-provider-fixture.v1alpha1.schema.json", + "kind": "schema", + "status": "active", + "compatibilityLine": "v1alpha1", + "owner": "adapter", + "title": "Registry Adapter payment provider fixture", + "description": "Registry Adapter project, profile, pack, fixture, runtime configuration, payment connections, ingestion job, job runtime configuration, and effective contract JSON Schema.", + "source": { + "path": "crates/registry-adapterctl/src/schemas.rs", + "sha256": "d3ae2236da999886ec80d3c8e18e2e0c6cb71eda7fbcdd2e134089cf51199cc0" + }, + "artifact": { + "path": "products/adapter/schemas/payment-provider-fixture.v1alpha1.schema.json", + "sha256": "4d448ef29aed27d9fc2d1ef251fcf66256d6c0f02d55594582105136a732a034", + "mediaType": "application/schema+json" + } + }, + { + "uri": "https://id.registrystack.org/schemas/adapter/payment-provider-pack/payment-provider-pack.v1alpha1.schema.json", + "kind": "schema", + "status": "active", + "compatibilityLine": "v1alpha1", + "owner": "adapter", + "title": "Registry Adapter payment provider pack", + "description": "Registry Adapter project, profile, pack, fixture, runtime configuration, payment connections, ingestion job, job runtime configuration, and effective contract JSON Schema.", + "source": { + "path": "crates/registry-adapterctl/src/schemas.rs", + "sha256": "d3ae2236da999886ec80d3c8e18e2e0c6cb71eda7fbcdd2e134089cf51199cc0" + }, + "artifact": { + "path": "products/adapter/schemas/payment-provider-pack.v1alpha1.schema.json", + "sha256": "1a5b6c0ae4299742e40a9f5ebe03a732c2ddd25a83b314ea25dd02cb2f56250f", + "mediaType": "application/schema+json" + } + }, { "uri": "https://id.registrystack.org/schemas/adapter/payments/payments.v1alpha1.schema.json", "kind": "schema", @@ -4689,11 +4725,11 @@ "description": "Registry Adapter project, profile, pack, fixture, runtime configuration, payment connections, ingestion job, job runtime configuration, and effective contract JSON Schema.", "source": { "path": "crates/registry-adapterctl/src/schemas.rs", - "sha256": "5a7292b400c08e61c1a64d98c5bb008b577898c341235d4b16b9c892fa147e60" + "sha256": "d3ae2236da999886ec80d3c8e18e2e0c6cb71eda7fbcdd2e134089cf51199cc0" }, "artifact": { "path": "products/adapter/schemas/payments.v1alpha1.schema.json", - "sha256": "00209fbf08637effcf1497601601d17196e34de84157bd72fc578e61871a029b", + "sha256": "230c16652707819427147a0772e4a2f490fba60ec43984e2392b496684bc458d", "mediaType": "application/schema+json" } }, @@ -4707,7 +4743,7 @@ "description": "Registry Adapter project, profile, pack, fixture, runtime configuration, payment connections, ingestion job, job runtime configuration, and effective contract JSON Schema.", "source": { "path": "crates/registry-adapterctl/src/schemas.rs", - "sha256": "5a7292b400c08e61c1a64d98c5bb008b577898c341235d4b16b9c892fa147e60" + "sha256": "d3ae2236da999886ec80d3c8e18e2e0c6cb71eda7fbcdd2e134089cf51199cc0" }, "artifact": { "path": "products/adapter/schemas/preview-expectations.v1alpha1.schema.json", @@ -4725,7 +4761,7 @@ "description": "Registry Adapter project, profile, pack, fixture, runtime configuration, payment connections, ingestion job, job runtime configuration, and effective contract JSON Schema.", "source": { "path": "crates/registry-adapterctl/src/schemas.rs", - "sha256": "5a7292b400c08e61c1a64d98c5bb008b577898c341235d4b16b9c892fa147e60" + "sha256": "d3ae2236da999886ec80d3c8e18e2e0c6cb71eda7fbcdd2e134089cf51199cc0" }, "artifact": { "path": "products/adapter/schemas/profile.v1alpha1.schema.json", @@ -4743,7 +4779,7 @@ "description": "Registry Adapter project, profile, pack, fixture, runtime configuration, payment connections, ingestion job, job runtime configuration, and effective contract JSON Schema.", "source": { "path": "crates/registry-adapterctl/src/schemas.rs", - "sha256": "5a7292b400c08e61c1a64d98c5bb008b577898c341235d4b16b9c892fa147e60" + "sha256": "d3ae2236da999886ec80d3c8e18e2e0c6cb71eda7fbcdd2e134089cf51199cc0" }, "artifact": { "path": "products/adapter/schemas/project.v1alpha1.schema.json", @@ -4761,7 +4797,7 @@ "description": "Registry Adapter project, profile, pack, fixture, runtime configuration, payment connections, ingestion job, job runtime configuration, and effective contract JSON Schema.", "source": { "path": "crates/registry-adapterctl/src/schemas.rs", - "sha256": "5a7292b400c08e61c1a64d98c5bb008b577898c341235d4b16b9c892fa147e60" + "sha256": "d3ae2236da999886ec80d3c8e18e2e0c6cb71eda7fbcdd2e134089cf51199cc0" }, "artifact": { "path": "products/adapter/schemas/runtime.v1alpha1.schema.json", @@ -5319,7 +5355,7 @@ "description": "Registry Coordinator deterministic scenario authoring JSON Schema.", "source": { "path": "crates/registry-coordinator/src/scenarios.rs", - "sha256": "6610fb0146afc7fce8b1339af0ed56d4b99e7a8bb37a3dfb6b695e7e8cbd475c" + "sha256": "d15a452b05c77a398cf957e0f955fb0d7faa2b478df6ee1780f10606d21366b3" }, "artifact": { "path": "products/coordinator/generated/scenarios/scenarios.schema.json", From c4fe142609683c5e195178808d42a4493860cd78 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Thu, 19 Nov 2026 20:50:58 +0000 Subject: [PATCH 12/40] fix(platform): decode Transit RSA public keys with pkcs1 0.8 Main moved pkcs1 to 0.8, whose owned RsaPublicKey is generic over its integer type. Borrow the modulus through RsaPublicKeyRef, as registry-evidencectl does. Signed-off-by: Jeremi Joslin --- crates/registry-platform-crypto/src/transit_rsa_no_oid.rs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/crates/registry-platform-crypto/src/transit_rsa_no_oid.rs b/crates/registry-platform-crypto/src/transit_rsa_no_oid.rs index bbdd41b39c..c01d8992ba 100644 --- a/crates/registry-platform-crypto/src/transit_rsa_no_oid.rs +++ b/crates/registry-platform-crypto/src/transit_rsa_no_oid.rs @@ -13,7 +13,6 @@ use std::time::Duration; use aws_lc_rs::rsa::PublicKey as RsaPublicKey; use base64::engine::general_purpose::STANDARD; use base64::Engine as _; -use pkcs1::der::Decode as _; use serde_json::{json, Value}; use sha2::{Digest as _, Sha256}; use thiserror::Error; @@ -265,7 +264,7 @@ impl TransitRsaNoOidClient { } let key = RsaPublicKey::from_der(spki_der.as_slice()) .map_err(|_| TransitRsaNoOidError::InvalidPublicKey)?; - let pkcs1 = pkcs1::RsaPublicKey::from_der(key.as_ref()) + let pkcs1 = pkcs1::RsaPublicKeyRef::try_from(key.as_ref()) .map_err(|_| TransitRsaNoOidError::InvalidPublicKey)?; let modulus = pkcs1.modulus.as_bytes(); let modulus_bits = exact_bit_length(modulus)?; From 809b2464e64bb9fb6d73e5188dd93637082fa60c Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 13 Nov 2026 05:25:33 +0700 Subject: [PATCH 13/40] fix(adapter): preserve payment file diagnostics Signed-off-by: Jeremi Joslin --- crates/registry-adapter/src/payments/pack.rs | 48 +++++- .../src/payment_fixtures.rs | 162 +++++++++++++++--- crates/registry-adapterctl/src/payments.rs | 49 ++++-- crates/registry-adapterctl/tests/payments.rs | 45 +++++ products/platform/config-formats.yaml | 9 +- .../platform/conformance/yaml/formats.yaml | 16 ++ 6 files changed, 276 insertions(+), 53 deletions(-) diff --git a/crates/registry-adapter/src/payments/pack.rs b/crates/registry-adapter/src/payments/pack.rs index f31b61cd2f..db6f4589cf 100644 --- a/crates/registry-adapter/src/payments/pack.rs +++ b/crates/registry-adapter/src/payments/pack.rs @@ -2,7 +2,10 @@ //! Reviewed provider selection for the typed payment host. use registry_adapter_core::{RhaiExpression, ScriptReference}; -use registry_platform_yaml::{ApiVersion, EnvelopeRule, Expect, FormatSpec, Reader, Report}; +use registry_platform_config::AuthoredExpressions; +use registry_platform_yaml::{ + ApiVersion, EnvelopeRule, Expect, FormatSpec, Reader, Report, UniqueList, +}; use serde::{Deserialize, Serialize}; use std::collections::{BTreeMap, BTreeSet}; use std::path::{Component, Path}; @@ -39,6 +42,34 @@ pub struct PaymentProviderPack { pub mapping: Option, } +/// Reader-only types apply the shared authored constraints while preserving +/// the public pack model and its generated schema. +#[derive(Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct PaymentProviderPackReader { + id: String, + version: String, + connector: ConnectorKind, + capabilities: UniqueList, + #[serde(default)] + tested_versions: Vec, + #[serde(default)] + mapping: Option, +} + +impl From for PaymentProviderPack { + fn from(reader: PaymentProviderPackReader) -> Self { + Self { + id: reader.id, + version: reader.version, + connector: reader.connector, + capabilities: reader.capabilities.into_vec(), + tested_versions: reader.tested_versions, + mapping: reader.mapping, + } + } +} + #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] #[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] pub enum ConnectorKind { @@ -52,7 +83,7 @@ pub enum ConnectorKind { AdapterPaymentHttpV1, } -#[derive(Clone, Copy, Debug, Ord, PartialOrd, Eq, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Copy, Debug, Ord, PartialOrd, Eq, PartialEq, Hash, Serialize, Deserialize)] #[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] #[serde(rename_all = "kebab-case")] pub enum PaymentCapability { @@ -127,8 +158,17 @@ pub struct PackError; impl PaymentProviderPack { /// Decode one authored pack using the common strict YAML and envelope reader. pub fn from_yaml(bytes: &[u8]) -> Result { - let decoded = Reader::new("pack.yaml").decode::(bytes, &Expect::one(&FORMAT))?; - Ok(decoded.value) + Self::from_yaml_at("pack.yaml", bytes) + } + + /// Decode one authored pack and retain the caller's displayed file path in + /// every located diagnostic. + pub fn from_yaml_at(file: impl Into, bytes: &[u8]) -> Result { + let mut authored = AuthoredExpressions; + let decoded = Reader::new(file) + .with_hook(&mut authored) + .decode::(bytes, &Expect::one(&FORMAT))?; + Ok(decoded.value.into()) } pub fn validate(&self) -> Result<(), PackError> { diff --git a/crates/registry-adapterctl/src/payment_fixtures.rs b/crates/registry-adapterctl/src/payment_fixtures.rs index 4c4f03daaf..58f2bc6386 100644 --- a/crates/registry-adapterctl/src/payment_fixtures.rs +++ b/crates/registry-adapterctl/src/payment_fixtures.rs @@ -14,6 +14,7 @@ use registry_payment_mifos_connector::{ BatchObservation, CollectionAccepted, CollectionCommand, CollectionObservation, CONNECTOR_PROFILE, }; +use registry_platform_config::AuthoredExpressions; use registry_platform_yaml::{ ApiVersion, BoundedU32, EnvelopeRule, Expect, FormatSpec, LocalId, Reader, }; @@ -95,10 +96,11 @@ pub(crate) enum Direction { } /// All errors are value-free so authored provider payloads never enter ctl reports. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[derive(Clone, Debug, PartialEq, Eq)] pub(crate) enum FixtureError { Unavailable, Refused, + Diagnostics(Vec), } struct MappedFixture { @@ -165,11 +167,7 @@ pub(crate) fn replay_mapped( pack_bytes: &[u8], ) -> Result<(), FixtureError> { let program = compile_mapped_pack(pack_path, pack, pack_bytes)?; - let bytes = std::fs::read(fixture_path).map_err(|_| FixtureError::Unavailable)?; - let document = Reader::new(fixture_path.display().to_string()) - .decode::(&bytes, &Expect::one(&FORMAT)) - .map_err(|_| FixtureError::Refused)? - .value; + let document = read_fixture(fixture_path)?; let FixtureDocument::Mapped { direction, intent, @@ -319,10 +317,6 @@ pub(crate) fn replay(path: &Path, connector: ConnectorKind) -> Result<(), Fixtur if connector != ConnectorKind::MifosPhEeLegacyV1 { return Err(FixtureError::Refused); } - let bytes = std::fs::read(path).map_err(|_| FixtureError::Unavailable)?; - let decoded = Reader::new(path.display().to_string()) - .decode::(&bytes, &Expect::one(&FORMAT)) - .map_err(|_| FixtureError::Refused)?; let FixtureDocument::Compiled { connector_profile, direction, @@ -330,7 +324,7 @@ pub(crate) fn replay(path: &Path, connector: ConnectorKind) -> Result<(), Fixtur expected_request, acceptance, status, - } = decoded.value + } = read_fixture(path)? else { return Err(FixtureError::Refused); }; @@ -394,6 +388,16 @@ pub(crate) fn replay(path: &Path, connector: ConnectorKind) -> Result<(), Fixtur Ok(()) } +fn read_fixture(path: &Path) -> Result { + let bytes = std::fs::read(path).map_err(|_| FixtureError::Unavailable)?; + let mut hook = AuthoredExpressions; + Reader::new(path.display().to_string()) + .with_hook(&mut hook) + .decode::(&bytes, &Expect::one(&FORMAT)) + .map(|decoded| decoded.value) + .map_err(|report| FixtureError::Diagnostics(report.into_diagnostics())) +} + fn matches_expected(actual: &T, expected: Value) -> Result<(), FixtureError> { let actual = serde_json::to_value(actual).map_err(|_| FixtureError::Refused)?; if actual == expected { @@ -462,20 +466,101 @@ status: ), ) .unwrap(); - assert_eq!( - replay(file.path(), ConnectorKind::MifosPhEeLegacyV1), - Err(FixtureError::Refused) - ); + let diagnostics = diagnostic_error(replay(file.path(), ConnectorKind::MifosPhEeLegacyV1)); + let unknown = diagnostics + .iter() + .find(|diagnostic| diagnostic.code == "config.unknown-key") + .unwrap(); + assert_eq!(unknown.artifact.as_deref(), Some(KIND)); + assert_eq!(unknown.path, "/secret"); std::fs::write(file.path(), COLLECTION).unwrap(); assert_eq!( replay(file.path(), ConnectorKind::SimulatorP2gV1), Err(FixtureError::Refused) ); std::fs::write(file.path(), COLLECTION.replace("type: compiled\n", "")).unwrap(); - assert_eq!( - replay(file.path(), ConnectorKind::MifosPhEeLegacyV1), - Err(FixtureError::Refused) - ); + let diagnostics = diagnostic_error(replay(file.path(), ConnectorKind::MifosPhEeLegacyV1)); + let missing_type = diagnostics + .iter() + .find(|diagnostic| diagnostic.code == "config.missing-key") + .unwrap(); + assert_eq!(missing_type.artifact.as_deref(), Some(KIND)); + assert_eq!(missing_type.path, ""); + assert!(missing_type.message.contains("`type`")); + } + + #[test] + fn fixture_type_reports_malformed_tags_at_their_source() { + let file = tempfile::NamedTempFile::new().unwrap(); + for (value, code, column) in [ + ("", "config.null-value", 1), + (" null", "config.null-value", 7), + (" true", "config.invalid-type", 7), + (" 42", "config.invalid-type", 7), + (" 3.14", "config.invalid-type", 7), + ] { + let fixture = COLLECTION.replace("type: compiled", &format!("type:{value}")); + std::fs::write(file.path(), fixture).unwrap(); + let diagnostics = diagnostic_error(read_fixture(file.path())); + let diagnostic = diagnostics + .iter() + .find(|diagnostic| diagnostic.code == code && diagnostic.path == "/type") + .unwrap(); + assert_eq!(diagnostic.artifact.as_deref(), Some(KIND)); + let source = diagnostic.source.as_ref().unwrap(); + assert_eq!(source.file, file.path().display().to_string()); + assert_eq!(source.line, Some(3)); + assert_eq!(source.column, Some(column)); + } + } + + #[test] + fn both_fixture_variants_preserve_authored_reader_artifact_and_source_locations() { + let file = tempfile::NamedTempFile::new().unwrap(); + for fixture_type in ["compiled", "mapped"] { + let substituted = format!( + "apiVersion: {VERSION}\nkind: {KIND}\ntype: {fixture_type}\ndirection: ${{DIRECTION}}\n" + ); + std::fs::write(file.path(), substituted).unwrap(); + let diagnostics = diagnostic_error(read_fixture(file.path())); + let substitution = diagnostics + .iter() + .find(|diagnostic| diagnostic.code == "config.substitution-not-allowed") + .unwrap(); + assert_eq!(substitution.artifact.as_deref(), Some(KIND)); + assert_eq!(substitution.path, "/direction"); + let substitution_source = substitution.source.as_ref().unwrap(); + assert_eq!(substitution_source.file, file.path().display().to_string()); + assert_eq!(substitution_source.line, Some(4)); + assert_eq!(substitution_source.column, Some(12)); + + let unknown_member = match fixture_type { + "compiled" => format!( + "apiVersion: {VERSION}\nkind: {KIND}\ntype: compiled\nconnectorProfile: profile\ndirection: p2g-collection\ncommand: {{}}\nexpectedRequest: {{}}\nacceptance:\n response: {{httpStatus: 200, body: {{}}}}\n expected: {{}}\nstatus:\n response: {{httpStatus: 200, body: {{}}}}\n expected: {{}}\nunexpected: true\n" + ), + "mapped" => format!( + "apiVersion: {VERSION}\nkind: {KIND}\ntype: mapped\ndirection: g2p-disbursement\nintent: {{}}\nsettings: {{}}\nsubmit:\n expectedRequest: {{}}\n response: {{status: 200, bodyJson: '{{}}'}}\n expected: {{}}\nstatus:\n expectedRequest: {{}}\n response: {{status: 200, bodyJson: '{{}}'}}\n expected: {{}}\nunexpected: true\n" + ), + _ => unreachable!(), + }; + let unexpected_line = unknown_member + .lines() + .position(|line| line == "unexpected: true") + .unwrap() + + 1; + std::fs::write(file.path(), unknown_member).unwrap(); + let diagnostics = diagnostic_error(read_fixture(file.path())); + let unknown = diagnostics + .iter() + .find(|diagnostic| diagnostic.code == "config.unknown-key") + .unwrap(); + assert_eq!(unknown.artifact.as_deref(), Some(KIND)); + assert_eq!(unknown.path, "/unexpected"); + let unknown_source = unknown.source.as_ref().unwrap(); + assert_eq!(unknown_source.file, file.path().display().to_string()); + assert_eq!(unknown_source.line, Some(unexpected_line)); + assert_eq!(unknown_source.column, Some(1)); + } } #[test] @@ -530,10 +615,16 @@ fn status_response(intent, settings, acceptance, response) { fixture.replacen("status: 202", &format!("status: {invalid_status}"), 1), ) .unwrap(); - assert_eq!( - replay_mapped(&fixture_path, &pack_path, &parsed, pack.as_bytes()), - Err(FixtureError::Refused) - ); + let diagnostics = diagnostic_error(replay_mapped( + &fixture_path, + &pack_path, + &parsed, + pack.as_bytes(), + )); + assert!(diagnostics.iter().any(|diagnostic| { + diagnostic.code == "config.out-of-range" + && diagnostic.path == "/submit/response/status" + })); } std::fs::write( &fixture_path, @@ -552,10 +643,16 @@ fn status_response(intent, settings, acceptance, response) { ), ) .unwrap(); - assert_eq!( - replay_mapped(&fixture_path, &pack_path, &parsed, pack.as_bytes()), - Err(FixtureError::Refused) - ); + let diagnostics = diagnostic_error(replay_mapped( + &fixture_path, + &pack_path, + &parsed, + pack.as_bytes(), + )); + assert!(diagnostics.iter().any(|diagnostic| { + diagnostic.code == "config.invalid-value" + && diagnostic.path == "/status/acceptance/references/Transfer.ID" + })); std::fs::write( scripts.join("provider.rhai"), format!("{script}\n// changed"), @@ -596,4 +693,15 @@ fn status_response(intent, settings, acceptance, response) { std::fs::canonicalize(".").unwrap() ); } + + fn diagnostic_error( + result: Result, + ) -> Vec { + match result { + Err(FixtureError::Diagnostics(diagnostics)) => diagnostics, + Ok(_) | Err(FixtureError::Unavailable | FixtureError::Refused) => { + panic!("expected authored reader diagnostics") + } + } + } } diff --git a/crates/registry-adapterctl/src/payments.rs b/crates/registry-adapterctl/src/payments.rs index 6af5cc7f8a..da807368a8 100644 --- a/crates/registry-adapterctl/src/payments.rs +++ b/crates/registry-adapterctl/src/payments.rs @@ -134,7 +134,7 @@ impl ProviderPackRegistry { message: "A payment provider pack could not be read.", action: "Correct the provider pack path and retry.", })?; - let pack = PaymentProviderPack::from_yaml(&bytes) + let pack = PaymentProviderPack::from_yaml_at(path.display().to_string(), &bytes) .map_err(|report| ProviderPackLoadError::Diagnostics(report.into_diagnostics()))?; if pack.validate().is_err() { return Err(ProviderPackLoadError::Problem { @@ -251,7 +251,7 @@ pub fn run(command: &PaymentsCommand) -> PaymentCheck { )]), unavailable: true, deny_warnings, - } + }; } }; let check = RuntimeConfigLoader::new(RuntimeEnvelope { @@ -260,6 +260,7 @@ pub fn run(command: &PaymentsCommand) -> PaymentCheck { }) .check_offline::(&absolute, true, |_| DEFAULT_STAND_IN); let mut additional = Vec::new(); + let mut companion_diagnostics = Vec::new(); let mut value = json!({}); if let Some(loaded) = &check.loaded { if loaded.config.validate().is_err() { @@ -268,15 +269,18 @@ pub fn run(command: &PaymentsCommand) -> PaymentCheck { "Check connection scopes, unique caller identities, currency and synthetic provider bindings; then retry.")); } else { match ProviderPackRegistry::load(provider_packs) { - Ok(registry) => check_provider_pack_bindings( - &check, - &loaded.config, - ®istry, - fixtures, - &mut additional, - ), + Ok(registry) => { + check_provider_pack_bindings( + &check, + &loaded.config, + ®istry, + &mut additional, + ); + companion_diagnostics = + check_payment_fixtures(&check, ®istry, fixtures, &mut additional); + } Err(ProviderPackLoadError::Diagnostics(diagnostics)) => { - additional.extend(diagnostics); + companion_diagnostics = diagnostics; } Err(ProviderPackLoadError::Problem { code, @@ -292,9 +296,11 @@ pub fn run(command: &PaymentsCommand) -> PaymentCheck { } } } + let mut checked = check.report_with(KIND, additional); + checked.extend(Report::new(companion_diagnostics)); PaymentCheck { value, - checked: check.report_with(KIND, additional), + checked, unavailable: check.unavailable, deny_warnings, } @@ -304,10 +310,8 @@ fn check_provider_pack_bindings( check: ®istry_platform_config::RuntimeFileCheck, config: &PaymentsConfig, registry: &ProviderPackRegistry, - fixtures: &[PathBuf], additional: &mut Vec, ) { - check_payment_fixtures(check, registry, fixtures, additional); for (index, connection) in config.connections.iter().enumerate() { let path = format!("/connections/{index}/binding/providerPack"); let Some(pin) = connection.binding.provider_pack.as_ref() else { @@ -436,9 +440,9 @@ fn check_payment_fixtures( registry: &ProviderPackRegistry, fixtures: &[PathBuf], additional: &mut Vec, -) { +) -> Vec { if fixtures.is_empty() { - return; + return Vec::new(); } let Some(selected) = registry.only() else { let (code, message, action) = if registry.by_digest.is_empty() { @@ -455,8 +459,9 @@ fn check_payment_fixtures( ) }; additional.push(check.error_at(KIND, code, "/fixtures", message, action)); - return; + return Vec::new(); }; + let mut companion_diagnostics = Vec::new(); for fixture in fixtures { let replay = if selected.pack.connector == ConnectorKind::AdapterPaymentHttpV1 { payment_fixtures::replay_mapped( @@ -470,6 +475,10 @@ fn check_payment_fixtures( }; if let Err(error) = replay { let (code, message, action) = match error { + FixtureError::Diagnostics(diagnostics) => { + companion_diagnostics.extend(diagnostics); + continue; + } FixtureError::Unavailable => ( "adapter.payment.fixture-unavailable", "A payment provider fixture could not be read.", @@ -484,6 +493,7 @@ fn check_payment_fixtures( additional.push(check.error_at(KIND, code, "/fixtures", message, action)); } } + companion_diagnostics } fn check_pack(file: &PathBuf) -> PaymentCheck { @@ -500,10 +510,13 @@ fn check_pack(file: &PathBuf) -> PaymentCheck { )]), unavailable: true, deny_warnings: false, - } + }; } }; - let (value, checked) = match PaymentProviderPack::from_yaml(&bytes) { + let (value, checked) = match PaymentProviderPack::from_yaml_at( + file.display().to_string(), + &bytes, + ) { Ok(pack) if pack.validate().is_ok() && (pack.connector != ConnectorKind::AdapterPaymentHttpV1 diff --git a/crates/registry-adapterctl/tests/payments.rs b/crates/registry-adapterctl/tests/payments.rs index 0f85e8bc3e..04931d4abc 100644 --- a/crates/registry-adapterctl/tests/payments.rs +++ b/crates/registry-adapterctl/tests/payments.rs @@ -193,6 +193,51 @@ fn payment_check_keeps_the_shared_reader_diagnostic_and_position() { assert!(stderr.is_empty()); } +#[test] +fn payment_check_keeps_companion_paths_as_supplied() { + let directory = tempfile::tempdir().unwrap(); + let pack = "apiVersion: id.registrystack.org/formats/adapter/payment-provider-pack/v1alpha1\nkind: AdapterPaymentProviderPack\nid: legacy\nversion: '1'\nconnector: mifos-ph-ee-legacy/v1\ncapabilities: [collection]\n"; + let pack_path = directory.path().join("pack.yaml"); + std::fs::write(&pack_path, format!("{pack}unexpected: true\n")).unwrap(); + let fixture = "apiVersion: id.registrystack.org/formats/adapter/payment-provider-fixture/v1alpha1\nkind: AdapterPaymentProviderFixture\ntype: 42\n"; + std::fs::write(directory.path().join("fixture.yaml"), fixture).unwrap(); + let payments = PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("../../products/adapter/examples/payment-collections/payments.example.yaml"); + let check = |additional: &[&str]| { + let output = std::process::Command::new(env!("CARGO_BIN_EXE_adapterctl")) + .current_dir(directory.path()) + .args(["--format", "json", "payments", "check"]) + .arg(&payments) + .args(["--provider-pack", "pack.yaml"]) + .args(additional) + .output() + .unwrap(); + assert_eq!(output.status.code(), Some(1)); + assert!(output.stderr.is_empty()); + serde_json::from_slice::(&output.stdout).unwrap() + }; + let report = check(&[]); + let diagnostic = &report["diagnostics"][0]; + assert_eq!(diagnostic["code"], "config.unknown-key"); + assert_eq!(diagnostic["artifact"], "AdapterPaymentProviderPack"); + assert_eq!(diagnostic["path"], "/unexpected"); + assert_eq!( + diagnostic["source"], + json!({"file": "pack.yaml", "line": 7, "column": 1}) + ); + + std::fs::write(&pack_path, pack).unwrap(); + let report = check(&["--fixtures", "fixture.yaml"]); + let diagnostic = &report["diagnostics"][0]; + assert_eq!(diagnostic["code"], "config.invalid-type"); + assert_eq!(diagnostic["artifact"], "AdapterPaymentProviderFixture"); + assert_eq!(diagnostic["path"], "/type"); + assert_eq!( + diagnostic["source"], + json!({"file": "fixture.yaml", "line": 3, "column": 7}) + ); +} + #[test] fn payment_provider_variants_keep_nested_source_positions() { let directory = tempfile::tempdir().unwrap(); diff --git a/products/platform/config-formats.yaml b/products/platform/config-formats.yaml index 6ebbfa255c..4bdb1360fd 100644 --- a/products/platform/config-formats.yaml +++ b/products/platform/config-formats.yaml @@ -4530,12 +4530,13 @@ formats: reader: crate: registry-adapterctl file: crates/registry-adapterctl/src/payment_fixtures.rs - function: replay_mapped + function: read_fixture type: FixtureDocument - check: adapterctl payments fixtures replay {payments} --provider-pack {pack}/pack.yaml --fixtures {file} + check: adapterctl payments check {payments} --provider-pack {pack} --fixtures {file} example: products/adapter/examples/payment-provider-fixture.yaml conformance: - requiredText: /type + # The shared type and direction fields use tag and enum diagnostics. + requiredText: none optionalText: none integer: /acceptance/response/httpStatus boolean: none @@ -4569,7 +4570,7 @@ formats: file: crates/registry-adapter/src/payments/pack.rs function: from_yaml type: PaymentProviderPack - check: adapterctl payments check-pack {file} + check: adapterctl payments check {payments} --provider-pack {file} example: products/adapter/packs/payment-simulator/pack.yaml conformance: requiredText: /id diff --git a/products/platform/conformance/yaml/formats.yaml b/products/platform/conformance/yaml/formats.yaml index 2e683d6436..ada73f87d0 100644 --- a/products/platform/conformance/yaml/formats.yaml +++ b/products/platform/conformance/yaml/formats.yaml @@ -191,6 +191,22 @@ formats: profile: {from: products/adapter/profiles/breg-records} pack: {from: products/adapter/packs/dhis2-tracker} fixtures: {from: products/adapter/fixtures/dhis2-tracker} + adapter/payment-provider-pack: + copies: + payments: {from: products/adapter/examples/payment-collections/payments.example.yaml} + adapter/payment-provider-fixture: + copies: + payments: {from: products/adapter/examples/payment-collections/payments.example.yaml} + values: + pack: "{project}/payment-provider-fixture-pack.yaml" + write: + payment-provider-fixture-pack.yaml: | + apiVersion: id.registrystack.org/formats/adapter/payment-provider-pack/v1alpha1 + kind: AdapterPaymentProviderPack + id: mifos-legacy-fixture + version: '1' + connector: mifos-ph-ee-legacy/v1 + capabilities: [collection] # `adapterctl job check` compiles the job's workspace, which resolves # the endpoint credential references; the staged runtime points them at # the variable the runner sets for every check. From f682bb09da5244b2f6fe2e5bb5eaa560796c819a Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 13 Nov 2026 05:25:33 +0700 Subject: [PATCH 14/40] fix(adapter): bound signed disbursement auth variants Signed-off-by: Jeremi Joslin --- .../registry-adapter/src/payments/g2p_model.rs | 8 ++++---- crates/registry-adapter/tests/g2p_model.rs | 10 +++++----- crates/registry-adapter/tests/g2p_provider.rs | 16 ++++++++++++---- 3 files changed, 21 insertions(+), 13 deletions(-) diff --git a/crates/registry-adapter/src/payments/g2p_model.rs b/crates/registry-adapter/src/payments/g2p_model.rs index d3f33fccf4..d78c7d15ee 100644 --- a/crates/registry-adapter/src/payments/g2p_model.rs +++ b/crates/registry-adapter/src/payments/g2p_model.rs @@ -115,9 +115,9 @@ pub enum G2pHttpAuth { MifosLegacySignature { tenant: String, signing_key_identity: String, - signing_key: G2pTransitRsaNoOidKeyBinding, + signing_key: Box, response_key_identity: String, - response_key: G2pTransitRsaNoOidKeyBinding, + response_key: Box, operations_credential_identity: String, operations_credential_ref: SecretReference, }, @@ -177,9 +177,9 @@ enum G2pHttpAuthReader { MifosLegacySignature { tenant: String, signing_key_identity: String, - signing_key: G2pTransitRsaNoOidKeyBinding, + signing_key: Box, response_key_identity: String, - response_key: G2pTransitRsaNoOidKeyBinding, + response_key: Box, operations_credential_identity: String, operations_credential_ref: SecretReference, }, diff --git a/crates/registry-adapter/tests/g2p_model.rs b/crates/registry-adapter/tests/g2p_model.rs index e940e2565b..9a573c621d 100644 --- a/crates/registry-adapter/tests/g2p_model.rs +++ b/crates/registry-adapter/tests/g2p_model.rs @@ -339,9 +339,9 @@ fn provider_binding_exposes_the_exact_pack_auth_profile() { *auth = G2pHttpAuth::MifosLegacySignature { tenant: "default".to_owned(), signing_key_identity: "mifos-signing-key".to_owned(), - signing_key: transit_key("mifos-request", 7, 'a'), + signing_key: Box::new(transit_key("mifos-request", 7, 'a')), response_key_identity: "mifos-response-key".to_owned(), - response_key: transit_key("mifos-response", 4, 'b'), + response_key: Box::new(transit_key("mifos-response", 4, 'b')), operations_credential_identity: "mifos-operations-client".to_owned(), operations_credential_ref: SecretReference::new("secret:env/MIFOS_OPERATIONS_TOKEN") .unwrap(), @@ -359,9 +359,9 @@ fn provider_identity_freezes_transit_versions_and_logical_operations_identity() *auth = G2pHttpAuth::MifosLegacySignature { tenant: "default".to_owned(), signing_key_identity: "mifos-signing-key".to_owned(), - signing_key: transit_key("mifos-request", 7, 'a'), + signing_key: Box::new(transit_key("mifos-request", 7, 'a')), response_key_identity: "mifos-response-key".to_owned(), - response_key: transit_key("mifos-response", 4, 'b'), + response_key: Box::new(transit_key("mifos-response", 4, 'b')), operations_credential_identity: "mifos-operations-client".to_owned(), operations_credential_ref: SecretReference::new("secret:env/MIFOS_OPERATIONS_TOKEN") .unwrap(), @@ -399,7 +399,7 @@ fn provider_identity_freezes_transit_versions_and_logical_operations_identity() else { unreachable!() }; - *signing_key = transit_key("mifos-request", 8, 'a'); + **signing_key = transit_key("mifos-request", 8, 'a'); assert_ne!( new_signing_version .provider_intent(&instruction) diff --git a/crates/registry-adapter/tests/g2p_provider.rs b/crates/registry-adapter/tests/g2p_provider.rs index 3066744f1f..2fcf5ba87d 100644 --- a/crates/registry-adapter/tests/g2p_provider.rs +++ b/crates/registry-adapter/tests/g2p_provider.rs @@ -202,9 +202,9 @@ async fn bearer_http_host_preserves_one_send_and_validates_wire_observations() { G2pHttpAuth::MifosLegacySignature { tenant: "pilot-beta".to_owned(), signing_key_identity: "test-signing-key".to_owned(), - signing_key: transit_key("test-signing-key", 7, 'a'), + signing_key: Box::new(transit_key("test-signing-key", 7, 'a')), response_key_identity: "test-response-key".to_owned(), - response_key: transit_key("test-response-key", 4, 'b'), + response_key: Box::new(transit_key("test-response-key", 4, 'b')), operations_credential_identity: "test-operations-client".to_owned(), operations_credential_ref: SecretReference::new("secret:file/provider-token").unwrap(), }, @@ -291,9 +291,17 @@ async fn mifos_legacy_signature_host_signs_exact_requests_and_verifies_before_ma G2pHttpAuth::MifosLegacySignature { tenant: fixture_text(&fixture, "tenant").to_owned(), signing_key_identity: "transit:mifos-request:v7".to_owned(), - signing_key: released_transit_key(&socket_path, "mifos-request", &fixture), + signing_key: Box::new(released_transit_key( + &socket_path, + "mifos-request", + &fixture, + )), response_key_identity: "transit:mifos-response:v7".to_owned(), - response_key: released_transit_key(&socket_path, "mifos-response", &fixture), + response_key: Box::new(released_transit_key( + &socket_path, + "mifos-response", + &fixture, + )), operations_credential_identity: "mifos-operations-client".to_owned(), operations_credential_ref: SecretReference::new("secret:file/operations-token") .unwrap(), From 3db1c8fdc23cd33495a55f91734a553aeba2ac68 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 13 Nov 2026 05:46:36 +0700 Subject: [PATCH 15/40] docs(adapter): clarify offline payment fixture help Signed-off-by: Jeremi Joslin --- crates/registry-adapterctl/src/payments.rs | 2 +- crates/registry-cli-docs/catalog.json | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/registry-adapterctl/src/payments.rs b/crates/registry-adapterctl/src/payments.rs index da807368a8..df85f79a2a 100644 --- a/crates/registry-adapterctl/src/payments.rs +++ b/crates/registry-adapterctl/src/payments.rs @@ -50,7 +50,7 @@ pub enum PaymentsCommand { #[arg(long, value_name = "FILE")] provider_pack: Vec, }, - /// Replay provider mappings without connecting to Mifos or BReg. + /// Replay provider mappings offline. Fixtures { #[command(subcommand)] command: PaymentsFixturesCommand, diff --git a/crates/registry-cli-docs/catalog.json b/crates/registry-cli-docs/catalog.json index 2a84f02168..993ce463ea 100644 --- a/crates/registry-cli-docs/catalog.json +++ b/crates/registry-cli-docs/catalog.json @@ -1646,7 +1646,7 @@ { "name": "fixtures", "invocation": "adapterctl payments fixtures", - "about": "Replay provider mappings without connecting to Mifos or BReg", + "about": "Replay provider mappings offline", "long_about": null, "usage": "adapterctl payments fixtures [OPTIONS] ", "arguments": [], From d022e186be5b465fe5152d3eafef1e81602221e7 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Fri, 13 Nov 2026 06:26:52 +0700 Subject: [PATCH 16/40] test(coordinator): include both payment workflow examples Signed-off-by: Jeremi Joslin --- crates/registry-language-server/tests/coordinator_navigation.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/registry-language-server/tests/coordinator_navigation.rs b/crates/registry-language-server/tests/coordinator_navigation.rs index 866a1bf7c1..216c6ba19d 100644 --- a/crates/registry-language-server/tests/coordinator_navigation.rs +++ b/crates/registry-language-server/tests/coordinator_navigation.rs @@ -190,7 +190,7 @@ fn every_maintained_coordinator_workflow_has_no_invented_missing_local_reference count += 1; } assert_eq!( - count, 12, + count, 13, "cover every maintained Coordinator workflow, including payments" ); } From 2191010d346c5b614be1b1349f25207a2a83e8ed Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Wed, 18 Nov 2026 20:24:53 +0100 Subject: [PATCH 17/40] feat: add hosted payment page, return URL and per-payer outcomes to the simulator Signed-off-by: Jeremi Joslin --- .../payment-simulator/contracts/openapi.json | 13 +- .../src/payment_simulator/api.py | 78 ++- .../src/payment_simulator/cli.py | 35 +- .../src/payment_simulator/hosted_page.py | 69 +++ .../src/payment_simulator/p2g_models.py | 2 +- .../src/payment_simulator/store.py | 200 +++++-- .../tests/test_p2g_hosted_page.py | 491 ++++++++++++++++++ 7 files changed, 848 insertions(+), 40 deletions(-) create mode 100644 tools/payment-simulator/src/payment_simulator/hosted_page.py create mode 100644 tools/payment-simulator/tests/test_p2g_hosted_page.py diff --git a/tools/payment-simulator/contracts/openapi.json b/tools/payment-simulator/contracts/openapi.json index 7581e7c763..2f4760c3c0 100644 --- a/tools/payment-simulator/contracts/openapi.json +++ b/tools/payment-simulator/contracts/openapi.json @@ -211,7 +211,8 @@ { "enum": [ "payer-rejected", - "request-expired" + "request-expired", + "payer-cancelled" ], "type": "string" }, @@ -1618,6 +1619,16 @@ "minLength": 1, "type": "string" } + }, + { + "in": "header", + "name": "X-Return-URL", + "required": false, + "schema": { + "maxLength": 200, + "minLength": 1, + "type": "string" + } } ], "requestBody": { diff --git a/tools/payment-simulator/src/payment_simulator/api.py b/tools/payment-simulator/src/payment_simulator/api.py index c9cc668e82..b8073094cb 100644 --- a/tools/payment-simulator/src/payment_simulator/api.py +++ b/tools/payment-simulator/src/payment_simulator/api.py @@ -8,12 +8,14 @@ from dataclasses import dataclass, field from decimal import Decimal, InvalidOperation from pathlib import Path +from urllib.parse import parse_qsl from fastapi import FastAPI, Request from fastapi.openapi.utils import get_openapi -from fastapi.responses import Response +from fastapi.responses import HTMLResponse, Response from pydantic import ValidationError +from .hosted_page import CONTENT_SECURITY_POLICY, outcome_url, render from .models import ( Acknowledgement, ApiError, @@ -25,11 +27,13 @@ Transaction, UpdateRequest, invalid, + not_found, ) from .p2g_models import CollectionAccepted, CollectionRequest, CollectionStatus -from .store import Scope, dumps +from .store import DECISIONS, Scope, dumps BODY_LIMIT = 65536 +FORM_LIMIT = 4096 @dataclass(frozen=True) @@ -46,6 +50,7 @@ class Settings: "https://programme.example.test/callback", "https://programme.example.test/api/v1/batch", ) + return_urls: tuple[str, ...] = () currencies: dict[str, int] = field(default_factory=lambda: {"USD": 2}) modes: tuple[str, ...] = ("00",) manual: bool = False @@ -258,6 +263,7 @@ async def mark_synthetic(request, call_next): } institution = parameter("X-Registering-Institution-ID", maximum=12) callback = parameter("X-Callback-URL", maximum=100) + return_url = parameter("X-Return-URL", required=False, maximum=200) @app.exception_handler(ApiError) async def api_error(_, exc): @@ -403,14 +409,28 @@ async def details(request: Request): ) ) - def collection_scope(request, *, callback=False): + def collection_scope(request, *, callback=False, return_url=False): scope = authenticated( request, settings, tenant_header="X-Platform-TenantId", callback=callback ) biller = header(request, "X-billerId", 20) if biller not in settings.billers: raise ApiError(403, "auth.forbidden", "Biller is not permitted") - return Scope(scope.producer, scope.tenant, institution=biller, callback=scope.callback) + target = header(request, "X-Return-URL", 200, required=False) if return_url else None + if target is not None and target not in settings.return_urls: + raise ApiError( + 403, + "auth.forbidden", + "Return URL is not allowed; add it with serve --return-url", + "X-Return-URL", + ) + return Scope( + scope.producer, + scope.tenant, + institution=biller, + callback=scope.callback, + return_url=target or "", + ) @app.post( "/rtpRequest", @@ -420,12 +440,13 @@ def collection_scope(request, *, callback=False): parameter("X-billerId"), parameter("X-CorrelationID", maximum=12), callback, + return_url, model=CollectionRequest, tenant_header="X-Platform-TenantId", ), ) async def request_collection(request: Request): - scope = collection_scope(request, callback=True) + scope = collection_scope(request, callback=True, return_url=True) correlation = header(request, "X-CorrelationID", 12) queries(request, set()) value = await body(request, CollectionRequest) @@ -458,6 +479,53 @@ async def collection_status(request: Request): response.headers["X-CorrelationID"] = correlation return response + def hosted_response(view, *, status=200): + response = HTMLResponse(render(view), status_code=status) + # The page URL is a capability: keep it out of caches and Referer headers. + response.headers["Cache-Control"] = "no-store" + response.headers["Referrer-Policy"] = "no-referrer" + response.headers["Content-Security-Policy"] = CONTENT_SECURITY_POLICY + return response + + def hosted_id(request): + transfer_id = request.path_params["transferRequestId"] + if not 1 <= len(transfer_id) <= 50: + raise not_found() + return transfer_id + + @app.get("/pay/{transferRequestId}", include_in_schema=False) + async def pay_page(request: Request): + return hosted_response(store.hosted_page(hosted_id(request))) + + @app.post("/pay/{transferRequestId}", include_in_schema=False) + async def pay_decision(request: Request): + transfer_id = hosted_id(request) + media = request.headers.get("Content-Type", "").split(";", 1)[0].strip().lower() + if media != "application/x-www-form-urlencoded": + raise ApiError(415, "request.media-type", "Use application/x-www-form-urlencoded") + raw = bytearray() + async for chunk in request.stream(): + if len(raw) + len(chunk) > FORM_LIMIT: + raise ApiError(413, "request.too-large", "Request exceeds profile limit") + raw.extend(chunk) + try: + pairs = parse_qsl(raw.decode(), keep_blank_values=True, strict_parsing=bool(raw)) + except (UnicodeError, ValueError): + raise invalid() from None + fields = dict(pairs) + if len(fields) != len(pairs) or not set(fields) <= {"token", "decision"}: + raise invalid() + # Check the token before the decision so a stranger learns nothing about the request. + store.hosted_page(transfer_id) + if fields.get("token") is None: + raise ApiError(403, "auth.forbidden", "Form token is not valid") + if fields.get("decision") not in DECISIONS: + raise invalid("decision") + view = store.hosted_page(transfer_id, fields["token"], fields["decision"]) + if view["decided"] and view["return_url"]: + return Response(status_code=303, headers={"Location": outcome_url(view)}) + return hosted_response(view) + def openapi(): if app.openapi_schema: return app.openapi_schema diff --git a/tools/payment-simulator/src/payment_simulator/cli.py b/tools/payment-simulator/src/payment_simulator/cli.py index e41fb042c5..76b3605f6d 100644 --- a/tools/payment-simulator/src/payment_simulator/cli.py +++ b/tools/payment-simulator/src/payment_simulator/cli.py @@ -13,6 +13,8 @@ from .api import Settings, create_app from .store import Store, dumps +OUTCOMES = ("paid", "failed", "expired", "cancelled") + def parser(): root = argparse.ArgumentParser(description=__doc__) @@ -37,6 +39,7 @@ def parser(): "payer-account", "biller", "callback-url", + "return-url", "currency", ): serve.add_argument(f"--{option}", action="append") @@ -54,7 +57,19 @@ def parser(): collection.add_argument("--producer", default="registry") collection.add_argument("--tenant", default="pilot") collection.add_argument("--biller", default="ministry") - collection.add_argument("--outcome", choices=("paid", "failed", "expired"), required=True) + collection.add_argument("--outcome", choices=OUTCOMES, required=True) + + payer = commands.add_parser( + "payer-outcome", help="choose the outcome for one payer financial address" + ) + payer.add_argument("--database", type=Path, required=True) + payer.add_argument("--producer", default="registry") + payer.add_argument("--tenant", default="pilot") + payer.add_argument("--biller", default="ministry") + payer.add_argument("--address", required=True, help="payerFiDetails.financialAddress") + choice = payer.add_mutually_exclusive_group(required=True) + choice.add_argument("--outcome", choices=OUTCOMES) + choice.add_argument("--remove", action="store_true", help="delete the rule for --address") advance = commands.add_parser( "advance", help="advance persisted instructions one or more steps" @@ -110,6 +125,7 @@ def serve_settings(args): payer_accounts=tuple(args.payer_account or defaults.payer_accounts), billers=tuple(args.biller or defaults.billers), callback_urls=tuple(args.callback_url or defaults.callback_urls), + return_urls=tuple(args.return_url or defaults.return_urls), currencies=currencies, modes=tuple(args.mode or defaults.modes), manual=args.manual, @@ -131,6 +147,12 @@ def serve_settings(args): raise ValueError( "--callback-url must be an absolute HTTP(S) URL of at most 100 characters" ) + for url in settings.return_urls: + parsed = urlsplit(url) + if len(url) > 200 or parsed.scheme not in ("http", "https") or not parsed.netloc: + raise ValueError( + "--return-url must be an absolute HTTP(S) URL of at most 200 characters" + ) settings.token() # Fail at startup with a useful error; re-read for each request on rotation. if args.token_file.stat().st_mode & 0o077: raise ValueError("token file must be private; run chmod 600 on it") @@ -172,6 +194,17 @@ def main(): Store(args.database).collection_scenario( args.producer, args.tenant, args.biller, args.outcome ) + elif args.command == "payer-outcome": + if not ( + 1 <= len(args.producer) <= 50 + and 1 <= len(args.tenant) <= 20 + and 1 <= len(args.biller) <= 20 + and 1 <= len(args.address) <= 30 + ): + raise ValueError("payer outcome scope or address exceeds its profile length") + Store(args.database).payer_outcome( + args.producer, args.tenant, args.biller, args.address, args.outcome + ) elif args.command == "inspect": print(dumps(Store(args.database, create=False).inspect(args.batch_id), indent=2)) elif args.command == "inspect-collections": diff --git a/tools/payment-simulator/src/payment_simulator/hosted_page.py b/tools/payment-simulator/src/payment_simulator/hosted_page.py new file mode 100644 index 0000000000..955f3bfc4d --- /dev/null +++ b/tools/payment-simulator/src/payment_simulator/hosted_page.py @@ -0,0 +1,69 @@ +"""Server-rendered HTML for the hosted payment page: no JavaScript and no external assets.""" + +from html import escape +from urllib.parse import parse_qsl, urlencode, urlsplit, urlunsplit + +BANNER = "Synthetic payment simulator, no real money" +LABELS = { + "paid": "Paid", + "failed": "Declined", + "cancelled": "Cancelled", + "expired": "Expired", +} +# A strict policy: the page loads nothing and runs nothing. It sets no form-action +# directive because browsers apply that to the redirect that follows a submission. +CONTENT_SECURITY_POLICY = ( + "default-src 'none'; style-src 'unsafe-inline'; frame-ancestors 'none'; base-uri 'none'" +) +STYLE = ( + "body{font:16px/1.5 system-ui,sans-serif;max-width:32rem;margin:0 auto;padding:1rem}" + ".banner{background:#fff3cd;border:2px solid #856404;padding:.75rem;font-weight:bold}" + "dl{display:grid;grid-template-columns:auto 1fr;gap:.25rem 1rem}dt{font-weight:bold}" + "button{font:inherit;padding:.5rem 1rem;margin:.25rem .25rem .25rem 0}" +) + + +def amount_text(view): + scale = view["scale"] + return f"{view['amount']:.{scale}f} {view['currency']}" + + +def outcome_url(view): + """The return URL with the transfer ID and final outcome appended to its query.""" + parts = urlsplit(view["return_url"]) + query = [ + *parse_qsl(parts.query, keep_blank_values=True), + ("transferRequestId", view["transfer_id"]), + ("status", view["outcome"]), + ] + return urlunsplit(parts._replace(query=urlencode(query))) + + +def render(view): + bill = escape(str(view["bill_id"])) + biller = escape(view["payload"]["billDetails"]["billerName"]) + details = ( + f"
Biller
{biller}
Bill
{bill}
" + f"
Amount
{escape(amount_text(view))}
" + ) + if view["final"]: + label = LABELS[view["outcome"]] + body = f"

Result: {label}. This request is final.

" + if view["return_url"]: + body += f'

Return to the service

' + else: + body = ( + '
' + f'' + '' + '' + '' + "
" + ) + return ( + '' + '' + '' + f"{BANNER}" + f'

Pay a bill

{details}{body}' + ) diff --git a/tools/payment-simulator/src/payment_simulator/p2g_models.py b/tools/payment-simulator/src/payment_simulator/p2g_models.py index f1d1a8d388..4b7b1b1551 100644 --- a/tools/payment-simulator/src/payment_simulator/p2g_models.py +++ b/tools/payment-simulator/src/payment_simulator/p2g_models.py @@ -50,4 +50,4 @@ class CollectionStatus(WireModel): paymentStatus: Literal["PENDING", "PAID", "FAILED", "EXPIRED"] lastUpdateDate: Annotated[int, Field(ge=0, description="Unix timestamp in seconds")] PaymentReferenceID: Id20 | None = None - failureReason: Literal["payer-rejected", "request-expired"] | None = None + failureReason: Literal["payer-rejected", "request-expired", "payer-cancelled"] | None = None diff --git a/tools/payment-simulator/src/payment_simulator/store.py b/tools/payment-simulator/src/payment_simulator/store.py index bbb29db6ee..3561e6499c 100644 --- a/tools/payment-simulator/src/payment_simulator/store.py +++ b/tools/payment-simulator/src/payment_simulator/store.py @@ -1,8 +1,10 @@ """One SQLite transaction owns each command, state advance, and simulated credit.""" import hashlib +import hmac import json import os +import secrets import sqlite3 from contextlib import contextmanager from dataclasses import dataclass @@ -16,7 +18,7 @@ from .models import ApiError, invalid, not_found MAX_MINOR = 9007199254740991 -SCHEMA_VERSION = 2 +SCHEMA_VERSION = 3 SCHEMA = """ CREATE TABLE mappings ( tenant TEXT, institution TEXT, payee TEXT, mode TEXT, address TEXT NOT NULL, bank TEXT, @@ -69,6 +71,28 @@ ); """ +# Hosted payment page state. Every collection request has one row: a form token for the +# page, the optional return URL, whether the request waits for the payer, and the decision. +HOSTED_SCHEMA = """ +CREATE TABLE IF NOT EXISTS collection_hosted ( + transfer_id TEXT PRIMARY KEY REFERENCES collection_requests(transfer_id), + form_token TEXT NOT NULL, return_url TEXT, hold INTEGER NOT NULL, decision TEXT +); +CREATE TABLE IF NOT EXISTS payer_outcomes ( + producer TEXT, tenant TEXT, biller TEXT, address TEXT, outcome TEXT NOT NULL, + PRIMARY KEY (producer, tenant, biller, address) +) +""" + +# Each outcome maps to its terminal (requestStatus, paymentStatus, failureReason). +TERMINAL = { + "paid": ("COM", "PAID", None), + "failed": ("RJC", "FAILED", "payer-rejected"), + "expired": ("EXP", "EXPIRED", "request-expired"), + "cancelled": ("RJC", "FAILED", "payer-cancelled"), +} +DECISIONS = {"pay": "paid", "decline": "failed", "cancel": "cancelled"} + def dumps(value, **kwargs): return simplejson.dumps(value, use_decimal=True, allow_nan=False, ensure_ascii=False, **kwargs) @@ -120,6 +144,7 @@ class Scope: institution: str = "" program: str = "" callback: str = "" + return_url: str = "" class Store: @@ -140,16 +165,21 @@ def __init__(self, path, *, create=True): if version == 0 and create: if db.execute("SELECT name FROM sqlite_master WHERE type='table'").fetchone(): raise ValueError("unrecognized database; choose a fresh state file") - for statement in (SCHEMA + COLLECTION_SCHEMA).split(";"): - if statement.strip(): - db.execute(statement) + self.create_tables(db, SCHEMA + COLLECTION_SCHEMA + HOSTED_SCHEMA) db.execute(f"PRAGMA user_version = {SCHEMA_VERSION}") - elif version == 1 and create: - # A single additive upgrade preserves the original G2P demo state. - # Keep it in this transaction; no reset or migration framework. - for statement in COLLECTION_SCHEMA.split(";"): - if statement.strip(): - db.execute(statement) + elif version in (1, 2) and create: + # Additive upgrades preserve the original G2P demo state and earlier + # collection requests. Keep them in this transaction; no migration framework. + self.create_tables(db, (COLLECTION_SCHEMA if version == 1 else "") + HOSTED_SCHEMA) + # Requests accepted before the hosted page existed get a form token too. + for row in db.execute( + "SELECT transfer_id FROM collection_requests WHERE transfer_id NOT IN " + "(SELECT transfer_id FROM collection_hosted)" + ).fetchall(): + db.execute( + "INSERT INTO collection_hosted VALUES (?, ?, NULL, 0, NULL)", + (row["transfer_id"], secrets.token_urlsafe(32)), + ) db.execute(f"PRAGMA user_version = {SCHEMA_VERSION}") elif version != SCHEMA_VERSION: raise ValueError( @@ -157,6 +187,12 @@ def __init__(self, path, *, create=True): "or choose a fresh state file" ) + @staticmethod + def create_tables(db, script): + for statement in script.split(";"): + if statement.strip(): + db.execute(statement) + @contextmanager def connection(self, *, write=False): db = sqlite3.connect(self.path, timeout=5, isolation_level=None) @@ -173,14 +209,16 @@ def connection(self, *, write=False): db.close() def receipt(self, db, scope, operation, command_id, body): - digest = fingerprint( - { - "body": body, - "institution": scope.institution, - "program": scope.program, - "callback": scope.callback, - } - ) + identity = { + "body": body, + "institution": scope.institution, + "program": scope.program, + "callback": scope.callback, + } + if scope.return_url: + # Absent when unset, so receipts that predate the return URL keep their fingerprint. + identity["returnUrl"] = scope.return_url + digest = fingerprint(identity) row = db.execute( "SELECT fingerprint, response FROM commands WHERE producer=? AND tenant=? " "AND operation=? AND command_id=?", @@ -448,11 +486,26 @@ def request_collection(self, scope, request, currencies): (scope.producer, scope.tenant, scope.institution, request.billID), ).fetchone(): raise ApiError(409, "collection.bill-in-use", "Bill already has a payment request") - scenario = db.execute( - "SELECT outcome FROM collection_scenarios WHERE producer=? AND tenant=? AND biller=?", - (scope.producer, scope.tenant, scope.institution), + # Precedence for requests that never reach the hosted page: payer rule, then + # the biller's scenario. A hosted decision overrides both when it is made. + rule = db.execute( + "SELECT outcome FROM payer_outcomes WHERE producer=? AND tenant=? AND biller=? " + "AND address=?", + ( + scope.producer, + scope.tenant, + scope.institution, + request.payerFiDetails.financialAddress, + ), ).fetchone() - transfer_id = str(uuid4()) + scenario = ( + rule + or db.execute( + "SELECT outcome FROM collection_scenarios WHERE producer=? AND tenant=? AND biller=?", + (scope.producer, scope.tenant, scope.institution), + ).fetchone() + ) + transfer_id = str(uuid4()) # 122 random bits: the ID is the page's capability. db.execute( "INSERT INTO collection_requests VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 0, ?)", ( @@ -471,6 +524,17 @@ def request_collection(self, scope, request, currencies): int(datetime.now(timezone.utc).timestamp()), ), ) + db.execute( + "INSERT INTO collection_hosted VALUES (?, ?, ?, ?, NULL)", + ( + transfer_id, + secrets.token_urlsafe(32), + scope.return_url or None, + # A request with a return URL waits for the payer unless a payer rule + # already decides it. + int(bool(scope.return_url) and rule is None), + ), + ) response = { "responseCode": "00", "responseDescription": "Accepted", @@ -490,15 +554,16 @@ def collection_status(self, scope, transfer_id): ).fetchone() if row is None: raise not_found() + return self.status_response(row) + + @staticmethod + def status_response(row): + transfer_id = row["transfer_id"] request_status, payment_status = "PND", "PENDING" if row["stage"] > 0 and row["outcome"] == "paid": request_status = "COM" # RTP completed is still not evidence of payment. if row["stage"] == 2: - request_status, payment_status = { - "paid": ("COM", "PAID"), - "failed": ("RJC", "FAILED"), - "expired": ("EXP", "EXPIRED"), - }[row["outcome"]] + request_status, payment_status, _ = TERMINAL[row["outcome"]] response = { "transferRequestId": transfer_id, "RequestId": row["request_id"], @@ -512,12 +577,80 @@ def collection_status(self, scope, transfer_id): } if payment_status == "PAID": response["PaymentReferenceID"] = row["reference"] - elif payment_status == "FAILED": - response["failureReason"] = "payer-rejected" - elif payment_status == "EXPIRED": - response["failureReason"] = "request-expired" + elif row["stage"] == 2: + response["failureReason"] = TERMINAL[row["outcome"]][2] return response + def payer_outcome(self, producer, tenant, biller, address, outcome): + """Map a payer financial address to an outcome; None removes the rule.""" + with self.connection(write=True) as db: + if outcome is None: + db.execute( + "DELETE FROM payer_outcomes WHERE producer=? AND tenant=? AND biller=? " + "AND address=?", + (producer, tenant, biller, address), + ) + return + db.execute( + "INSERT INTO payer_outcomes VALUES (?, ?, ?, ?, ?) " + "ON CONFLICT(producer, tenant, biller, address) DO UPDATE SET " + "outcome=excluded.outcome", + (producer, tenant, biller, address, outcome), + ) + + def hosted_page(self, transfer_id, token=None, decision=None): + """Read the hosted page state, optionally applying one payer decision. + + The unguessable transfer ID is the capability. A decision needs the form token + stored with the request and is ignored once the request is final. + """ + with self.connection(write=decision is not None) as db: + row = db.execute( + "SELECT * FROM collection_requests JOIN collection_hosted USING(transfer_id) " + "LEFT JOIN collection_payments USING(transfer_id) WHERE transfer_id=?", + (transfer_id,), + ).fetchone() + if row is None: + raise not_found() + decided = False + if decision is not None: + if token is None or not hmac.compare_digest( + token.encode(), row["form_token"].encode() + ): + raise ApiError(403, "auth.forbidden", "Form token is not valid") + if row["stage"] < 2: + self.settle(db, row, DECISIONS[decision], decision) + decided = True + row = db.execute( + "SELECT * FROM collection_requests JOIN collection_hosted " + "USING(transfer_id) LEFT JOIN collection_payments USING(transfer_id) " + "WHERE transfer_id=?", + (transfer_id,), + ).fetchone() + view = dict(row) + view["payload"] = json.loads(row["payload"]) + view["final"] = row["stage"] == 2 + view["decided"] = decided + view["amount"] = Decimal(row["amount_minor"]).scaleb(-row["scale"]) + return view + + @staticmethod + def settle(db, row, outcome, decision): + updated = int(datetime.now(timezone.utc).timestamp()) + if outcome == "paid" and row["reference"] is None: + db.execute( + "INSERT INTO collection_payments VALUES (?, ?, ?)", + (row["transfer_id"], "SIM-" + uuid4().hex[:16], updated), + ) + db.execute( + "UPDATE collection_requests SET outcome=?, stage=2, last_update=? WHERE transfer_id=?", + (outcome, updated, row["transfer_id"]), + ) + db.execute( + "UPDATE collection_hosted SET hold=0, decision=? WHERE transfer_id=?", + (decision, row["transfer_id"]), + ) + def collection_scenario(self, producer, tenant, biller, outcome): with self.connection(write=True) as db: db.execute( @@ -527,7 +660,10 @@ def collection_scenario(self, producer, tenant, biller, outcome): ) def advance_collections(self, db): - rows = db.execute("SELECT * FROM collection_requests WHERE stage < 2").fetchall() + rows = db.execute( + "SELECT * FROM collection_requests WHERE stage < 2 AND transfer_id NOT IN " + "(SELECT transfer_id FROM collection_hosted WHERE hold=1)" + ).fetchall() for row in rows: updated = int(datetime.now(timezone.utc).timestamp()) if row["stage"] == 1 and row["outcome"] == "paid": diff --git a/tools/payment-simulator/tests/test_p2g_hosted_page.py b/tools/payment-simulator/tests/test_p2g_hosted_page.py new file mode 100644 index 0000000000..8fbf306fde --- /dev/null +++ b/tools/payment-simulator/tests/test_p2g_hosted_page.py @@ -0,0 +1,491 @@ +"""Hosted payment page, return URL, cancelled outcome and per-payer outcomes.""" + +import re +import sqlite3 +import uuid +from dataclasses import replace +from urllib.parse import parse_qs, urlsplit + +import pytest +from fastapi.testclient import TestClient + +from payment_simulator import cli +from payment_simulator.api import Settings, create_app +from payment_simulator.store import Store +from tests.test_p2g_service import create, intent, status + +RETURN = "https://portal.example.test/paid" +RETURN_HEADER = {"X-Return-URL": RETURN} +FORM = {"Content-Type": "application/x-www-form-urlencoded"} + + +@pytest.fixture +def service(tmp_path): + token = tmp_path / "token" + token.write_text("synthetic-p2g-token") + token.chmod(0o600) + settings = Settings( + token_file=token, + manual=True, + return_urls=(RETURN, "https://portal.example.test/done?lang=en"), + ) + store = Store(tmp_path / "state.sqlite") + # Redirects point at an unreachable synthetic host, so never follow them. + with TestClient(create_app(settings, store), follow_redirects=False) as client: + yield client, settings, store + + +def page(client, transfer_id): + return client.get(f"/pay/{transfer_id}") + + +def token_of(html): + match = re.search(r'name="token" value="([^"]+)"', html) + assert match, html + return match.group(1) + + +def decide(client, transfer_id, decision, *, token=None, **extra): + if token is None: + token = token_of(page(client, transfer_id).text) + body = f"token={token}&decision={decision}" if token else f"decision={decision}" + return client.post(f"/pay/{transfer_id}", content=body, headers={**FORM, **extra}) + + +def accept(client, request=None, **extra): + response = create(client, request, **extra) + assert response.status_code == 200, response.text + return response.json()["transferRequestId"] + + +def poll(client, transfer_id): + response = status(client, transfer_id) + assert response.status_code == 200 + return response.json() + + +def test_return_url_must_be_allow_listed(service): + client, settings, store = service + response = create(client, **{"X-Return-URL": "https://evil.example.test/steal"}) + assert response.status_code == 403 + assert response.headers["content-type"] == "application/problem+json" + problem = response.json() + assert problem["code"] == "auth.forbidden" + assert problem["field"] == "X-Return-URL" + assert "return-url" in problem["title"].lower() + assert store.inspect_collections()["requestCount"] == 0 + with TestClient(create_app(replace(settings, return_urls=()), store)) as closed: + assert create(closed, **RETURN_HEADER).status_code == 403 + # The refusal spends no command identity. + assert create(client, **RETURN_HEADER).status_code == 200 + + +def test_return_url_header_is_optional_and_single(service): + client, _, _ = service + assert create(client).status_code == 200 + blank = create( + client, + intent(requestId="fee-003", rtpId=1003, billID="bill-003"), + **{"X-Return-URL": ""}, + ) + assert blank.status_code == 400 + + +def test_return_url_takes_part_in_the_idempotency_fingerprint(service): + client, _, _ = service + first = create(client, **RETURN_HEADER) + assert create(client, **RETURN_HEADER).json() == first.json() + changed = create(client, **{"X-Return-URL": "https://portal.example.test/done?lang=en"}) + assert changed.status_code == 409 + assert changed.json()["code"] == "request.id-reused" + assert create(client).status_code == 409 + + +def test_requests_without_return_url_keep_their_fingerprint(service): + client, _, _ = service + accepted = create(client).json() + assert create(client).json() == accepted + + +def test_transfer_ids_are_random_uuid4(service): + client, _, _ = service + ids = [ + accept(client, intent(requestId=f"fee-{n}", rtpId=2000 + n, billID=f"b-{n}")) + for n in range(20) + ] + assert len(set(ids)) == 20 + for transfer_id in ids: + parsed = uuid.UUID(transfer_id) + # UUIDv4 carries 122 random bits from the operating system's CSPRNG. + assert parsed.version == 4 and str(parsed) == transfer_id + + +def test_page_shows_banner_bill_and_three_choices(service): + client, _, _ = service + transfer_id = accept(client, **RETURN_HEADER) + response = page(client, transfer_id) + assert response.status_code == 200 + assert response.headers["content-type"].startswith("text/html") + assert response.headers["X-Payment-Simulator"] == "synthetic" + assert response.headers["Cache-Control"] == "no-store" + assert response.headers["Referrer-Policy"] == "no-referrer" + assert "default-src 'none'" in response.headers["Content-Security-Policy"] + html = response.text + assert "Synthetic payment simulator, no real money" in html + assert "Ministry" in html and "bill-001" in html + assert "25.50 USD" in html + for decision in ("pay", "decline", "cancel"): + assert f'name="decision" value="{decision}"' in html + assert '
x"} + transfer_id = accept(client, request) + html = page(client, transfer_id).text + assert "x" not in html and "<b>x</b>" in html + + +def test_page_needs_no_bearer_token(service): + client, _, _ = service + transfer_id = accept(client) + assert "Authorization" not in client.headers + assert page(client, transfer_id).status_code == 200 + + +@pytest.mark.parametrize("transfer_id", ["unknown", "x" * 51, str(uuid.uuid4())]) +def test_unknown_transfer_is_404_for_both_methods(service, transfer_id): + client, _, _ = service + assert page(client, transfer_id).status_code == 404 + response = client.post(f"/pay/{transfer_id}", content="decision=pay&token=t", headers=FORM) + assert response.status_code == 404 + assert response.json()["code"] == "resource.not-found" + + +@pytest.mark.parametrize( + ("decision", "request_status", "payment_status", "reason", "label"), + [ + ("pay", "COM", "PAID", None, "paid"), + ("decline", "RJC", "FAILED", "payer-rejected", "failed"), + ("cancel", "RJC", "FAILED", "payer-cancelled", "cancelled"), + ], +) +def test_decision_settles_and_redirects( + service, decision, request_status, payment_status, reason, label +): + client, _, store = service + transfer_id = accept(client, **RETURN_HEADER) + response = decide(client, transfer_id, decision) + assert response.status_code == 303 + location = urlsplit(response.headers["Location"]) + assert f"{location.scheme}://{location.netloc}{location.path}" == RETURN + assert parse_qs(location.query) == {"transferRequestId": [transfer_id], "status": [label]} + result = poll(client, transfer_id) + assert (result["requestStatus"], result["paymentStatus"]) == (request_status, payment_status) + assert result.get("failureReason") == reason + assert ("PaymentReferenceID" in result) == (decision == "pay") + assert len(store.inspect_collections()["payments"]) == (decision == "pay") + + +def test_redirect_preserves_an_existing_query(service): + client, _, _ = service + transfer_id = accept(client, **{"X-Return-URL": "https://portal.example.test/done?lang=en"}) + location = urlsplit(decide(client, transfer_id, "pay").headers["Location"]) + assert parse_qs(location.query) == { + "lang": ["en"], + "transferRequestId": [transfer_id], + "status": ["paid"], + } + + +def test_without_return_url_a_result_page_is_shown(service): + client, _, _ = service + transfer_id = accept(client) + response = decide(client, transfer_id, "pay") + assert response.status_code == 200 + assert "Synthetic payment simulator, no real money" in response.text + assert "paid" in response.text.lower() + assert 'name="decision"' not in response.text + assert poll(client, transfer_id)["paymentStatus"] == "PAID" + + +@pytest.mark.parametrize("token", [None, "", "wrong-token"]) +def test_missing_or_wrong_form_token_is_refused(service, token): + client, _, store = service + transfer_id = accept(client, **RETURN_HEADER) + other = accept(client, intent(requestId="fee-002", rtpId=1002, billID="bill-002")) + real = token_of(page(client, other).text) + body = "decision=pay" if token is None else f"decision=pay&token={token}" + for candidate in (body, f"decision=pay&token={real}"): + response = client.post(f"/pay/{transfer_id}", content=candidate, headers=FORM) + assert response.status_code == 403 + assert response.json()["code"] == "auth.forbidden" + assert poll(client, transfer_id)["paymentStatus"] == "PENDING" + assert store.inspect_collections()["payments"] == [] + + +@pytest.mark.parametrize( + ("body", "headers", "code"), + [ + ("token={t}&decision=refund", FORM, 400), + ("token={t}", FORM, 400), + ("token={t}&token={t}&decision=pay", FORM, 400), + ("token={t}&decision=pay&extra=1", FORM, 400), + ('{{"decision":"pay"}}', {"Content-Type": "application/json"}, 415), + ], +) +def test_malformed_submissions_change_nothing(service, body, headers, code): + client, _, _ = service + transfer_id = accept(client, **RETURN_HEADER) + token = token_of(page(client, transfer_id).text) + response = client.post(f"/pay/{transfer_id}", content=body.format(t=token), headers=headers) + assert response.status_code == code + assert poll(client, transfer_id)["paymentStatus"] == "PENDING" + + +def test_oversized_submission_is_refused(service): + client, _, _ = service + transfer_id = accept(client) + response = client.post(f"/pay/{transfer_id}", content="a=" + "b" * 10000, headers=FORM) + assert response.status_code == 413 + + +def test_second_submit_shows_the_final_state_and_changes_nothing(service): + client, _, store = service + transfer_id = accept(client, **RETURN_HEADER) + token = token_of(page(client, transfer_id).text) + assert decide(client, transfer_id, "pay", token=token).status_code == 303 + before = poll(client, transfer_id) + for decision in ("pay", "decline", "cancel"): + again = decide(client, transfer_id, decision, token=token) + assert again.status_code == 200 + assert "paid" in again.text.lower() + assert 'name="decision"' not in again.text + assert RETURN in again.text + assert poll(client, transfer_id) == before + assert len(store.inspect_collections()["payments"]) == 1 + assert 'name="decision"' not in page(client, transfer_id).text + + +def test_return_url_requests_wait_for_the_payer(service): + client, _, store = service + waiting = accept(client, **RETURN_HEADER) + plain = accept(client, intent(requestId="fee-002", rtpId=1002, billID="bill-002")) + store.advance(3) + assert poll(client, waiting)["requestStatus"] == "PND" + assert poll(client, waiting)["paymentStatus"] == "PENDING" + assert poll(client, plain)["paymentStatus"] == "PAID" + assert decide(client, waiting, "pay").status_code == 303 + assert poll(client, waiting)["paymentStatus"] == "PAID" + + +def test_page_on_a_finished_transfer_shows_the_final_state(service): + client, _, store = service + transfer_id = accept(client) + store.advance(2) + html = page(client, transfer_id).text + assert "paid" in html.lower() and 'name="decision"' not in html + # A finished page carries no form, and a guessed token is still refused. + assert decide(client, transfer_id, "decline", token="whatever").status_code == 403 + assert poll(client, transfer_id)["paymentStatus"] == "PAID" + + +def test_hosted_decision_beats_the_global_scenario(service): + client, _, store = service + store.collection_scenario("registry", "pilot", "ministry", "failed") + transfer_id = accept(client) + assert decide(client, transfer_id, "pay").status_code == 200 + assert poll(client, transfer_id)["paymentStatus"] == "PAID" + store.advance(3) + assert poll(client, transfer_id)["paymentStatus"] == "PAID" + assert len(store.inspect_collections()["payments"]) == 1 + + +def test_global_scenario_still_applies_without_the_page(service): + client, _, store = service + store.collection_scenario("registry", "pilot", "ministry", "failed") + transfer_id = accept(client) + store.advance(2) + assert poll(client, transfer_id)["failureReason"] == "payer-rejected" + + +def test_cancelled_global_scenario(service): + client, _, store = service + store.collection_scenario("registry", "pilot", "ministry", "cancelled") + transfer_id = accept(client) + store.advance(1) + assert poll(client, transfer_id)["paymentStatus"] == "PENDING" + store.advance(1) + result = poll(client, transfer_id) + assert (result["requestStatus"], result["paymentStatus"]) == ("RJC", "FAILED") + assert result["failureReason"] == "payer-cancelled" + assert "PaymentReferenceID" not in result + + +def test_payer_rule_beats_the_global_scenario(service): + client, _, store = service + store.payer_outcome("registry", "pilot", "ministry", "synthetic-citizen", "failed") + mine = accept(client) + other_request = intent(requestId="fee-002", rtpId=1002, billID="bill-002") + other_request["payerFiDetails"] = {"payerFIBIC": "TESTBANK", "financialAddress": "someone-else"} + other = accept(client, other_request) + store.advance(2) + assert poll(client, mine)["failureReason"] == "payer-rejected" + assert poll(client, other)["paymentStatus"] == "PAID" + + +def test_payer_rule_releases_a_waiting_return_url_request(service): + client, _, store = service + store.payer_outcome("registry", "pilot", "ministry", "synthetic-citizen", "cancelled") + transfer_id = accept(client, **RETURN_HEADER) + store.advance(2) + assert poll(client, transfer_id)["failureReason"] == "payer-cancelled" + assert "cancelled" in page(client, transfer_id).text.lower() + + +def test_hosted_decision_beats_the_payer_rule(service): + client, _, store = service + store.payer_outcome("registry", "pilot", "ministry", "synthetic-citizen", "failed") + store.collection_scenario("registry", "pilot", "ministry", "expired") + transfer_id = accept(client) + assert decide(client, transfer_id, "pay").status_code == 200 + store.advance(3) + assert poll(client, transfer_id)["paymentStatus"] == "PAID" + + +def test_payer_rule_can_be_replaced_and_removed(service): + client, _, store = service + store.payer_outcome("registry", "pilot", "ministry", "synthetic-citizen", "failed") + store.payer_outcome("registry", "pilot", "ministry", "synthetic-citizen", "expired") + first = accept(client) + store.payer_outcome("registry", "pilot", "ministry", "synthetic-citizen", None) + second = accept(client, intent(requestId="fee-002", rtpId=1002, billID="bill-002")) + store.advance(2) + assert poll(client, first)["paymentStatus"] == "EXPIRED" + assert poll(client, second)["paymentStatus"] == "PAID" + + +def test_requests_from_before_the_upgrade_get_a_page(service): + client, _, store = service + transfer_id = accept(client) + with sqlite3.connect(store.path) as db: + db.execute("DROP TABLE collection_hosted") + db.execute("DROP TABLE payer_outcomes") + db.execute("PRAGMA user_version=2") + Store(store.path) + assert "Synthetic payment simulator" in page(client, transfer_id).text + assert decide(client, transfer_id, "decline").status_code == 200 + assert poll(client, transfer_id)["failureReason"] == "payer-rejected" + + +def run_cli(monkeypatch, *arguments): + monkeypatch.setattr("sys.argv", ["payment-simulator", *arguments]) + cli.main() + + +def test_payer_outcome_command(service, monkeypatch, capsys): + client, _, store = service + database = str(store.path) + run_cli( + monkeypatch, + "payer-outcome", + "--database", + database, + "--address", + "synthetic-citizen", + "--outcome", + "failed", + ) + transfer_id = accept(client) + store.advance(2) + assert poll(client, transfer_id)["paymentStatus"] == "FAILED" + run_cli( + monkeypatch, + "payer-outcome", + "--database", + database, + "--address", + "synthetic-citizen", + "--remove", + ) + again = accept(client, intent(requestId="fee-002", rtpId=1002, billID="bill-002")) + store.advance(2) + assert poll(client, again)["paymentStatus"] == "PAID" + for bad in ( + ["--address", "x"], + ["--address", "x", "--outcome", "paid", "--remove"], + ["--address", "x" * 31, "--outcome", "paid"], + ): + with pytest.raises(SystemExit) as exit_info: + run_cli(monkeypatch, "payer-outcome", "--database", database, *bad) + assert exit_info.value.code == 2 + capsys.readouterr() + + +def test_collection_scenario_accepts_cancelled(service, monkeypatch): + client, _, store = service + run_cli( + monkeypatch, + "collection-scenario", + "--database", + str(store.path), + "--outcome", + "cancelled", + ) + transfer_id = accept(client) + store.advance(2) + assert poll(client, transfer_id)["failureReason"] == "payer-cancelled" + + +@pytest.fixture +def served(tmp_path, monkeypatch): + token = tmp_path / "token" + token.write_text("synthetic-guard-token") + token.chmod(0o600) + calls = [] + monkeypatch.setattr(cli.uvicorn, "run", lambda app, **kwargs: calls.append(app)) + + def run(*extra): + run_cli( + monkeypatch, + "serve", + "--database", + str(tmp_path / "state.sqlite"), + "--token-file", + str(token), + *extra, + ) + + return run, calls + + +def test_serve_return_url_option(served): + run, calls = served + run("--return-url", RETURN, "--return-url", "http://localhost:3000/back") + assert len(calls) == 1 + run() + assert len(calls) == 2 + + +@pytest.mark.parametrize("url", ["ftp://x.example.test/a", "/relative", "https://" + "a" * 200]) +def test_serve_rejects_bad_return_urls(served, capsys, url): + run, calls = served + with pytest.raises(SystemExit) as exit_info: + run("--return-url", url) + assert exit_info.value.code == 2 + assert "--return-url" in capsys.readouterr().err + assert calls == [] From 6f7bdfe04c733408111d5c9defd33f90a4277dfd Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Wed, 18 Nov 2026 20:24:54 +0100 Subject: [PATCH 18/40] docs: describe the hosted payment page, cancelled outcome and payer rules Signed-off-by: Jeremi Joslin --- tools/payment-simulator/P2G-SPEC.md | 86 ++++++++++++++++++++++++----- tools/payment-simulator/README.md | 48 +++++++++++++++- 2 files changed, 118 insertions(+), 16 deletions(-) diff --git a/tools/payment-simulator/P2G-SPEC.md b/tools/payment-simulator/P2G-SPEC.md index 94466ea13f..11592f558d 100644 --- a/tools/payment-simulator/P2G-SPEC.md +++ b/tools/payment-simulator/P2G-SPEC.md @@ -8,8 +8,8 @@ This profile adds two biller-facing operations to the existing G2P simulator: | Observe collection status | `GET /transferRequests/{transferRequestId}` | `200`, current RTP and payment status | It supports one full payment request per bill, with a known payer financial -address. It does not create bills, collect real money, or implement a citizen -checkout. A programme or registry remains responsible for the bill and what +address. It does not create bills, collect real money, or implement a real citizen +checkout. A synthetic hosted payment page is described below. A programme or registry remains responsible for the bill and what confirmed payment permits. Coordinator integration is a separate change. ## GovStack review and source decisions @@ -50,7 +50,9 @@ These are deliberate profile decisions, not full GovStack conformance: | Status correlation | Response `RequestId` identifies the original create command. The GET's fresh `X-CorrelationID` is echoed in the response header. | | Payment evidence | Add `paymentStatus`, original bill/amount/currency, and polling ID. `PaymentReferenceID` exists only for confirmed `PAID`. | | Expiry | Simulate an unpaid request expiring; there is no authored TTL or wall-clock expiry scheduler in this increment. | -| Reissue | One request per bill within producer/tenant/biller scope, including failed/expired requests. Reissue, cancellation, partial payments and refunds need a later explicit policy. | +| Reissue | One request per bill within producer/tenant/biller scope, including failed, expired and cancelled requests. Reissue, partial payments and refunds need a later explicit policy. | +| Return URL | An optional `X-Return-URL` header on create, outside the GovStack body, so the body schema is unchanged. See the hosted payment page below. | +| Cancellation | A payer cancelling at the hosted page, or a `cancelled` fixture outcome, is `RJC/FAILED` with `failureReason: payer-cancelled`. No new status value is added. | The bank-to-Payments payment notification and Payments-to-biller mark-paid advice are not exposed as caller writes. Neither a registry workflow nor a @@ -80,7 +82,11 @@ at most `9007199254740991` minor units. Quote neither amounts nor integer IDs. Require `Content-Type: application/json`, `X-CorrelationID` (1–12 characters, equal to `requestId`), and `X-Callback-URL` (1–100 characters, approved in server configuration). The callback value is retained for wire compatibility; -the mock makes no outbound request. +the mock makes no outbound request. `X-Return-URL` (1–200 characters) is +optional. It must exactly match a value configured with `serve --return-url`, +and none is configured by default. Otherwise the request is refused with `403 +auth.forbidden` and `field: X-Return-URL`, and no request or command identity +is created. All body fields below are required: @@ -127,7 +133,7 @@ before dispatch. After a timeout or lost response, replay the unchanged command to recover its acknowledgement and polling ID. Command identity is `(producer, tenant, collection, requestId)`. Its fingerprint -includes the body, biller and callback URL. Equivalent decimal notation and +includes the body, biller, callback URL and return URL (when present). Equivalent decimal notation and object ordering replay identically; changed content returns `409 request.id-reused`. The acknowledgement, immutable request snapshot, exact amount/scale and selected outcome commit in one SQLite transaction. @@ -169,7 +175,7 @@ All shown fields except `PaymentReferenceID` are always present. `billId`, amount and currency must match the accepted intent. The payment reference is 1–20 characters and is required only when `paymentStatus` is `PAID`; it is absent otherwise. `lastUpdateDate` is an integer Unix timestamp -in seconds. Failed/expired results include the bounded `failureReason` below. +in seconds. Failed, cancelled and expired results include the bounded `failureReason` below. | RTP status | Payment status | Meaning | |---|---|---| @@ -177,14 +183,53 @@ in seconds. Failed/expired results include the bounded `failureReason` below. | `COM` | `PENDING` | RTP exchange completed; payment is still unconfirmed | | `COM` | `PAID` | Full payment confirmed; stable payment reference present | | `RJC` | `FAILED` | Payer rejected this request; `failureReason: payer-rejected` | +| `RJC` | `FAILED` | Payer cancelled this request; `failureReason: payer-cancelled` | | `EXP` | `EXPIRED` | Request expired unpaid; `failureReason: request-expired` | -Only the last three rows are terminal. Terminal results and payment references +Only the last four rows are terminal. Terminal results and payment references remain stable across polls, replays and restarts. A consumer must validate the IDs, amount, currency and status pairing. Unknown or contradictory results remain unresolved, never treated as paid. A future real-provider adapter must map actual payment evidence, not RTP delivery/acceptance, to `PAID`. +## Hosted payment page + +`GET /pay/{transferRequestId}` and `POST /pay/{transferRequestId}` are a +synthetic checkout for a citizen-facing front end. They are not part of the +GovStack profile or the generated OpenAPI, and they need no bearer token. + +- **Capability.** The transfer ID is a UUIDv4, which carries 122 random bits from + the operating system, so it cannot be guessed. Unknown or over-long IDs return + `404`. The page sends `Cache-Control: no-store`, `Referrer-Policy: + no-referrer` and a Content-Security-Policy that allows nothing to load or run. +- **Page.** Server-rendered HTML with inline CSS only: no JavaScript, no external + assets. It shows the banner "Synthetic payment simulator, no real money", the + biller name, bill ID and the amount with the currency's configured scale + (`25.50 USD`, `1200 JPY`), and a form with Pay, Decline and Cancel. +- **CSRF.** Each request has a random form token stored with it and rendered in + the form. A submission must carry it (`application/x-www-form-urlencoded` + fields `token` and `decision`, at most 4 KiB), or the simulator returns `403 + auth.forbidden` and changes nothing. A page on another site cannot read the + token, so it cannot forge a choice. This avoids depending on `Origin` or + `Referer` headers, which browsers and proxies do not always send. Other + malformed submissions return `400`, `413` or `415`. +- **Decisions.** `pay` settles to `COM/PAID` with a payment reference. `decline` + settles to `RJC/FAILED` with `payer-rejected`. `cancel` settles to `RJC/FAILED` + with `payer-cancelled`. The decision settles the request at once, without the + intermediate `COM/PENDING`, so the redirect and the next poll agree. +- **Return.** With a return URL, the first accepted decision answers `303` to + that URL with `transferRequestId` and `status` (`paid`, `failed`, `cancelled`) + appended to any existing query. Without one, a result page is shown. The + parameters are a hint for the front end, not evidence of payment. +- **Finished transfers.** A request is final once it has a terminal state. A + later submit with the right token returns the result page with a link back to + the return URL and changes nothing, so a double click or a replayed POST never + creates a second payment reference. A wrong token is still `403`. +- **Waiting.** A request created with a return URL is not advanced by the worker + or `advance`: it stays `PND/PENDING` until the payer decides. A request without + a return URL advances as before and can also be decided at the page until it + is final. + ## Deterministic local outcomes and verification Select an outcome for future requests only: @@ -194,12 +239,27 @@ uv run payment-simulator collection-scenario --database .state/payments.sqlite \ --producer registry --tenant pilot --biller ministry --outcome paid ``` -Outcomes are `paid` (default), `failed`, or `expired`. Automatic mode advances -them in two worker steps. With `serve --manual`, `advance --steps 1` exposes +Outcomes are `paid` (default), `failed`, `expired` or `cancelled`. Automatic +mode advances them in two worker steps. With `serve --manual`, `advance --steps 1` exposes the intermediate state, and a second step produces the terminal result. The paid scenario deliberately exposes `COM/PENDING` before `COM/PAID`. Expiry is an injected fixture outcome, not proof that a configured real-time TTL passed. +Map one payer to an outcome with `payer-outcome` (`--remove` deletes the rule): + +```sh +uv run payment-simulator payer-outcome --database .state/payments.sqlite \ + --producer registry --tenant pilot --biller ministry \ + --address citizen-decline --outcome failed +``` + +The rule matches `payerFiDetails.financialAddress` exactly and applies to new +requests. An outcome is chosen in this order: the payer's decision at the hosted +page, then the payer rule, then the biller's scenario. A matching payer rule also +stops a request with a return URL from waiting, so that person's request settles +without a visit to the page. The decision still wins if the payer reaches the +page before the request is final, which is easiest to see with `serve --manual`. + The payment receipt and terminal transition commit together, with one receipt per accepted request. `inspect-collections --database ...` provides separate local evidence; it is not a public API. It can filter by `--transfer-request-id`. @@ -209,8 +269,8 @@ target driver for outcome, replay, conflict, scope and lost-response recovery checks. Missing external outcome/restart/witness capabilities remain explicit not-verified skips. Implementation tests additionally cover malformed input, concurrent replay, currency changes, and preservation of G2P state through the -single additive database upgrade from version 1 to version 2. +additive database upgrades from versions 1 and 2 to version 3. The upgrade adds +the hosted-page and payer-rule tables and gives earlier requests a form token. -No programme funding, checkout UI, alias resolution, bill inquiry forwarding, -bank notification ingress, callback delivery, refunds, cancellation, expiry -scheduler, or Coordinator operation is added by this profile. +No programme funding, real checkout, alias resolution, bill inquiry forwarding, +bank notification ingress, callback delivery, refunds, expiry scheduler, or Coordinator operation is added by this profile. diff --git a/tools/payment-simulator/README.md b/tools/payment-simulator/README.md index 0e57ba8a97..138e8ab2cd 100644 --- a/tools/payment-simulator/README.md +++ b/tools/payment-simulator/README.md @@ -58,8 +58,9 @@ server binds to `127.0.0.1:8008`, advances instructions automatically, and serves its OpenAPI at `/openapi.json` and interactive documentation at `/docs`. The token is read on every request, so replacing its contents rotates the credential while preserving the producer identity and replay records. -An existing version 1 database is upgraded to version 2 in one additive -transaction when the server starts, preserving its G2P records and credits. +An existing version 1 or 2 database is upgraded to version 3 in one additive +transaction when the server starts, preserving its G2P records, credits and +collection requests. In another terminal in this directory: @@ -140,12 +141,51 @@ uv run python examples/collect_payment.py --token-file .state/token --run-id exp uv run payment-simulator collection-scenario --database .state/payments.sqlite --outcome paid ``` +Use `--outcome cancelled` for a payer who cancels: it reports `RJC/FAILED` with +`failureReason: payer-cancelled`. To make one named test person always decline, +map their `payerFiDetails.financialAddress` to an outcome. A payer rule beats +the biller's scenario, and `--remove` deletes it: + +```sh +uv run payment-simulator payer-outcome --database .state/payments.sqlite \ + --address citizen-decline --outcome failed +uv run payment-simulator payer-outcome --database .state/payments.sqlite \ + --address citizen-decline --remove +``` + Each run ID here represents a different synthetic bill. The profile allows one request per bill, including failed and expired requests; it has no reissue or refund policy. Keep the original run ID when recovering an uncertain payment. Expiry is a fixture outcome, not a configured real-time deadline. In manual mode, the existing `advance` command advances both G2P and P2G in two steps. +## Send a citizen to pay + +A citizen-facing front end can hand the citizen to a hosted page and get them +back. Start `serve` with the front end's return URL, then add `X-Return-URL` to +`POST /rtpRequest`: + +```sh +uv run payment-simulator serve --database .state/payments.sqlite \ + --token-file .state/token --return-url https://portal.example.test/paid +``` + +Send the citizen to `GET /pay/{transferRequestId}` on the simulator's origin. +The page shows a "Synthetic payment simulator, no real money" banner, the +biller, bill and amount, and three buttons: Pay, Decline and Cancel. The browser +posts the choice back, and the simulator answers `303` to the return URL with +`transferRequestId` and `status` (`paid`, `failed` or `cancelled`) added to its +query. Without a return URL the page shows the result instead. + +The redirect is a hint. The front end must still poll +`GET /transferRequests/{transferRequestId}` and check the payment status and +reference before it acts. The page needs no bearer token: the transfer ID is a +random UUIDv4 and acts as the capability, and each submission carries a form +token stored with the request. A request with a return URL stays `PND/PENDING` +until the payer decides, and the decision settles it at once. Requests without +a return URL behave as before. See [the P2G profile](P2G-SPEC.md#hosted-payment-page) +for precedence and refusals. + ## Configuration and boundaries The local credential belongs to one producer per server. The defaults are: @@ -158,6 +198,7 @@ The local credential belongs to one producer per server. The defaults are: | Programme | `cash-support` | `--program` | | Payer account | `programme-account` | `--payer-account` | | P2G biller | `ministry` | `--biller` | +| Accepted return URLs | none (any `X-Return-URL` is refused) | `--return-url` | | Currency and decimal scale | `USD:2` | `--currency` | | Submission mode | `00` | `--mode` (`00`, `01`, `03`) | | Accepted callback URLs | `https://programme.example.test/callback`, `https://programme.example.test/api/v1/batch` | `--callback-url` | @@ -173,7 +214,8 @@ Use polling. Receipts are retained for the lifetime of this disposable database. There is no receipt expiry, reset API, real rail, production identity provider, high availability or container publishing. An unsupported database version is refused; only the additive v1-to-v2 upgrade is -provided. Programme funding and real citizen checkout are outside this mock. +provided. Programme funding and real citizen checkout are outside this mock. The hosted +page is a synthetic stand-in with no card or bank entry. Do not use real beneficiary data or expose this development server as a payment service. From badde47179852eb365458986e9ed3a7191e1b003 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Wed, 18 Nov 2026 20:42:58 +0100 Subject: [PATCH 19/40] fix: settle payer-rule requests at creation A request whose payer has a configured outcome stayed pending until the worker advanced it, so a fast click on the hosted page could decide it first. The rule now settles the request when it is created. Signed-off-by: Jeremi Joslin --- tools/payment-simulator/P2G-SPEC.md | 16 +++-- tools/payment-simulator/README.md | 6 +- .../src/payment_simulator/store.py | 9 ++- .../tests/test_p2g_hosted_page.py | 69 +++++++++++++++++-- 4 files changed, 84 insertions(+), 16 deletions(-) diff --git a/tools/payment-simulator/P2G-SPEC.md b/tools/payment-simulator/P2G-SPEC.md index 11592f558d..340acdd6b9 100644 --- a/tools/payment-simulator/P2G-SPEC.md +++ b/tools/payment-simulator/P2G-SPEC.md @@ -226,7 +226,8 @@ GovStack profile or the generated OpenAPI, and they need no bearer token. the return URL and changes nothing, so a double click or a replayed POST never creates a second payment reference. A wrong token is still `403`. - **Waiting.** A request created with a return URL is not advanced by the worker - or `advance`: it stays `PND/PENDING` until the payer decides. A request without + or `advance`: it stays `PND/PENDING` until the payer decides, unless a payer rule + settled it at creation. A request without a return URL advances as before and can also be decided at the page until it is final. @@ -254,11 +255,14 @@ uv run payment-simulator payer-outcome --database .state/payments.sqlite \ ``` The rule matches `payerFiDetails.financialAddress` exactly and applies to new -requests. An outcome is chosen in this order: the payer's decision at the hosted -page, then the payer rule, then the biller's scenario. A matching payer rule also -stops a request with a return URL from waiting, so that person's request settles -without a visit to the page. The decision still wins if the payer reaches the -page before the request is final, which is easiest to see with `serve --manual`. +requests. A matching request is settled to its terminal state when it is +created, so the first `GET /transferRequests/{id}` is already final, with a +payment reference for `paid`. Nothing can decide it first: the hosted page then +shows the result (and the return link), and a `POST /pay/{id}` is answered with +that result page and changes nothing. An outcome is therefore chosen in this +order: the payer rule, then, for requests without one, the payer's decision at +the hosted page, then the biller's scenario. Changing or removing a rule does +not affect requests already created. The payment receipt and terminal transition commit together, with one receipt per accepted request. `inspect-collections --database ...` provides separate diff --git a/tools/payment-simulator/README.md b/tools/payment-simulator/README.md index 138e8ab2cd..32363859ef 100644 --- a/tools/payment-simulator/README.md +++ b/tools/payment-simulator/README.md @@ -144,7 +144,8 @@ uv run payment-simulator collection-scenario --database .state/payments.sqlite - Use `--outcome cancelled` for a payer who cancels: it reports `RJC/FAILED` with `failureReason: payer-cancelled`. To make one named test person always decline, map their `payerFiDetails.financialAddress` to an outcome. A payer rule beats -the biller's scenario, and `--remove` deletes it: +the biller's scenario and the hosted page: the request is final as soon as it is +created, and the page only shows the result. `--remove` deletes the rule: ```sh uv run payment-simulator payer-outcome --database .state/payments.sqlite \ @@ -182,7 +183,8 @@ The redirect is a hint. The front end must still poll reference before it acts. The page needs no bearer token: the transfer ID is a random UUIDv4 and acts as the capability, and each submission carries a form token stored with the request. A request with a return URL stays `PND/PENDING` -until the payer decides, and the decision settles it at once. Requests without +until the payer decides, and the decision settles it at once, unless a payer rule +settles it at creation. Requests without a return URL behave as before. See [the P2G profile](P2G-SPEC.md#hosted-payment-page) for precedence and refusals. diff --git a/tools/payment-simulator/src/payment_simulator/store.py b/tools/payment-simulator/src/payment_simulator/store.py index 3561e6499c..fc031d0901 100644 --- a/tools/payment-simulator/src/payment_simulator/store.py +++ b/tools/payment-simulator/src/payment_simulator/store.py @@ -486,8 +486,9 @@ def request_collection(self, scope, request, currencies): (scope.producer, scope.tenant, scope.institution, request.billID), ).fetchone(): raise ApiError(409, "collection.bill-in-use", "Bill already has a payment request") - # Precedence for requests that never reach the hosted page: payer rule, then - # the biller's scenario. A hosted decision overrides both when it is made. + # A payer rule settles the request at creation, so nothing, including a fast + # click on the hosted page, can decide it first. Without one, the biller's + # scenario applies and a hosted decision overrides it. rule = db.execute( "SELECT outcome FROM payer_outcomes WHERE producer=? AND tenant=? AND biller=? " "AND address=?", @@ -535,6 +536,10 @@ def request_collection(self, scope, request, currencies): int(bool(scope.return_url) and rule is None), ), ) + if rule is not None: + self.settle( + db, {"transfer_id": transfer_id, "reference": None}, rule["outcome"], None + ) response = { "responseCode": "00", "responseDescription": "Accepted", diff --git a/tools/payment-simulator/tests/test_p2g_hosted_page.py b/tools/payment-simulator/tests/test_p2g_hosted_page.py index 8fbf306fde..84dee9d521 100644 --- a/tools/payment-simulator/tests/test_p2g_hosted_page.py +++ b/tools/payment-simulator/tests/test_p2g_hosted_page.py @@ -357,14 +357,71 @@ def test_payer_rule_releases_a_waiting_return_url_request(service): assert "cancelled" in page(client, transfer_id).text.lower() -def test_hosted_decision_beats_the_payer_rule(service): +RULE = ("registry", "pilot", "ministry", "synthetic-citizen") + + +@pytest.mark.parametrize( + ("outcome", "request_status", "payment_status", "reason"), + [ + ("paid", "COM", "PAID", None), + ("failed", "RJC", "FAILED", "payer-rejected"), + ("cancelled", "RJC", "FAILED", "payer-cancelled"), + ("expired", "EXP", "EXPIRED", "request-expired"), + ], +) +@pytest.mark.parametrize("extra", [{}, RETURN_HEADER], ids=["no-return-url", "return-url"]) +def test_payer_rule_settles_at_creation( + service, outcome, request_status, payment_status, reason, extra +): client, _, store = service - store.payer_outcome("registry", "pilot", "ministry", "synthetic-citizen", "failed") - store.collection_scenario("registry", "pilot", "ministry", "expired") - transfer_id = accept(client) - assert decide(client, transfer_id, "pay").status_code == 200 + store.payer_outcome(*RULE, outcome) + transfer_id = accept(client, **extra) + # No advance and no page visit: the first read is already final. + result = poll(client, transfer_id) + assert (result["requestStatus"], result["paymentStatus"]) == (request_status, payment_status) + assert result.get("failureReason") == reason + assert ("PaymentReferenceID" in result) == (outcome == "paid") + assert len(store.inspect_collections()["payments"]) == (outcome == "paid") + html = page(client, transfer_id).text + assert 'name="decision"' not in html + assert ("This request is final" in html) is True + assert (RETURN in html) == bool(extra) + if extra: + link = re.search(r'href="([^"]+)"', html).group(1).replace("&", "&") + assert parse_qs(urlsplit(link).query)["status"] == [outcome] store.advance(3) - assert poll(client, transfer_id)["paymentStatus"] == "PAID" + assert poll(client, transfer_id) == result + + +def test_hosted_post_cannot_override_the_payer_rule(service): + client, _, store = service + store.payer_outcome(*RULE, "failed") + transfer_id = accept(client, **RETURN_HEADER) + before = poll(client, transfer_id) + # The page shows no form, so the token comes from storage. + with sqlite3.connect(store.path) as db: + token = db.execute( + "SELECT form_token FROM collection_hosted WHERE transfer_id=?", (transfer_id,) + ).fetchone()[0] + for decision in ("pay", "decline", "cancel"): + response = decide(client, transfer_id, decision, token=token) + # Refused: no redirect, no new decision, and the result page is shown. + assert response.status_code == 200 + assert 'name="decision"' not in response.text + assert poll(client, transfer_id) == before + assert store.inspect_collections()["payments"] == [] + + +def test_requests_without_a_rule_are_unchanged_when_another_payer_has_one(service): + client, _, store = service + store.payer_outcome(*RULE, "failed") + other_request = intent(requestId="fee-002", rtpId=1002, billID="bill-002") + other_request["payerFiDetails"] = {"payerFIBIC": "TESTBANK", "financialAddress": "someone-else"} + waiting = accept(client, other_request, **RETURN_HEADER) + assert poll(client, waiting)["paymentStatus"] == "PENDING" + assert 'name="decision"' in page(client, waiting).text + assert decide(client, waiting, "pay").status_code == 303 + assert poll(client, waiting)["paymentStatus"] == "PAID" def test_payer_rule_can_be_replaced_and_removed(service): From 20306adbfba59d13b6d40ae7d76c5d709832a678 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Thu, 19 Nov 2026 20:58:43 +0000 Subject: [PATCH 20/40] docs: move payment contracts to the docs site Main moved Adapter and Coordinator product prose out of products/ and into the docs site. Carry the payment contracts this branch had written into the removed CONCEPT, DEPLOYMENT, PRODUCT-CONTRACT and SECURITY-MODEL files to their site pages: typed payment hosting on the Adapter configure page, the payments connection on the Coordinator configuration reference, the six payment operations and their completions on the Coordinator configure page, payment recovery on the operate page, and the payment invariant (now COORDINATOR-INV-16, since main assigned INV-15) with its operator obligation on the security page. Signed-off-by: Jeremi Joslin --- .../src/content/docs/configure/adapter.mdx | 74 +++++++++++++++++- .../content/docs/configure/coordinator.mdx | 46 ++++++++++- .../src/content/docs/operate/coordinator.mdx | 14 ++++ .../reference/coordinator-configuration.mdx | 52 ++++++++++--- .../src/content/docs/security/coordinator.mdx | 77 ++++++++++++++++++- .../examples/payment-collections/README.md | 2 +- 6 files changed, 250 insertions(+), 15 deletions(-) diff --git a/docs/site/src/content/docs/configure/adapter.mdx b/docs/site/src/content/docs/configure/adapter.mdx index 1684207064..3c06b111c2 100644 --- a/docs/site/src/content/docs/configure/adapter.mdx +++ b/docs/site/src/content/docs/configure/adapter.mdx @@ -47,7 +47,7 @@ The generated outputs are build artifacts. {/* Evidence: crates/registry-adapter-core/src/runtime.rs AdapterRuntimeConfig */} {/* Evidence: crates/registry-adapter-core/src/fixture.rs AdapterFixture */} {/* Evidence: crates/registry-adapter-core/src/mapping.rs AdapterMapping */} -{/* Evidence: crates/registry-adapterctl/tests/check.rs schemas_writes_ten_files_into_the_given_directory */} +{/* Evidence: crates/registry-adapterctl/tests/check.rs schemas_writes_thirteen_files_into_the_given_directory */} Projects reference packs and profiles as plain identifiers, resolved and digest-checked by `adapterctl check`. A pack declares the engine capabilities it requires (components, languages and EIPs). @@ -1075,6 +1075,78 @@ A `no-store` response leaves the acquisition usable for live reads and unavailab That restriction survives mapping and paging. Consultation's protected response headers stay unchanged. +## Typed payment hosting + +The optional payment module in `registry-adapter` mounts dedicated collection, disbursement, observation and reporting operations on the Adapter listener, outside the generic record routes. +Registry Coordinator exposes them as native typed steps. +A workflow supplies the bill or instruction record identity and version, then uses the accepted attempt identifier for observation and reporting. +Tenant, biller, provider origins, credentials, currency policy and the restricted BReg Actions are operator-owned connection configuration, and a payment-only deployment needs no record project. + +Base Registry Engine (BReg) owns the authoritative bills and fee policy, the approved disbursement instructions, the recorded receipts and provider confirmations, and the service's paid or unused issuance guard. +The payment host owns durable attempts, the original provider and registry binding snapshots, the exact prepared commands, correlation and verified observations. +Coordinator owns workflow progress and waits, and the provider owns the financial transaction. + +The payment host is a scoped exception to two facade rules. +It retains exact bill snapshots, original connection bindings, prepared restricted BReg commands and verified provider observations for recovery, which the record facade never does, and those bounded payment facts never enter the generic route engine. +It also links the public BReg client for restricted bill-binding and receipt Actions, a payment protocol crate and its provider connectors. +The Adapter core and the shared engine keep their source-neutral dependency boundary, and the dependency gate enforces that split. + +### Collection + +Before any provider send, PostgreSQL reserves one attempt per institution, service, bill and bill version across workflow command keys. +The host persists the exact bind Action and key, invokes that restricted Action, and verifies the frozen authoritative bill binding. +It then persists the first dispatch time before sending the original exact provider command. +An accepted response means the provider accepted the request, not merely that a local row exists, and an unknown outcome stays unresolved. +The simulator allows an exact same-command resend inside the original connection's declared replay window, and an unknown HTTP provider submission stays held after dispatch. + +Provider identifiers derive from a domain-separated digest of the full immutable bill and the provider origin, producer identity, tenant and biller, so independent Adapter databases do not allocate overlapping identities. +Disjoint digest portions fit the provider's request, request-to-pay and bill fields, and the provider must reject a reused request identifier with a different body. +Stored commands are checked against that derivation and replayed exactly. + +The original-command receipt lookup is a database read. +Collection reads may observe the provider but never bind, dispatch or record a receipt. +A confirmed provider observation must match the complete saved request, transfer, bill, amount and currency tuple, and a pending state, including a provider `COM/PENDING`, never authorises a receipt. + +The receipt step accepts only a collection identifier. +The host derives the receipt from its confirmed observation and frozen bill, persists the exact restricted BReg report Action and key, and verifies the authoritative readback. +A lost bind or report acknowledgement recovers from the saved command or exact readback. +The numeric-loopback simulator preserves exact decimal JSON and requires synthetic response provenance before it authorises a synthetic fee receipt. +Generic provider-pack observations are available as correlated status. + +### Disbursement + +The Adapter reads the approved instruction from BReg, including the exact money, the recipient destination and the funding account. +It prepares the exact provider command under the pinned binding and reserves one attempt for the authoritative source, instruction identity and version. +It commits the restricted BReg binding Action and records the first dispatch before sending. +An uncertain submission stays held, and Coordinator can reconcile the original acceptance only through a read-only lookup for the saved key and instruction. + +The `mifos-legacy-signature` host profile signs the exact Bulk request and verifies the raw acknowledgement and the expected tenant before interpreting it. +Request signing and response verification use separate pinned Transit keys, and Operations status reads use a separate bearer credential. + +The separate confirmation operation accepts only a disbursement identifier. +The Adapter reports verified provider completion through its restricted BReg Action, using the original instruction facts and a separately keyed exact command. +The resulting confirmation records what the provider reported; credit to the recipient and settlement require separate authoritative evidence. + +### Authorisation and retained attempts + +Every lookup rechecks the current caller, connection and service scope. +The Adapter identity holds the restricted BReg grants that bind and report attempts. +A connection configuration change affects new attempts only. +A retained attempt uses its original provider origins, tenant and party bindings, credential identities, exact pack pin and registry binding. +Load the original provider pack alongside the active pack to resume retained work; a missing pack holds the attempt before provider I/O. +Bearer credentials can rotate at the same configured reference. + +Payment attempts and command receipts stay durable without automatic expiry. +They include the restricted bill and instruction facts needed for recovery, so protect their PostgreSQL storage and backups. +Generic facade response-retention sweeps do not delete payment attempts. +Payment audit events carry no values and commit before an effect or a response is released. + +{/* Evidence: crates/registry-adapter/src/payments/service.rs; + crates/registry-adapter/src/payments/g2p_model.rs mifos-legacy-signature; + crates/registry-adapter/tests/payment_service.rs; + crates/registry-adapter/tests/payment_store.rs; + products/adapter/scripts/check_dependency_direction.py. */} + ## Next - [adapter route language](../adapter-routes/) diff --git a/docs/site/src/content/docs/configure/coordinator.mdx b/docs/site/src/content/docs/configure/coordinator.mdx index 147e0de7b3..f7778eeaff 100644 --- a/docs/site/src/content/docs/configure/coordinator.mdx +++ b/docs/site/src/content/docs/configure/coordinator.mdx @@ -513,6 +513,7 @@ await-review: `timeoutSeconds` is required and shorter than the run deadline. Casework submission exposes `result`, and the BReg Proposal operations expose `proposal`. +The payment collection operations expose `collection` and the disbursement operations expose `disbursement`, as [Collect and disburse payments](#collect-and-disburse-payments) describes. An external GET operation can declare a named `bounded-poll` completion with a typed pure `interpret` Function and `intervalSeconds`. The Function receives the saved command and the latest validated response and returns `pending`, `complete` with a typed result, or a declared `refused` code. The host owns transport, credentials, permitted destinations, scheduling, correlation, and the durable read budget, and the workflow graph stays acyclic. @@ -804,6 +805,49 @@ When a BReg Action uses a strict Casework policy pin, adding or changing stage c crates/registry-coordinator/tests/casework_adapter.rs; crates/registry-coordinator/src/definition.rs definition.review-request-not-run-owned. */} +## Collect and disburse payments + +Six native operations use the typed payment capability of the Registry Adapter through one operator-selected [`payments` connection](../../reference/coordinator-configuration/#payment-connections). +The workflow never supplies an amount, provider reference, provider destination, recipient destination, funding account, HTTP header, receipt value, or registry destination. +The connection fixes the Adapter origin, the Adapter payment connection, the credential, resource, and scopes. +The Adapter resolves the authoritative bill or instruction, the provider binding, and the reporting authority. +Its reporter identity, not Coordinator, holds any BReg grant to bind a bill, record a receipt, read an instruction, or report a provider confirmation. + +| Operation | Effect | Input | +|---|---|---| +| `payments.request-collection/v1` | Mutation, recovered by the same command and a receipt | `billId` and positive `billVersion` | +| `payments.read-collection/v1` | Read | `collectionId` | +| `payments.record-receipt/v1` | Mutation, recovered by the same command | `collectionId` of a confirmed collection | +| `payments.request-disbursement/v1` | Mutation, held after dispatch and reconciled by receipt | `instructionRecordId` and positive `instructionVersion` | +| `payments.read-disbursement/v1` | Read | `disbursementId` | +| `payments.record-provider-confirmation/v1` | Mutation, recovered by the same command | `disbursementId` of a provider-confirmed disbursement | + +A collection request is sent under the durable step key. +Its accepted output fixes `collectionId`, the exact bill identity, `bindingRevision`, and `simulation`. +Recovery calls the Adapter's read-only original-request lookup with the saved request and key under the current connection authorisation, and settles only when the retained acceptance matches the saved bill identity and version. +`receipt-unresolved`, `receipt-expired`, `recovery-held`, `outcome-unknown`, an invalid response, or a correlation mismatch never proves absence and never authorises a new effect. +A malformed success, a provider-protocol failure, a lost exchange, or another ambiguous answer after dispatch stays uncertain. + +The request and read operations expose the host-owned completion `collection`. +It retains the accepted collection, bill identity, binding revision, and simulation marker, then reads the collection through the current payment connection. +`accepted`, `pending`, and `unknown` keep the wait pending, and `confirmed` and `failed` settle the collection attempt. +Only a verified `confirmed` collection lets `payments.record-receipt/v1` succeed, and receipt recording stays a separate idempotent call so recovery cannot turn an observation into a registry change. +A wait timeout does not change provider state, establish failure, or release a service that requires confirmed payment. + +A disbursement request sends only the approved instruction's identity and version. +Its accepted output fixes the disbursement, instruction, binding revision, and simulation marker. +Because the provider profile does not establish safe replay of a submission, `retry-same` is refused after an uncertain request: only the read-only original-request lookup with the exact saved instruction and key can settle it. +The request and read operations expose the completion `disbursement`, which keeps `accepted`, `pending`, and `unknown` pending and settles on `provider-confirmed` or `failed`. +Only a verified `provider-confirmed` disbursement lets `payments.record-provider-confirmation/v1` succeed. +Provider confirmation records what the provider reported; it does not claim credit to the recipient or final settlement, and a timeout establishes none of those facts. + +The [payment collection](https://github.com/registrystack/registry-stack/tree/main/products/coordinator/examples/payment-collections) and [disbursement](https://github.com/registrystack/registry-stack/tree/main/products/coordinator/examples/g2p-disbursements) examples show both workflows against the synthetic payment simulator. + +{/* Evidence: crates/registry-coordinator/src/operations.rs payments.request-collection/v1, + payments.request-disbursement/v1; + crates/registry-coordinator/tests/payment_adapter.rs; + crates/registry-payment-client/tests/http_boundary.rs. */} + ## Call an external provider An `external.get/v1` alias can specialise its validated response and declare a bounded-poll completion, as [Wait for a result](#wait-for-a-result) describes. @@ -847,7 +891,7 @@ functions: operations: create-bill: uses: external.command/v1 - connection: payments + connection: external-billing responseSchema: {typeRef: bill-response} interpret: bill-outcome ``` diff --git a/docs/site/src/content/docs/operate/coordinator.mdx b/docs/site/src/content/docs/operate/coordinator.mdx index b2442758ec..22bff1d8e6 100644 --- a/docs/site/src/content/docs/operate/coordinator.mdx +++ b/docs/site/src/content/docs/operate/coordinator.mdx @@ -1026,6 +1026,20 @@ Ordinary cancellation leaves downstream work for explicit owner-authorized withd crates/registry-coordinator/tests/casework_adapter.rs reconciliation-unavailable; crates/registry-coordinator/src/store/recovery.rs reconciliation-unavailable. */} +### Payment recovery + +An uncertain `payments.request-collection/v1` recovers through the Adapter's read-only original-request lookup, with the saved bill identity, version, and key under the current connection authorisation. +An unresolved, expired, held, or unknown receipt never proves that a new collection may be requested. + +An uncertain `payments.request-disbursement/v1` stays held. +`reconcile` may use the Adapter's read-only lookup for the exact original instruction and key, but `retry-same` is refused, and an unresolved lookup never proves absence or licenses a fresh submission. +The separate `payments.record-receipt/v1` and `payments.record-provider-confirmation/v1` reporting commands may use `retry-same` with their frozen body and key. +Investigate an unresolved original-request receipt with the Adapter operator before any same-command recovery or cancellation decision. + +{/* Evidence: crates/registry-coordinator/tests/payment_adapter.rs + collection_request_and_recovery_use_the_exact_original_command, + uncertain_disbursement_submission_never_becomes_a_fresh_send. */} + ### Waits A `wait-for` observes a named completion, correlated to an earlier accepted call. diff --git a/docs/site/src/content/docs/reference/coordinator-configuration.mdx b/docs/site/src/content/docs/reference/coordinator-configuration.mdx index 05b8cbeb54..a84ed83ca6 100644 --- a/docs/site/src/content/docs/reference/coordinator-configuration.mdx +++ b/docs/site/src/content/docs/reference/coordinator-configuration.mdx @@ -83,7 +83,7 @@ at most {reference.operations[0].maximum_call_attempts} attempts of ## Connections `runtime.yaml` declares every logical connection in one `connections` map, at most sixteen names. -Each entry selects its complete contract with `type`: `breg`, `casework-review-producer`, `messaging`, `scheduling`, `external-http`, or `evaluation`. +Each entry selects its complete contract with `type`: `breg`, `casework-review-producer`, `messaging`, `payments`, `scheduling`, `external-http`, or `evaluation`. The [deployment runbook](../../operate/coordinator/) covers the rest of the `deployment` block. {/* Evidence: crates/registry-coordinator/src/runtime.rs ConnectionConfig. */} @@ -146,20 +146,20 @@ Use a separate connection when commands need a different credential or scope tha ```yaml connections: - payments: + legacy-provider: type: external-http - baseUrl: https://payments.example.org/v1/ + baseUrl: https://legacy.example.org/api/ paths: - - bills/status - commandPath: bills + - requests/status + commandPath: requests authorization: tokenEndpoint: https://issuer.example.org/oauth/token clientAssertionAudience: https://issuer.example.org - clientId: coordinator-payments - signingKeyRef: secret:file/payments-jwk - resource: https://payments.example.org + clientId: coordinator-legacy-provider + signingKeyRef: secret:file/legacy-provider-jwk + resource: https://legacy.example.org scopes: - - bills:create + - requests:create responseSchema: type: object required: @@ -180,6 +180,40 @@ Coordinator trusts a 429 to mean the provider did not process the command, so th crates/registry-coordinator/src/runtime.rs command_path; crates/registry-coordinator/tests/external_command.rs. */} +### Payment connections + +A `payments` connection serves the native payment operations over the Registry Adapter payment host. +`baseUrl` names the Adapter, and `paymentConnection` selects one Adapter-owned payment connection. +That selection is part of a live run's binding identity, and the workflow cannot replace either value. +Use an ordinary service `authorization` without `taskAuthority`; the Adapter authorises the current credential on each call. +`resultCheckSeconds`, from 60 to 86,400 and 900 by default, spaces the authoritative collection or disbursement reads of a waiting run and is not part of the binding identity. + +```yaml +connections: + licence-fees: + type: payments + baseUrl: https://adapter.example.org + paymentConnection: licence-fees + authorization: + tokenEndpoint: https://issuer.example.org/oauth/token + clientAssertionAudience: https://issuer.example.org + clientId: coordinator-payments + signingKeyRef: secret:file/payments-jwk + resource: https://adapter.example.org + scopes: + - payments:collect + resultCheckSeconds: 900 +``` + +Grant Coordinator only the Adapter payment capability. +Any BReg grant that binds a bill or records a receipt, and any instruction-registry grant that reads an instruction or reports provider confirmation, belongs to the Adapter's configured reporter identity. +An unresolved original-request lookup requires inspection; it never licenses a fresh collection or disbursement attempt. +`payments.request-disbursement/v1` cannot use `retry-same` after uncertainty, and reconciles only through its read-only original-command lookup. +The separate `payments.record-provider-confirmation/v1` report may use `retry-same`, because the Adapter owns that idempotently keyed reporting command. + +{/* Evidence: crates/registry-coordinator/src/runtime.rs PaymentConnectionConfig; + crates/registry-coordinator/tests/payment_adapter.rs. */} + ### Evaluation connections An `evaluation` connection serves `evaluation.evaluate/v1`. diff --git a/docs/site/src/content/docs/security/coordinator.mdx b/docs/site/src/content/docs/security/coordinator.mdx index b9149abbd4..9f5abea8e0 100644 --- a/docs/site/src/content/docs/security/coordinator.mdx +++ b/docs/site/src/content/docs/security/coordinator.mdx @@ -21,14 +21,15 @@ Deployment steps are in [Deploy Registry Coordinator](../../operate/coordinator/ ## Scope and trust boundaries - The operator owns the runtime configuration: connection base URLs, the external command path, - credentials, issuer settings and the Base Registry Engine (BReg) connection profile. + credentials, issuer settings, the Base Registry Engine (BReg) connection profile and the Registry + Adapter payment connection. Operator configuration is trusted; workflow data is not. - A workflow author writes a project that Coordinator freezes into a definition. The author supplies bodies, mappings and pure Functions. The author does not choose destinations, headers, credentials or recovery behaviour; the closed operation catalogue does. -- Providers decide every effect a run requests: Registry Casework, Registry Scheduling, BReg and - external HTTP providers. +- Providers decide every effect a run requests: Registry Casework, Registry Scheduling, BReg, the + Registry Adapter payment host and external HTTP providers. Coordinator holds workload identity, not decision authority, and each receiving product still authorises the call. - A caller authenticates with an access token verified against the configured OIDC issuer. @@ -710,6 +711,71 @@ normal serving or apply while a live Run's retained binding differs from the con crates/registry-coordinator/tests/deployment_postgres.rs split_activation_and_real_router_enforce_owned_progress_and_operator_recovery. */} +### COORDINATOR-INV-16: payment completion requires exact authoritative evidence + +Threat: a workflow could supply an amount, provider route, header, receipt or registry destination; +reuse an acceptance for another bill, collection, instruction or disbursement; treat pending, +unknown or a timed-out wait as payment; or start a fresh provider effect after an ambiguous +response or unresolved receipt. + +Enforcement: the native payment catalogue accepts only `billId` and positive `billVersion` when +requesting a collection, and only `collectionId` when reading a collection or recording its receipt. +The disbursement catalogue accepts only `instructionRecordId` and positive `instructionVersion` +when requesting a disbursement, and only `disbursementId` when reading it or reporting provider +confirmation. +`PaymentConnectionConfig` fixes the Adapter origin, the Adapter payment connection and ordinary +service authorisation. +The maintained payment client validates strict typed responses against the exact bill, collection, +instruction or disbursement identity before returning them. +A request is durably keyed, and reconciliation uses only the Adapter's read-only original-request +endpoint with that saved key and body under current connection authorisation. +Provider-protocol failures, malformed or mismatched success documents, broken exchanges after +dispatch, `recovery-held` and `outcome-unknown` remain uncertain. +An unresolved or expired receipt proves no absence and grants no fresh effect. + +Disbursement request recovery is deliberately narrower than collection recovery. +The request declares `hold-after-dispatch`, so an uncertain submission cannot use `retry-same`, and +the worker, the recovery store and the offline scenario runner refuse a later command retry. +A later synthetic success is eligible only under `reconcile`, where it represents the +original-command lookup. +Only the separate provider-confirmation report is recovered by the same command, under its own +durable key. + +The host-owned `collection` completion retains the accepted collection, bill, binding revision and +simulation marker, and each observation performs a fresh authorised read through the same logical +payment connection. +`accepted`, `pending` and `unknown` keep the wait pending; `confirmed` and `failed` settle only the +collection attempt, and only Adapter-verified `confirmed` state can satisfy the separate, keyed +`payments.record-receipt/v1` call. +The `disbursement` completion likewise settles only on `provider-confirmed` or `failed`, and only +verified `provider-confirmed` state can satisfy `payments.record-provider-confirmation/v1`. +That confirmation does not claim credit to the recipient or final settlement. +Coordinator carries no BReg bill-binding, receipt, instruction read or reporting grant, and a +timeout changes none of these facts. + +Refused: a workflow-selected amount, paid state, provider destination, header, receipt or registry +destination; another command's acceptance; another collection or disbursement observation; receipt +or provider-confirmation recording for anything the Adapter has not verified in the required +terminal state; replay of an uncertain disbursement submission; any inference that pending, +unknown, a timeout or a missing receipt authorises release or replacement. + +{/* Evidence: crates/registry-payment-client/tests/http_boundary.rs + collection_request_sends_only_authoritative_bill_identity, + original_request_receipt_is_a_read_with_the_exact_key_and_body, + a_response_for_another_command_or_collection_is_a_protocol_failure, + malformed_or_duplicate_payment_evidence_fails_visibly, + typed_problem_codes_preserve_authentication_and_uncertainty_semantics, + record_receipt_requires_confirmed_exactly_correlated_evidence; + crates/registry-coordinator/tests/payment_adapter.rs + collection_request_and_recovery_use_the_exact_original_command, + ambiguous_mutation_response_holds_until_read_only_recovery_resolves, + payment_authentication_failure_is_a_value_free_refusal, + payment_completion_settles_only_terminal_exactly_bound_state, + disbursement_request_and_recovery_use_the_exact_original_command, + uncertain_disbursement_submission_never_becomes_a_fresh_send, + provider_confirmation_report_is_one_exact_keyed_command, + disbursement_completion_settles_only_terminal_exactly_bound_state. */} + ## Operator obligations The guarantees hold only when you meet these obligations. @@ -759,6 +825,11 @@ The residuals refer to them by number. Run admitted without it no longer matches its binding, so `deployment-status` reports `live-binding-conflict` and normal serving refuses while it remains. `coordinator --recovery-only` inspects it (COORDINATOR-INV-15). +14. Give Coordinator only the Adapter payment capability. + Keep the BReg bill and instruction binding and reporting grants with the authorised Adapter + identities. + Investigate an unresolved original-request receipt before any same-command recovery or + cancellation decision (COORDINATOR-INV-16). {/* Evidence: crates/registry-coordinator/tests/external_command_postgres.rs a_lost_acknowledgement_holds_and_retry_same_sends_the_same_command; diff --git a/products/adapter/examples/payment-collections/README.md b/products/adapter/examples/payment-collections/README.md index f53e4aa773..3ff43abad5 100644 --- a/products/adapter/examples/payment-collections/README.md +++ b/products/adapter/examples/payment-collections/README.md @@ -25,7 +25,7 @@ native payment operations: The request's named completion polls the provider through the Adapter, so an ordinary workflow does not need to author its own polling loop. See the [Coordinator operation catalog](../../../coordinator/generated/operations/README.md) -and [connection setup](../../../coordinator/DEPLOYMENT.md). +and [connection setup](https://docs.registrystack.org/reference/coordinator-configuration/#payment-connections). ## Bind the connection From 2f7219a7beaddfa5c4fa143caefe8765f5eeac4a Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Thu, 19 Nov 2026 20:58:43 +0000 Subject: [PATCH 21/40] chore: regenerate payment schemas and identifier catalogue The payment provider pack schema still carried references to the removed Adapter concept document; regenerate it and the identifier catalogue digests from their sources. Signed-off-by: Jeremi Joslin --- .../schemas/payment-provider-pack.v1alpha1.schema.json | 4 ++-- products/identifiers/generated/catalog.v1.json | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/products/adapter/schemas/payment-provider-pack.v1alpha1.schema.json b/products/adapter/schemas/payment-provider-pack.v1alpha1.schema.json index 71251de9a6..d00568f212 100644 --- a/products/adapter/schemas/payment-provider-pack.v1alpha1.schema.json +++ b/products/adapter/schemas/payment-provider-pack.v1alpha1.schema.json @@ -108,7 +108,7 @@ }, "RhaiExpression": { "additionalProperties": false, - "description": "A Rhai expression reference: the digest-pinned file from the pack's\nscript inventory and the precompiled entrypoint to call\n(`products/adapter/CONCEPT.md` sections 5.6 and 8.5). Inline code is\nrefused (CFG-EMBED-1).", + "description": "A Rhai expression reference: the digest-pinned file from the pack's\nscript inventory and the precompiled entrypoint to call. Inline code is\nrefused (CFG-EMBED-1).", "properties": { "entrypoint": { "description": "The precompiled entrypoint the engine calls.", @@ -127,7 +127,7 @@ }, "ScriptReference": { "additionalProperties": false, - "description": "A script seam: code in its own file beside the pack, referenced by a\nrelative path and pinned by digest (CFG-EMBED-1). Scripts never carry\ncredentials and never construct URLs; the `http` component builds every\nrequest from its declared template\n(`products/adapter/CONCEPT.md` section 5.6).", + "description": "A script seam: code in its own file beside the pack, referenced by a\nrelative path and pinned by digest (CFG-EMBED-1). Scripts never carry\ncredentials and never construct URLs; the `http` component builds every\nrequest from its declared template.", "properties": { "digest": { "$ref": "#/$defs/Digest", diff --git a/products/identifiers/generated/catalog.v1.json b/products/identifiers/generated/catalog.v1.json index b7ca668d31..b02edde10f 100644 --- a/products/identifiers/generated/catalog.v1.json +++ b/products/identifiers/generated/catalog.v1.json @@ -4711,7 +4711,7 @@ }, "artifact": { "path": "products/adapter/schemas/payment-provider-pack.v1alpha1.schema.json", - "sha256": "1a5b6c0ae4299742e40a9f5ebe03a732c2ddd25a83b314ea25dd02cb2f56250f", + "sha256": "b2da0ab508173724798f91e1aab0ffe28348f237d3965595e039cae061e0f0b0", "mediaType": "application/schema+json" } }, From 498e820314be616e858e730cb984db6f069eef0a Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Thu, 19 Nov 2026 22:42:14 +0000 Subject: [PATCH 22/40] fix(adapter): refuse live collection providers Collections are simulation-only, as the payment-collections contract states. A collection binding is accepted only with the simulator provider and simulation: true; a Mifos or mapped HTTP collection, or a simulator binding with simulation: false, is refused with adapter.payment.collection-simulation-only by both adapter serve and adapterctl payments check. The generated payments schema fixes simulation to true. The Mifos and HTTP collection branches in the router and request path stay for a follow-up; no new connection can reach them. Service and authoring tests that ran live collections now assert the refusal, and the provider-pack pin tests use pinned simulator collections. Signed-off-by: Jeremi Joslin --- .../registry-adapter/src/payments/config.rs | 95 +-- .../src/payments/g2p_config.rs | 4 +- crates/registry-adapter/src/payments/http.rs | 9 +- .../registry-adapter/tests/payment_config.rs | 85 +-- .../registry-adapter/tests/payment_service.rs | 708 +----------------- crates/registry-adapterctl/src/payments.rs | 16 +- crates/registry-adapterctl/tests/payments.rs | 134 ++-- .../src/content/docs/configure/adapter.mdx | 12 +- .../schemas/payments.v1alpha1.schema.json | 2 + 9 files changed, 182 insertions(+), 883 deletions(-) diff --git a/crates/registry-adapter/src/payments/config.rs b/crates/registry-adapter/src/payments/config.rs index 458358aad1..288469d42f 100644 --- a/crates/registry-adapter/src/payments/config.rs +++ b/crates/registry-adapter/src/payments/config.rs @@ -68,6 +68,8 @@ pub struct PaymentBinding { /// original binding unchanged across an upgrade. #[serde(default, skip_serializing_if = "Option::is_none")] pub provider_pack: Option, + /// Collections are simulation-only; a live collection provider is refused. + #[cfg_attr(feature = "schema", schemars(extend("const" = true)))] pub simulation: bool, #[cfg_attr(feature = "schema", schemars(pattern("^[A-Z]{3}$")))] pub currency: String, @@ -222,9 +224,20 @@ pub struct RegistryBinding { pub credential_identity: String, } -#[derive(Clone, Copy, Debug, thiserror::Error)] -#[error("adapter.payment.configuration")] -pub struct ConfigError; +#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)] +#[error("{0}")] +pub struct ConfigError(&'static str); + +impl ConfigError { + pub const INVALID: Self = Self("adapter.payment.configuration"); + /// Collections run only against the synthetic simulator until a live + /// collection provider is verified end to end. + pub const COLLECTION_SIMULATION_ONLY: Self = Self("adapter.payment.collection-simulation-only"); + + pub const fn code(self) -> &'static str { + self.0 + } +} fn unique_clients<'de, D: serde::Deserializer<'de>>( deserializer: D, @@ -249,7 +262,7 @@ impl PaymentsConfig { || self.connections.len() > 64 || self.disbursements.len() > 64 { - return Err(ConfigError); + return Err(ConfigError::INVALID); } let mut ids = BTreeSet::new(); for connection in &self.connections { @@ -268,13 +281,13 @@ impl PaymentsConfig { != connection.allowed_clients.len() || !text(&connection.required_scope, 128) { - return Err(ConfigError); + return Err(ConfigError::INVALID); } connection.binding.validate()?; } for connection in &self.disbursements { if !ids.insert(&connection.id) { - return Err(ConfigError); + return Err(ConfigError::INVALID); } connection.validate()?; } @@ -287,39 +300,19 @@ impl PaymentBinding { if !text(&self.provider_credential_identity, 128) || !(1..=86_400).contains(&self.replay_window_seconds) { - return Err(ConfigError); + return Err(ConfigError::INVALID); } + // Collections are simulation-only: the Mifos and mapped HTTP arms + // remain parseable for retained attempts but cannot back a new + // connection until a live collection provider is verified. match &self.provider { CollectionProvider::Simulator { connection } if self.simulation => { - connection.validate().map_err(|_| ConfigError)?; - } - CollectionProvider::Mifos { - connection, - payer, - transaction_type, - } if !self.simulation => { - validate_mifos(connection, payer, transaction_type)?; - } - CollectionProvider::Http { - submit_base_url, - status_base_url, - settings, - } if !self.simulation && self.provider_pack.is_some() => { - for origin in [submit_base_url, status_base_url] { - registry_platform_yaml::Url::new(origin.clone()).map_err(|_| ConfigError)?; - ServiceBaseUrl::new(url::Url::parse(origin).map_err(|_| ConfigError)?) - .map_err(|_| ConfigError)?; - } - if !settings.is_object() - || serde_json::to_vec(settings).map_err(|_| ConfigError)?.len() > 16_384 - { - return Err(ConfigError); - } + connection.validate().map_err(|_| ConfigError::INVALID)?; } CollectionProvider::Simulator { .. } | CollectionProvider::Mifos { .. } | CollectionProvider::Http { .. } => { - return Err(ConfigError); + return Err(ConfigError::COLLECTION_SIMULATION_ONLY); } } if self.provider_pack.as_ref().is_some_and(|pin| { @@ -329,7 +322,7 @@ impl PaymentBinding { || !pin.digest.starts_with("sha256:") || !pin.digest[7..].bytes().all(|byte| byte.is_ascii_hexdigit()) }) { - return Err(ConfigError); + return Err(ConfigError::INVALID); } Money { value: "1".into(), @@ -337,11 +330,12 @@ impl PaymentBinding { scale: self.currency_scale, } .minor_units() - .map_err(|_| ConfigError)?; + .map_err(|_| ConfigError::INVALID)?; let registry = &self.registry; - registry_platform_yaml::Url::new(registry.base_url.clone()).map_err(|_| ConfigError)?; - ServiceBaseUrl::new(url::Url::parse(®istry.base_url).map_err(|_| ConfigError)?) - .map_err(|_| ConfigError)?; + registry_platform_yaml::Url::new(registry.base_url.clone()) + .map_err(|_| ConfigError::INVALID)?; + ServiceBaseUrl::new(url::Url::parse(®istry.base_url).map_err(|_| ConfigError::INVALID)?) + .map_err(|_| ConfigError::INVALID)?; if !text(®istry.read_profile, 128) || !text(®istry.bind_profile, 128) || !text(®istry.receipt_profile, 128) @@ -352,7 +346,7 @@ impl PaymentBinding { || !local_id(®istry.receipt_action) || registry.bind_action == registry.receipt_action { - return Err(ConfigError); + return Err(ConfigError::INVALID); } Ok(()) } @@ -369,8 +363,8 @@ impl PaymentBinding { "connector": connector, "billContract": BILL_CONTRACT, "binding": self, }); - let canonical = - registry_platform_canonical_json::canonicalize_json(&value).map_err(|_| ConfigError)?; + let canonical = registry_platform_canonical_json::canonicalize_json(&value) + .map_err(|_| ConfigError::INVALID)?; Ok(registry_platform_config::sha256_uri(&canonical)) } @@ -401,30 +395,9 @@ impl PaymentBinding { } } -fn validate_mifos( - connection: &MifosConnection, - payer: &MifosPayerMapping, - transaction_type: &MifosTransactionType, -) -> Result<(), ConfigError> { - connection.validate().map_err(|_| ConfigError)?; - if !header_text(&payer.financial_address_key, 32) - || !header_text(&payer.payer_id_key, 32) - || !header_text(&transaction_type.scenario, 32) - || !header_text(&transaction_type.sub_scenario, 32) - || !header_text(&transaction_type.initiator, 32) - || !header_text(&transaction_type.initiator_type, 32) - { - return Err(ConfigError); - } - Ok(()) -} - pub(crate) fn text(value: &str, max: usize) -> bool { !value.is_empty() && value.len() <= max && value.bytes().all(|b| (0x21..=0x7e).contains(&b)) } -fn header_text(value: &str, max: usize) -> bool { - !value.is_empty() && value.len() <= max && value.bytes().all(|byte| byte.is_ascii_graphic()) -} fn local_id(value: &str) -> bool { text(value, 128) && value diff --git a/crates/registry-adapter/src/payments/g2p_config.rs b/crates/registry-adapter/src/payments/g2p_config.rs index a026cc1eea..d22722074f 100644 --- a/crates/registry-adapter/src/payments/g2p_config.rs +++ b/crates/registry-adapter/src/payments/g2p_config.rs @@ -30,8 +30,8 @@ impl G2pConnection { != self.allowed_clients.len() || !super::config::text(&self.required_scope, 128) { - return Err(ConfigError); + return Err(ConfigError::INVALID); } - self.binding.validate().map_err(|_| ConfigError) + self.binding.validate().map_err(|_| ConfigError::INVALID) } } diff --git a/crates/registry-adapter/src/payments/http.rs b/crates/registry-adapter/src/payments/http.rs index f5fbc32d15..b30cce646d 100644 --- a/crates/registry-adapter/src/payments/http.rs +++ b/crates/registry-adapter/src/payments/http.rs @@ -113,9 +113,12 @@ pub fn load_config(path: &Path) -> Result { .load::(&absolute) .map_err(|_| refused("payment configuration was refused"))? .config; - config - .validate() - .map_err(|_| refused("payment connections were refused"))?; + config.validate().map_err(|error| { + ServeError::Configuration(format!( + "{}: payment connections were refused", + error.code() + )) + })?; Ok(config) } diff --git a/crates/registry-adapter/tests/payment_config.rs b/crates/registry-adapter/tests/payment_config.rs index c1585c3d16..fc400f4b59 100644 --- a/crates/registry-adapter/tests/payment_config.rs +++ b/crates/registry-adapter/tests/payment_config.rs @@ -1,7 +1,14 @@ // SPDX-License-Identifier: Apache-2.0 -use registry_adapter::payments::config::PaymentsConfig; +use registry_adapter::payments::config::{ConfigError, PaymentsConfig}; use serde_json::{json, Value}; +fn refusal(value: Value) -> ConfigError { + serde_json::from_value::(value) + .unwrap() + .validate() + .unwrap_err() +} + fn config() -> Value { json!({ "connections": [{ "id":"fees", "institutionId":"ministry", "serviceId":"permit", "allowedClients":["payment-coordinator"], "requiredScope":"payments:collections", @@ -60,36 +67,17 @@ fn http_config() -> Value { } #[test] -fn mapped_http_provider_requires_a_pin_and_bounded_separate_origins() { - let valid: PaymentsConfig = serde_json::from_value(http_config()).unwrap(); - assert!(valid.validate().is_ok()); - let mut missing_pin = http_config(); - missing_pin["connections"][0]["binding"] - .as_object_mut() - .unwrap() - .remove("providerPack"); - assert!(serde_json::from_value::(missing_pin) - .unwrap() - .validate() - .is_err()); - for pointer in [ - "/connections/0/binding/provider/submitBaseUrl", - "/connections/0/binding/provider/statusBaseUrl", - ] { - let mut invalid = http_config(); - *invalid.pointer_mut(pointer).unwrap() = json!("http://example.test/path"); - assert!(serde_json::from_value::(invalid) - .unwrap() - .validate() - .is_err()); - } - let mut oversized = http_config(); - oversized["connections"][0]["binding"]["provider"]["settings"]["tenant"] = - json!("x".repeat(20_000)); - assert!(serde_json::from_value::(oversized) - .unwrap() - .validate() - .is_err()); +fn mapped_http_collection_providers_are_refused_as_simulation_only() { + assert_eq!( + refusal(http_config()).code(), + "adapter.payment.collection-simulation-only" + ); + let mut simulated = http_config(); + simulated["connections"][0]["binding"]["simulation"] = json!(true); + assert_eq!( + refusal(simulated).code(), + "adapter.payment.collection-simulation-only" + ); } #[test] fn connections_are_explicit_scoped_and_synthetic() { @@ -105,29 +93,28 @@ fn connections_are_explicit_scoped_and_synthetic() { } let mut live = config(); live["connections"][0]["binding"]["simulation"] = json!(false); - assert!(serde_json::from_value::(live) - .unwrap() - .validate() - .is_err()); + assert_eq!( + refusal(live).code(), + "adapter.payment.collection-simulation-only" + ); let mut unusable = config(); unusable["connections"][0]["id"] = json!("MixedCase"); - assert!(serde_json::from_value::(unusable) - .unwrap() - .validate() - .is_err()); + assert_eq!(refusal(unusable).code(), "adapter.payment.configuration"); } #[test] -fn only_mifos_can_back_a_non_simulation_collection() { - let live: PaymentsConfig = serde_json::from_value(mifos_config()).unwrap(); - assert!(live.validate().is_ok()); +fn live_mifos_collections_are_refused_as_simulation_only() { + assert_eq!( + refusal(mifos_config()).code(), + "adapter.payment.collection-simulation-only" + ); let mut simulated_mifos = mifos_config(); simulated_mifos["connections"][0]["binding"]["simulation"] = json!(true); - assert!(serde_json::from_value::(simulated_mifos) - .unwrap() - .validate() - .is_err()); + assert_eq!( + refusal(simulated_mifos).code(), + "adapter.payment.collection-simulation-only" + ); let mut unknown = mifos_config(); unknown["connections"][0]["binding"]["provider"]["connection"]["extra"] = json!(true); @@ -481,15 +468,15 @@ fn persisted_command_cannot_be_borrowed_by_another_bill_or_provider_namespace() #[cfg(feature = "schema")] #[test] -fn authored_connections_allow_the_strict_mifos_shape_and_require_scope() { +fn authored_connections_are_simulation_only_and_require_scope() { let schema = serde_json::to_value(schemars::schema_for!(PaymentsConfig)).unwrap(); let compiled = jsonschema::JSONSchema::options() .with_draft(jsonschema::Draft::Draft202012) .compile(&schema) .unwrap(); assert!(compiled.is_valid(&config())); - assert!(compiled.is_valid(&mifos_config())); - assert!(compiled.is_valid(&http_config())); + assert!(!compiled.is_valid(&mifos_config())); + assert!(!compiled.is_valid(&http_config())); let mut value = config(); value["connections"][0] .as_object_mut() diff --git a/crates/registry-adapter/tests/payment_service.rs b/crates/registry-adapter/tests/payment_service.rs index f03f2e6b68..cee15b648c 100644 --- a/crates/registry-adapter/tests/payment_service.rs +++ b/crates/registry-adapter/tests/payment_service.rs @@ -5,11 +5,10 @@ use async_trait::async_trait; use registry_adapter::{ payments::{ config::{PaymentBinding, PaymentsConfig}, - model::{digest, BillSnapshot, CollectionProviderCommand, PreparedRegistryAction}, - pack::PaymentProviderPack, - provider_mapping::{PaymentMappingProgram, PaymentMappingRegistry, ProviderAcceptance}, + model::{BillSnapshot, CollectionProviderCommand, PreparedRegistryAction}, + provider_mapping::ProviderAcceptance, registry::{BillState, BillView, RegistryPort}, - service::{PaymentService, ProviderPort, ProviderSubmission, SyntheticProvider}, + service::{PaymentService, ProviderPort, ProviderSubmission}, store::{migrate, PaymentStore}, }, serve::Caller, @@ -18,15 +17,10 @@ use registry_payment_protocol::{ CollectionState, Money, PaymentProblemCode as Error, RequestCollection, }; use registry_payment_simulator_connector::{ConnectorError, Observation}; -use registry_platform_config::{SecretProvider, SecretResolver}; use serde_json::{json, Map, Value}; -use std::{ - collections::BTreeMap, - os::unix::fs::PermissionsExt, - sync::{ - atomic::{AtomicBool, AtomicUsize, Ordering}, - Arc, Mutex, - }, +use std::sync::{ + atomic::{AtomicBool, AtomicUsize, Ordering}, + Arc, Mutex, }; use uuid::Uuid; @@ -552,275 +546,19 @@ async fn uncertain_attempt_is_held_after_its_original_replay_window() { } #[tokio::test] -async fn an_unknown_mifos_submit_is_never_sent_again() { +async fn a_service_refuses_live_collection_connections() { let (store, registry, provider) = setup().await; - { - let mut bill = registry.bill.lock().unwrap(); - bill.snapshot.simulation = false; - bill.snapshot.money.currency = "KES".into(); - bill.snapshot.payer_financial_address = "254700000001".into(); - bill.snapshot.payer_id = "payer-account-1".into(); - } - provider.lose_ack.store(true, Ordering::SeqCst); - let request = RequestCollection { - bill_id: registry.bill.lock().unwrap().snapshot.bill_id, - bill_version: 1, - }; - let service = - PaymentService::new(mifos_config(), store, registry.clone(), provider.clone()).unwrap(); - assert_eq!( - service - .request("fees", &caller(), "mifos-key", &request) - .await - .unwrap_err(), - Error::OutcomeUnknown - ); - assert_eq!( - service - .request("fees", &caller(), "mifos-key", &request) - .await - .unwrap_err(), - Error::RecoveryHeld - ); - assert_eq!(provider.sends.load(Ordering::SeqCst), 1); - assert_eq!(provider.commands.lock().unwrap().len(), 1); -} - -#[tokio::test] -async fn mifos_provider_success_cannot_advance_the_registry_bill_to_paid() { - let (store, registry, provider) = setup().await; - { - let mut bill = registry.bill.lock().unwrap(); - bill.snapshot.simulation = false; - bill.snapshot.money.currency = "KES".into(); - bill.snapshot.payer_financial_address = "254700000001".into(); - bill.snapshot.payer_id = "payer-account-1".into(); - } - let request = RequestCollection { - bill_id: registry.bill.lock().unwrap().snapshot.bill_id, - bill_version: 1, - }; - let service = - PaymentService::new(mifos_config(), store, registry.clone(), provider.clone()).unwrap(); - let accepted = service - .request("fees", &caller(), "mifos-key", &request) - .await - .unwrap(); - provider.confirmed.store(true, Ordering::SeqCst); - assert_eq!( - service - .read("fees", &caller(), accepted.collection_id) - .await - .unwrap() - .state, - CollectionState::Confirmed - ); - assert_eq!( - service - .record_receipt("fees", &caller(), "mifos-receipt", accepted.collection_id,) - .await - .unwrap_err(), - Error::RecoveryHeld - ); - assert_eq!(registry.reports.load(Ordering::SeqCst), 0); - assert_eq!(registry.bill.lock().unwrap().state, BillState::AttemptBound); -} - -const SECOND_PROVIDER_SCRIPT: &str = r#" -fn submit_request(intent, settings, acceptance) { - if acceptance != () { throw "submit accepts no prior acceptance"; } - #{ - pathParameters: #{}, - query: #{mode: "direct"}, - headers: #{"x-provider-tenant": settings.tenant}, - body: #{ - command: #{id: intent.correlationId}, - debtor: #{account: intent.payerId, address: intent.payerFinancialAddress}, - total: intent.money - } + for config in [ + mifos_config(), + second_provider_config("http://127.0.0.1:9/", b"second-provider-pack"), + ] { + assert!(matches!( + PaymentService::new(config, store.clone(), registry.clone(), provider.clone()), + Err(Error::Unavailable) + )); } } -fn submit_response(intent, settings, acceptance, response) { - if settings == () || acceptance != () || response.status != 202 - || response.body.correlation != intent.correlationId { - throw "submit response mismatch"; - } - #{correlationId: intent.correlationId, references: #{payment: response.body.receipt}} -} - -fn status_request(intent, settings, acceptance) { - if intent == () || acceptance == () { throw "status needs retained context"; } - #{ - pathParameters: #{payment: acceptance.references.payment}, - query: #{view: "full"}, - headers: #{"x-provider-tenant": settings.tenant}, - body: () - } -} - -fn status_response(intent, settings, acceptance, response) { - if settings == () || acceptance == () || response.status != 200 - || response.body.correlation != intent.correlationId - || response.body.receipt != acceptance.references.payment { - throw "status response mismatch"; - } - #{ - correlationId: response.body.correlation, - providerReference: response.body.receipt, - state: if response.body.state == "complete" { "provider-confirmed" } else { "pending" }, - money: #{ - minorUnits: response.body.total.minorUnits, - currency: response.body.total.currency, - scale: intent.money.scale - }, - parties: [ - #{role: "payer", key: "account", value: response.body.debtor.account}, - #{role: "payer", key: "address", value: response.body.debtor.address} - ] - } -} -"#; - -fn generic_provider_pack(id: &str, submit_path: &str, status_path: &str) -> Vec { - format!( - r#"apiVersion: id.registrystack.org/formats/adapter/payment-provider-pack/v1alpha1 -kind: AdapterPaymentProviderPack -id: {id} -version: '1' -connector: adapter-payment-http/v1 -capabilities: [collection] -mapping: - collection: - auth: bearer - submit: - path: {submit_path} - request: {{file: scripts/provider.rhai, entrypoint: submit_request}} - response: {{file: scripts/provider.rhai, entrypoint: submit_response}} - status: - path: {status_path} - request: {{file: scripts/provider.rhai, entrypoint: status_request}} - response: {{file: scripts/provider.rhai, entrypoint: status_response}} - scripts: - - path: scripts/provider.rhai - digest: {} -"#, - registry_platform_config::sha256_uri(SECOND_PROVIDER_SCRIPT.as_bytes()) - ) - .into_bytes() -} - -fn second_provider_pack() -> Vec { - generic_provider_pack( - "second-provider", - "/v2/payments", - "/v2/payments/{{payment}}", - ) -} - -fn compile_provider(pack_bytes: &[u8]) -> PaymentMappingProgram { - let pack = PaymentProviderPack::from_yaml(pack_bytes).unwrap(); - PaymentMappingProgram::compile( - &pack, - pack_bytes, - &BTreeMap::from([( - "scripts/provider.rhai".to_owned(), - SECOND_PROVIDER_SCRIPT.as_bytes().to_vec(), - )]), - ) - .unwrap() -} - -#[derive(Clone)] -struct WireProviderState { - requests: Arc>>, - correlation: Arc>>, - mismatched_observation: Arc, - unknown_submit: Arc, -} - -struct WireRequest { - method: http::Method, - path: String, - query: Option, - authorization: Option, - tenant: Option, - content_type: Option, - body: Vec, -} - -async fn second_provider_submit( - axum::extract::State(state): axum::extract::State, - headers: http::HeaderMap, - uri: http::Uri, - body: axum::body::Bytes, -) -> impl axum::response::IntoResponse { - let decoded: Value = serde_json::from_slice(&body).unwrap(); - let correlation = decoded["command"]["id"].as_str().unwrap().to_owned(); - *state.correlation.lock().unwrap() = Some(correlation.clone()); - state.requests.lock().unwrap().push(WireRequest { - method: http::Method::POST, - path: uri.path().to_owned(), - query: uri.query().map(str::to_owned), - authorization: headers - .get(http::header::AUTHORIZATION) - .and_then(|value| value.to_str().ok()) - .map(str::to_owned), - tenant: headers - .get("x-provider-tenant") - .and_then(|value| value.to_str().ok()) - .map(str::to_owned), - content_type: headers - .get(http::header::CONTENT_TYPE) - .and_then(|value| value.to_str().ok()) - .map(str::to_owned), - body: body.to_vec(), - }); - let response_correlation = if state.unknown_submit.load(Ordering::SeqCst) { - "unmatched-correlation".to_owned() - } else { - correlation - }; - ( - http::StatusCode::ACCEPTED, - axum::Json(json!({"receipt":"beta-transfer-7","correlation":response_correlation})), - ) -} - -async fn second_provider_status( - axum::extract::State(state): axum::extract::State, - headers: http::HeaderMap, - uri: http::Uri, -) -> impl axum::response::IntoResponse { - state.requests.lock().unwrap().push(WireRequest { - method: http::Method::GET, - path: uri.path().to_owned(), - query: uri.query().map(str::to_owned), - authorization: headers - .get(http::header::AUTHORIZATION) - .and_then(|value| value.to_str().ok()) - .map(str::to_owned), - tenant: headers - .get("x-provider-tenant") - .and_then(|value| value.to_str().ok()) - .map(str::to_owned), - content_type: headers - .get(http::header::CONTENT_TYPE) - .and_then(|value| value.to_str().ok()) - .map(str::to_owned), - body: Vec::new(), - }); - let mismatch = state.mismatched_observation.load(Ordering::SeqCst); - let correlation = state.correlation.lock().unwrap().clone().unwrap(); - axum::Json(json!({ - "receipt":"beta-transfer-7", - "correlation":correlation, - "state":"complete", - "total":{"minorUnits":if mismatch { "2501" } else { "2500" },"currency":"KES","scale":2}, - "debtor":{"account":if mismatch { "other-payer" } else { "payer-account-1" },"address":"254700000001"} - })) -} - fn generic_provider_config(origin: &str, pack_bytes: &[u8], id: &str) -> PaymentsConfig { serde_json::from_value(json!({"connections":[{ "id":"fees","institutionId":"ministry","serviceId":"permit", @@ -838,419 +576,3 @@ fn generic_provider_config(origin: &str, pack_bytes: &[u8], id: &str) -> Payment fn second_provider_config(origin: &str, pack_bytes: &[u8]) -> PaymentsConfig { generic_provider_config(origin, pack_bytes, "second-provider") } - -async fn start_wire_provider() -> (String, WireProviderState, tokio::task::JoinHandle<()>) { - let state = WireProviderState { - requests: Arc::new(Mutex::new(Vec::new())), - correlation: Arc::new(Mutex::new(None)), - mismatched_observation: Arc::new(AtomicBool::new(true)), - unknown_submit: Arc::new(AtomicBool::new(false)), - }; - let router = axum::Router::new() - .route("/v2/payments", axum::routing::post(second_provider_submit)) - .route( - "/v2/payments/{payment}", - axum::routing::get(second_provider_status), - ) - .route( - "/v2/a/payments", - axum::routing::post(second_provider_submit), - ) - .route( - "/v2/a/payments/{payment}", - axum::routing::get(second_provider_status), - ) - .route( - "/v2/b/payments", - axum::routing::post(second_provider_submit), - ) - .route( - "/v2/b/payments/{payment}", - axum::routing::get(second_provider_status), - ) - .with_state(state.clone()); - let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); - let origin = format!("http://{}/", listener.local_addr().unwrap()); - let server = tokio::spawn(async move { - axum::serve(listener, router).await.unwrap(); - }); - (origin, state, server) -} - -#[tokio::test] -async fn generic_http_host_freezes_one_post_and_uses_read_only_status_for_a_second_provider() { - let (origin, state, server) = start_wire_provider().await; - - let pack_bytes = second_provider_pack(); - let program = compile_provider(&pack_bytes); - let secret_root = tempfile::tempdir().unwrap(); - let token_path = secret_root.path().join("provider-token"); - let resolver = - Arc::new(SecretResolver::new([SecretProvider::File], secret_root.path()).unwrap()); - - let (store, registry, _) = setup().await; - { - let mut bill = registry.bill.lock().unwrap(); - bill.snapshot.simulation = false; - bill.snapshot.money.currency = "KES".into(); - bill.snapshot.payer_financial_address = "254700000001".into(); - bill.snapshot.payer_id = "payer-account-1".into(); - } - let config = second_provider_config(&origin, &pack_bytes); - let mut mappings = PaymentMappingRegistry::default(); - mappings.insert(program).unwrap(); - let provider = Arc::new(SyntheticProvider::new(resolver, Some(Arc::new(mappings)))); - let service = PaymentService::new(config, store.clone(), registry.clone(), provider).unwrap(); - let request = RequestCollection { - bill_id: registry.bill.lock().unwrap().snapshot.bill_id, - bill_version: 1, - }; - assert_eq!( - service - .request("fees", &caller(), "second-provider-request", &request) - .await - .unwrap_err(), - Error::Unavailable, - "a local credential failure must not consume the one-send grant" - ); - let preflight_failed = store - .find_bill("ministry", "permit", request.bill_id, request.bill_version) - .await - .unwrap() - .unwrap(); - assert!(preflight_failed.bound); - assert!(preflight_failed.first_send_at.is_none()); - assert!(preflight_failed.transfer_id.is_none()); - assert!(state.requests.lock().unwrap().is_empty()); - - std::fs::write(&token_path, b"test-only-provider-token").unwrap(); - std::fs::set_permissions(&token_path, std::fs::Permissions::from_mode(0o600)).unwrap(); - let accepted = service - .request("fees", &caller(), "second-provider-request", &request) - .await - .unwrap(); - - let saved = store.get(accepted.collection_id).await.unwrap(); - let CollectionProviderCommand::Http(command) = &saved.provider_command else { - panic!("the generic provider must retain its exact prepared request"); - }; - assert_eq!( - saved.provider_command_digest.as_ref(), - Some(&digest(&saved.provider_command).unwrap()) - ); - assert_eq!(command.prepared_submit.path, "/v2/payments"); - assert_eq!(command.prepared_submit.query["mode"], "direct"); - assert_eq!( - command.prepared_submit.headers["x-provider-tenant"], - "pilot-beta" - ); - let expected_body = registry_platform_canonical_json::canonicalize_json(&json!({ - "command":{"id":command.intent["correlationId"]}, - "debtor":{"account":"payer-account-1","address":"254700000001"}, - "total":{"minorUnits":2500,"currency":"KES","scale":2} - })) - .unwrap(); - assert_eq!(command.prepared_submit.body.as_ref(), Some(&expected_body)); - - { - let requests = state.requests.lock().unwrap(); - assert_eq!(requests.len(), 1); - let post = &requests[0]; - assert_eq!(post.method, http::Method::POST); - assert_eq!(post.path, "/v2/payments"); - assert_eq!(post.query.as_deref(), Some("mode=direct")); - assert!(post.authorization.as_deref() == Some("Bearer test-only-provider-token")); - assert_eq!(post.tenant.as_deref(), Some("pilot-beta")); - assert_eq!(post.content_type.as_deref(), Some("application/json")); - assert_eq!(post.body, expected_body); - } - - assert_eq!( - service - .read("fees", &caller(), accepted.collection_id) - .await - .unwrap_err(), - Error::ProviderProtocol, - "provider money or payer mismatch must fail closed" - ); - assert!(store - .get(accepted.collection_id) - .await - .unwrap() - .observation - .is_none()); - state.mismatched_observation.store(false, Ordering::SeqCst); - assert_eq!( - service - .read("fees", &caller(), accepted.collection_id) - .await - .unwrap() - .state, - CollectionState::Confirmed - ); - assert_eq!( - service - .record_receipt( - "fees", - &caller(), - "second-provider-receipt", - accepted.collection_id, - ) - .await - .unwrap_err(), - Error::RecoveryHeld - ); - assert_eq!(registry.reports.load(Ordering::SeqCst), 0); - assert_eq!(registry.bill.lock().unwrap().state, BillState::AttemptBound); - - let requests = state.requests.lock().unwrap(); - assert_eq!(requests.len(), 3); - assert_eq!( - requests - .iter() - .filter(|request| request.method == http::Method::POST) - .count(), - 1, - "status reads and receipt refusal must not repeat the provider effect" - ); - for get in requests - .iter() - .filter(|request| request.method == http::Method::GET) - { - assert_eq!(get.path, "/v2/payments/beta-transfer-7"); - assert_eq!(get.query.as_deref(), Some("view=full")); - assert!(get.authorization.as_deref() == Some("Bearer test-only-provider-token")); - assert_eq!(get.tenant.as_deref(), Some("pilot-beta")); - assert!(get.content_type.is_none()); - assert!(get.body.is_empty()); - } - drop(requests); - server.abort(); -} - -fn mapping_registry( - programs: impl IntoIterator, -) -> Arc { - let mut registry = PaymentMappingRegistry::default(); - for program in programs { - registry.insert(program).unwrap(); - } - Arc::new(registry) -} - -fn install_test_token(root: &std::path::Path) { - let path = root.join("provider-token"); - std::fs::write(&path, b"test-only-provider-token").unwrap(); - std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600)).unwrap(); -} - -fn make_live_bill(registry: &Registry) { - let mut bill = registry.bill.lock().unwrap(); - bill.snapshot.simulation = false; - bill.snapshot.money.currency = "KES".into(); - bill.snapshot.payer_financial_address = "254700000001".into(); - bill.snapshot.payer_id = "payer-account-1".into(); -} - -#[tokio::test] -async fn retained_collection_selects_its_exact_pack_before_post_or_get() { - let (origin, state, server) = start_wire_provider().await; - state.mismatched_observation.store(false, Ordering::SeqCst); - let pack_a = - generic_provider_pack("provider-a", "/v2/a/payments", "/v2/a/payments/{{payment}}"); - let pack_b = - generic_provider_pack("provider-b", "/v2/b/payments", "/v2/b/payments/{{payment}}"); - let config_a = generic_provider_config(&origin, &pack_a, "provider-a"); - let config_b = generic_provider_config(&origin, &pack_b, "provider-b"); - - let secret_root = tempfile::tempdir().unwrap(); - install_test_token(secret_root.path()); - let resolver = - Arc::new(SecretResolver::new([SecretProvider::File], secret_root.path()).unwrap()); - let only_a = mapping_registry([compile_provider(&pack_a)]); - let only_b = mapping_registry([compile_provider(&pack_b)]); - let both = mapping_registry([compile_provider(&pack_a), compile_provider(&pack_b)]); - - let (accepted_store, accepted_registry, _) = setup().await; - make_live_bill(&accepted_registry); - let accepted_request = RequestCollection { - bill_id: accepted_registry.bill.lock().unwrap().snapshot.bill_id, - bill_version: 1, - }; - let service_a = PaymentService::new( - config_a.clone(), - accepted_store.clone(), - accepted_registry.clone(), - Arc::new(SyntheticProvider::new(resolver.clone(), Some(only_a))), - ) - .unwrap(); - let accepted_a = service_a - .request("fees", &caller(), "accepted-a", &accepted_request) - .await - .unwrap(); - assert_eq!(state.requests.lock().unwrap()[0].path, "/v2/a/payments"); - - let service_only_b = PaymentService::new( - config_b.clone(), - accepted_store.clone(), - accepted_registry.clone(), - Arc::new(SyntheticProvider::new( - resolver.clone(), - Some(only_b.clone()), - )), - ) - .unwrap(); - assert_eq!( - service_only_b - .read("fees", &caller(), accepted_a.collection_id) - .await - .unwrap_err(), - Error::Unavailable - ); - assert_eq!( - state.requests.lock().unwrap().len(), - 1, - "missing A must not GET" - ); - - let missing_secret_root = tempfile::tempdir().unwrap(); - let missing_resolver = - Arc::new(SecretResolver::new([SecretProvider::File], missing_secret_root.path()).unwrap()); - let (unsent_store, unsent_registry, _) = setup().await; - make_live_bill(&unsent_registry); - let unsent_request = RequestCollection { - bill_id: unsent_registry.bill.lock().unwrap().snapshot.bill_id, - bill_version: 1, - }; - let unsent_a = PaymentService::new( - config_a.clone(), - unsent_store.clone(), - unsent_registry.clone(), - Arc::new(SyntheticProvider::new( - missing_resolver.clone(), - Some(mapping_registry([compile_provider(&pack_a)])), - )), - ) - .unwrap(); - assert_eq!( - unsent_a - .request("fees", &caller(), "unsent-a", &unsent_request) - .await - .unwrap_err(), - Error::Unavailable - ); - install_test_token(missing_secret_root.path()); - let unsent_only_b = PaymentService::new( - config_b.clone(), - unsent_store, - unsent_registry, - Arc::new(SyntheticProvider::new(missing_resolver, Some(only_b))), - ) - .unwrap(); - assert_eq!( - unsent_only_b - .request("fees", &caller(), "unsent-a", &unsent_request) - .await - .unwrap_err(), - Error::Unavailable - ); - assert_eq!( - state.requests.lock().unwrap().len(), - 1, - "missing A must not POST" - ); - - let service_both = PaymentService::new( - config_b.clone(), - accepted_store, - accepted_registry, - Arc::new(SyntheticProvider::new(resolver.clone(), Some(both.clone()))), - ) - .unwrap(); - assert_eq!( - service_both - .read("fees", &caller(), accepted_a.collection_id) - .await - .unwrap() - .state, - CollectionState::Confirmed - ); - assert_eq!( - state.requests.lock().unwrap()[1].path, - "/v2/a/payments/beta-transfer-7" - ); - - let (new_store, new_registry, _) = setup().await; - make_live_bill(&new_registry); - let new_request = RequestCollection { - bill_id: new_registry.bill.lock().unwrap().snapshot.bill_id, - bill_version: 1, - }; - let new_b = PaymentService::new( - config_b, - new_store, - new_registry, - Arc::new(SyntheticProvider::new(resolver, Some(both))), - ) - .unwrap(); - new_b - .request("fees", &caller(), "new-b", &new_request) - .await - .unwrap(); - assert_eq!(state.requests.lock().unwrap()[2].path, "/v2/b/payments"); - server.abort(); -} - -#[tokio::test] -async fn unknown_generic_send_never_reauthorizes_the_retained_command() { - let (origin, state, server) = start_wire_provider().await; - state.unknown_submit.store(true, Ordering::SeqCst); - let pack = generic_provider_pack("provider-b", "/v2/b/payments", "/v2/b/payments/{{payment}}"); - let config = generic_provider_config(&origin, &pack, "provider-b"); - let secret_root = tempfile::tempdir().unwrap(); - install_test_token(secret_root.path()); - let resolver = - Arc::new(SecretResolver::new([SecretProvider::File], secret_root.path()).unwrap()); - let (store, registry, _) = setup().await; - make_live_bill(®istry); - let request = RequestCollection { - bill_id: registry.bill.lock().unwrap().snapshot.bill_id, - bill_version: 1, - }; - let service = PaymentService::new( - config, - store, - registry, - Arc::new(SyntheticProvider::new( - resolver, - Some(mapping_registry([compile_provider(&pack)])), - )), - ) - .unwrap(); - assert_eq!( - service - .request("fees", &caller(), "unknown-b", &request) - .await - .unwrap_err(), - Error::OutcomeUnknown - ); - state.unknown_submit.store(false, Ordering::SeqCst); - assert_eq!( - service - .request("fees", &caller(), "unknown-b", &request) - .await - .unwrap_err(), - Error::RecoveryHeld - ); - assert_eq!( - state - .requests - .lock() - .unwrap() - .iter() - .filter(|request| request.method == http::Method::POST) - .count(), - 1 - ); - server.abort(); -} diff --git a/crates/registry-adapterctl/src/payments.rs b/crates/registry-adapterctl/src/payments.rs index df85f79a2a..f887d2d466 100644 --- a/crates/registry-adapterctl/src/payments.rs +++ b/crates/registry-adapterctl/src/payments.rs @@ -2,7 +2,7 @@ //! Offline payment configuration checks; neither command resolves credentials. use crate::payment_fixtures::{self, FixtureError}; use clap::{Args, Subcommand}; -use registry_adapter::payments::config::{PaymentsConfig, API_VERSION, KIND}; +use registry_adapter::payments::config::{ConfigError, PaymentsConfig, API_VERSION, KIND}; use registry_adapter::payments::pack::{ ConnectorKind, PaymentCapability, PaymentProviderAuth, PaymentProviderPack, ProviderPackPin, }; @@ -263,10 +263,16 @@ pub fn run(command: &PaymentsCommand) -> PaymentCheck { let mut companion_diagnostics = Vec::new(); let mut value = json!({}); if let Some(loaded) = &check.loaded { - if loaded.config.validate().is_err() { - additional.push(check.error_at(KIND, "adapter.payment.configuration", "/connections", - "The payment connections were refused.", - "Check connection scopes, unique caller identities, currency and synthetic provider bindings; then retry.")); + if let Err(error) = loaded.config.validate() { + additional.push(if error == ConfigError::COLLECTION_SIMULATION_ONLY { + check.error_at(KIND, error.code(), "/connections", + "A collection connection names a live provider; collections run only against the synthetic simulator.", + "Bind each collection to the simulator provider with simulation: true; then retry.") + } else { + check.error_at(KIND, error.code(), "/connections", + "The payment connections were refused.", + "Check connection scopes, unique caller identities, currency and synthetic provider bindings; then retry.") + }); } else { match ProviderPackRegistry::load(provider_packs) { Ok(registry) => { diff --git a/crates/registry-adapterctl/tests/payments.rs b/crates/registry-adapterctl/tests/payments.rs index 04931d4abc..495f3746ba 100644 --- a/crates/registry-adapterctl/tests/payments.rs +++ b/crates/registry-adapterctl/tests/payments.rs @@ -5,61 +5,16 @@ use std::{ process::ExitCode, }; -const MAPPED_PROVIDER_SCRIPT: &str = r#" -fn submit_request(intent, settings, acceptance) { - if settings == () || acceptance != () { throw "invalid submit context"; } - #{pathParameters: #{}, query: #{}, headers: #{}, body: #{correlation: intent.correlationId}} -} -fn submit_response(intent, settings, acceptance, response) { - if settings == () || acceptance != () || response == () { throw "invalid submit context"; } - #{correlationId: intent.correlationId, references: #{transaction: "accepted"}} -} -fn status_request(intent, settings, acceptance) { - if intent == () || settings == () || acceptance == () { throw "status needs context"; } - #{pathParameters: #{}, query: #{}, headers: #{}, body: ()} -} -fn status_response(intent, settings, acceptance, response) { - if settings == () || acceptance == () || response == () { throw "status needs context"; } - #{ - correlationId: intent.correlationId, - providerReference: "accepted", - state: "pending", - money: intent.money, - parties: [#{role: "payer", key: intent.source.scheme, value: intent.source.value}] - } -} -"#; - -fn mapped_provider_pack(id: &str) -> String { +fn simulator_provider_pack(id: &str) -> String { format!( - r#"apiVersion: id.registrystack.org/formats/adapter/payment-provider-pack/v1alpha1 -kind: AdapterPaymentProviderPack -id: {id} -version: '1' -connector: adapter-payment-http/v1 -capabilities: [collection] -mapping: - collection: - auth: bearer - submit: - path: /collections - request: {{file: mapping.rhai, entrypoint: submit_request}} - response: {{file: mapping.rhai, entrypoint: submit_response}} - status: - path: /collections/status - request: {{file: mapping.rhai, entrypoint: status_request}} - response: {{file: mapping.rhai, entrypoint: status_response}} - scripts: - - path: mapping.rhai - digest: {} -"#, - registry_platform_config::sha256_uri(MAPPED_PROVIDER_SCRIPT.as_bytes()) + "apiVersion: id.registrystack.org/formats/adapter/payment-provider-pack/v1alpha1\n\ +kind: AdapterPaymentProviderPack\nid: {id}\nversion: '1'\nconnector: simulator-p2g/v1\n\ +capabilities: [collection]\n" ) } -fn write_mapped_provider_pack(directory: &Path, id: &str) -> (PathBuf, String) { - std::fs::write(directory.join("mapping.rhai"), MAPPED_PROVIDER_SCRIPT).unwrap(); - let bytes = mapped_provider_pack(id); +fn write_simulator_provider_pack(directory: &Path, id: &str) -> (PathBuf, String) { + let bytes = simulator_provider_pack(id); let path = directory.join(format!("{id}.yaml")); std::fs::write(&path, &bytes).unwrap(); let digest = registry_platform_config::sha256_uri(bytes.as_bytes()); @@ -107,6 +62,23 @@ fn mapped_collection(id: &str, pack_id: &str, digest: &str) -> Value { }) } +fn pinned_simulator_collection(id: &str, pack_id: &str, digest: &str) -> Value { + let mut connection = mapped_collection(id, pack_id, digest); + connection["binding"]["simulation"] = json!(true); + connection["binding"]["provider"] = json!({ + "type": "simulator", + "connection": { + "baseUrl": "http://127.0.0.1:8099/", + "tenant": "pilot", + "biller": "ministry", + "billerName": "Ministry", + "callbackUrl": "https://programme.example.test/callback", + "payerFiBic": "SIMBANK" + } + }); + connection +} + fn write_payments(directory: &Path, connections: Vec) -> PathBuf { let path = directory.join("payments.json"); std::fs::write( @@ -344,13 +316,14 @@ fn payment_check_consumes_the_exact_pinned_provider_pack() { #[test] fn payment_check_and_contract_accept_distinct_active_provider_pins() { let directory = tempfile::tempdir().unwrap(); - let (alpha_path, alpha_digest) = write_mapped_provider_pack(directory.path(), "provider-alpha"); - let (beta_path, beta_digest) = write_mapped_provider_pack(directory.path(), "provider-beta"); + let (alpha_path, alpha_digest) = + write_simulator_provider_pack(directory.path(), "provider-alpha"); + let (beta_path, beta_digest) = write_simulator_provider_pack(directory.path(), "provider-beta"); let file = write_payments( directory.path(), vec![ - mapped_collection("alpha-fees", "provider-alpha", &alpha_digest), - mapped_collection("beta-fees", "provider-beta", &beta_digest), + pinned_simulator_collection("alpha-fees", "provider-alpha", &alpha_digest), + pinned_simulator_collection("beta-fees", "provider-beta", &beta_digest), ], ); @@ -378,13 +351,14 @@ fn payment_check_and_contract_accept_distinct_active_provider_pins() { #[test] fn payment_check_fails_closed_for_a_missing_or_mismatched_active_pack() { let directory = tempfile::tempdir().unwrap(); - let (alpha_path, alpha_digest) = write_mapped_provider_pack(directory.path(), "provider-alpha"); - let (beta_path, beta_digest) = write_mapped_provider_pack(directory.path(), "provider-beta"); + let (alpha_path, alpha_digest) = + write_simulator_provider_pack(directory.path(), "provider-alpha"); + let (beta_path, beta_digest) = write_simulator_provider_pack(directory.path(), "provider-beta"); let file = write_payments( directory.path(), vec![ - mapped_collection("alpha-fees", "provider-alpha", &alpha_digest), - mapped_collection("beta-fees", "provider-beta", &beta_digest), + pinned_simulator_collection("alpha-fees", "provider-alpha", &alpha_digest), + pinned_simulator_collection("beta-fees", "provider-beta", &beta_digest), ], ); @@ -411,7 +385,7 @@ fn payment_check_fails_closed_for_a_missing_or_mismatched_active_pack() { std::fs::write( &beta_path, - mapped_provider_pack("provider-beta").replace( + simulator_provider_pack("provider-beta").replace( "capabilities: [collection]", "capabilities: [collection]\ntestedVersions: [tampered]", ), @@ -434,10 +408,14 @@ fn payment_check_fails_closed_for_a_missing_or_mismatched_active_pack() { #[test] fn payment_check_bounds_the_provider_pack_registry() { let directory = tempfile::tempdir().unwrap(); - let (pack_path, digest) = write_mapped_provider_pack(directory.path(), "provider-alpha"); + let (pack_path, digest) = write_simulator_provider_pack(directory.path(), "provider-alpha"); let file = write_payments( directory.path(), - vec![mapped_collection("alpha-fees", "provider-alpha", &digest)], + vec![pinned_simulator_collection( + "alpha-fees", + "provider-alpha", + &digest, + )], ); let mut args = vec![ "adapterctl".into(), @@ -459,16 +437,40 @@ fn payment_check_bounds_the_provider_pack_registry() { ); } +#[test] +fn payment_check_refuses_a_live_collection_as_simulation_only() { + let directory = tempfile::tempdir().unwrap(); + let digest = format!("sha256:{}", "a".repeat(64)); + let file = write_payments( + directory.path(), + vec![mapped_collection("alpha-fees", "provider-alpha", &digest)], + ); + let (code, report) = run_json(vec![ + "adapterctl".into(), + "--format".into(), + "json".into(), + "payments".into(), + "check".into(), + file.display().to_string(), + ]); + assert_eq!(code, ExitCode::from(1), "{report}"); + assert_eq!( + report["diagnostics"][0]["code"], "adapter.payment.collection-simulation-only", + "{report}" + ); +} + #[test] fn payment_check_refuses_ambiguous_multi_pack_fixture_replay() { let directory = tempfile::tempdir().unwrap(); - let (alpha_path, alpha_digest) = write_mapped_provider_pack(directory.path(), "provider-alpha"); - let (beta_path, beta_digest) = write_mapped_provider_pack(directory.path(), "provider-beta"); + let (alpha_path, alpha_digest) = + write_simulator_provider_pack(directory.path(), "provider-alpha"); + let (beta_path, beta_digest) = write_simulator_provider_pack(directory.path(), "provider-beta"); let file = write_payments( directory.path(), vec![ - mapped_collection("alpha-fees", "provider-alpha", &alpha_digest), - mapped_collection("beta-fees", "provider-beta", &beta_digest), + pinned_simulator_collection("alpha-fees", "provider-alpha", &alpha_digest), + pinned_simulator_collection("beta-fees", "provider-beta", &beta_digest), ], ); let fixture = directory.path().join("fixture.yaml"); diff --git a/docs/site/src/content/docs/configure/adapter.mdx b/docs/site/src/content/docs/configure/adapter.mdx index 3c06b111c2..17898ddce7 100644 --- a/docs/site/src/content/docs/configure/adapter.mdx +++ b/docs/site/src/content/docs/configure/adapter.mdx @@ -1093,11 +1093,14 @@ The Adapter core and the shared engine keep their source-neutral dependency boun ### Collection +Collections run only against the synthetic payment simulator. +A collection connection must use the `simulator` provider with `simulation: true`; any other collection provider is refused at load with `adapter.payment.collection-simulation-only`, by both `adapter serve` and `adapterctl payments check`. + Before any provider send, PostgreSQL reserves one attempt per institution, service, bill and bill version across workflow command keys. The host persists the exact bind Action and key, invokes that restricted Action, and verifies the frozen authoritative bill binding. It then persists the first dispatch time before sending the original exact provider command. An accepted response means the provider accepted the request, not merely that a local row exists, and an unknown outcome stays unresolved. -The simulator allows an exact same-command resend inside the original connection's declared replay window, and an unknown HTTP provider submission stays held after dispatch. +The simulator allows an exact same-command resend inside the original connection's declared replay window. Provider identifiers derive from a domain-separated digest of the full immutable bill and the provider origin, producer identity, tenant and biller, so independent Adapter databases do not allocate overlapping identities. Disjoint digest portions fit the provider's request, request-to-pay and bill fields, and the provider must reject a reused request identifier with a different body. @@ -1105,13 +1108,12 @@ Stored commands are checked against that derivation and replayed exactly. The original-command receipt lookup is a database read. Collection reads may observe the provider but never bind, dispatch or record a receipt. -A confirmed provider observation must match the complete saved request, transfer, bill, amount and currency tuple, and a pending state, including a provider `COM/PENDING`, never authorises a receipt. +A confirmed provider observation must match the complete saved request, transfer, bill, amount and currency tuple, and a pending state, including the simulator's `COM/PENDING`, never authorises a receipt. The receipt step accepts only a collection identifier. The host derives the receipt from its confirmed observation and frozen bill, persists the exact restricted BReg report Action and key, and verifies the authoritative readback. A lost bind or report acknowledgement recovers from the saved command or exact readback. The numeric-loopback simulator preserves exact decimal JSON and requires synthetic response provenance before it authorises a synthetic fee receipt. -Generic provider-pack observations are available as correlated status. ### Disbursement @@ -1141,7 +1143,9 @@ They include the restricted bill and instruction facts needed for recovery, so p Generic facade response-retention sweeps do not delete payment attempts. Payment audit events carry no values and commit before an effect or a response is released. -{/* Evidence: crates/registry-adapter/src/payments/service.rs; +{/* Evidence: crates/registry-adapter/src/payments/config.rs COLLECTION_SIMULATION_ONLY; + crates/registry-adapter/tests/payment_config.rs live_mifos_collections_are_refused_as_simulation_only; + crates/registry-adapter/src/payments/service.rs; crates/registry-adapter/src/payments/g2p_model.rs mifos-legacy-signature; crates/registry-adapter/tests/payment_service.rs; crates/registry-adapter/tests/payment_store.rs; diff --git a/products/adapter/schemas/payments.v1alpha1.schema.json b/products/adapter/schemas/payments.v1alpha1.schema.json index 036f22f45d..e6385e20dc 100644 --- a/products/adapter/schemas/payments.v1alpha1.schema.json +++ b/products/adapter/schemas/payments.v1alpha1.schema.json @@ -485,6 +485,8 @@ "type": "integer" }, "simulation": { + "const": true, + "description": "Collections are simulation-only; a live collection provider is refused.", "type": "boolean" } }, From 4283213d88958d0558a4b5d4451560307621e8f4 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Thu, 19 Nov 2026 22:54:13 +0000 Subject: [PATCH 23/40] fix(payments): treat a simulator payer cancellation as a failed collection The simulator reports a cancel on its hosted page, or a cancelled payer rule, as RJC/FAILED with failureReason payer-cancelled. The connector refused that pairing as a protocol error, holding the collection. Map it to CollectionState::Failed like payer-rejected. The tests use a status body captured from the simulator for a cancelled payer rule, decoded directly and through SimulatorClient. Signed-off-by: Jeremi Joslin --- .../src/lib.rs | 5 +- .../tests/profile.rs | 72 +++++++++++++++++++ 2 files changed, 76 insertions(+), 1 deletion(-) diff --git a/crates/registry-payment-simulator-connector/src/lib.rs b/crates/registry-payment-simulator-connector/src/lib.rs index c3adb7c0ed..74943d22ed 100644 --- a/crates/registry-payment-simulator-connector/src/lib.rs +++ b/crates/registry-payment-simulator-connector/src/lib.rs @@ -272,7 +272,10 @@ impl ProviderCommand { } ("RJC", "FAILED") if response.reference.is_none() - && response.failure_reason.as_deref() == Some("payer-rejected") => + && matches!( + response.failure_reason.as_deref(), + Some("payer-rejected" | "payer-cancelled") + ) => { CollectionState::Failed } diff --git a/crates/registry-payment-simulator-connector/tests/profile.rs b/crates/registry-payment-simulator-connector/tests/profile.rs index de717eb8ae..1c9707b679 100644 --- a/crates/registry-payment-simulator-connector/tests/profile.rs +++ b/crates/registry-payment-simulator-connector/tests/profile.rs @@ -81,6 +81,78 @@ fn confirmation_requires_synthetic_reference_and_exact_valid_pair() { } } +// Captured from the payment simulator for a payer whose outcome rule is +// `cancelled`: the rule settles the request at creation. +const CANCELLED_TRANSFER: &str = "97b18987-d833-413d-80cb-ce8f83e5468d"; +const CANCELLED_ACCEPTANCE: &str = r#"{"responseCode":"00","responseDescription":"Accepted","requestID":"request1","rtpId":1,"transferRequestId":"97b18987-d833-413d-80cb-ce8f83e5468d"}"#; +const CANCELLED_STATUS: &str = r#"{"transferRequestId":"97b18987-d833-413d-80cb-ce8f83e5468d","RequestId":"request1","rtpId":1,"billId":"bill1","amount":25.50,"currency":"USD","requestStatus":"RJC","paymentStatus":"FAILED","lastUpdateDate":1795128182,"failureReason":"payer-cancelled"}"#; + +#[test] +fn payer_cancellation_is_a_failed_collection() { + let observation = command() + .decode_status(CANCELLED_TRANSFER, CANCELLED_STATUS.as_bytes()) + .unwrap(); + assert_eq!(observation.state, CollectionState::Failed); + assert_eq!( + observation.failure_reason.as_deref(), + Some("payer-cancelled") + ); + assert_eq!(observation.provider_reference, None); + for (from, to) in [ + ("payer-cancelled", "payer-unsure"), + ("\"RJC\"", "\"EXP\""), + ( + "\"failureReason\"", + "\"PaymentReferenceID\":\"SIM-1\",\"failureReason\"", + ), + ] { + let changed = CANCELLED_STATUS.replace(from, to); + assert!(command() + .decode_status(CANCELLED_TRANSFER, changed.as_bytes()) + .is_err()); + } +} + +#[tokio::test] +async fn a_cancelled_payer_rule_reaches_the_connector_as_a_failed_collection() { + use registry_payment_simulator_connector::SimulatorClient; + use registry_platform_httputil::client::BearerToken; + use tokio::io::{AsyncReadExt, AsyncWriteExt}; + 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 { + for (route, body) in [ + ("POST /rtpRequest ".to_owned(), CANCELLED_ACCEPTANCE), + ( + format!("GET /transferRequests/{CANCELLED_TRANSFER} "), + CANCELLED_STATUS, + ), + ] { + let (mut socket, _) = listener.accept().await.unwrap(); + let mut request = vec![0; 4096]; + let count = socket.read(&mut request).await.unwrap(); + assert!(std::str::from_utf8(&request[..count]) + .unwrap() + .starts_with(&route)); + let response = format!("HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nX-Payment-Simulator: synthetic\r\nX-CorrelationID: request1\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", body.len()); + socket.write_all(response.as_bytes()).await.unwrap(); + } + }); + let mut config = connection(); + config.base_url = format!("http://{address}/"); + let client = SimulatorClient::new(config).unwrap(); + let token = BearerToken::new("canary-synthetic-provider-token").unwrap(); + let transfer = client.submit(&command(), &token).await.unwrap(); + assert_eq!(transfer, CANCELLED_TRANSFER); + let observation = client.observe(&command(), &transfer, &token).await.unwrap(); + assert_eq!(observation.state, CollectionState::Failed); + assert_eq!( + observation.failure_reason.as_deref(), + Some("payer-cancelled") + ); + server.await.unwrap(); +} + #[tokio::test] async fn an_invalid_acknowledgement_after_dispatch_is_an_unknown_outcome() { use registry_payment_simulator_connector::{ConnectorError, SimulatorClient}; From 3e69672784b13d2656f376a17f2aa758c6f166e7 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Thu, 19 Nov 2026 22:54:28 +0000 Subject: [PATCH 24/40] docs(adapter): list the disbursement table grants Startup checks the adapter_g2p tables when disbursements are configured; the payment example listed only the collection grants. Signed-off-by: Jeremi Joslin --- products/adapter/examples/payment-collections/README.md | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/products/adapter/examples/payment-collections/README.md b/products/adapter/examples/payment-collections/README.md index 3ff43abad5..b79ccba8ed 100644 --- a/products/adapter/examples/payment-collections/README.md +++ b/products/adapter/examples/payment-collections/README.md @@ -105,6 +105,15 @@ GRANT USAGE, SELECT ON SEQUENCE adapter_payment_events_sequence_seq TO payment_adapter_runtime; ``` +When the payments configuration also declares `disbursements`, startup checks +the disbursement tables too. Grant these as well: + +```sql +GRANT SELECT, INSERT, UPDATE ON adapter_g2p_attempts TO payment_adapter_runtime; +GRANT SELECT, INSERT ON adapter_g2p_commands, adapter_g2p_events TO payment_adapter_runtime; +GRANT USAGE ON SEQUENCE adapter_g2p_events_sequence_seq TO payment_adapter_runtime; +``` + Production builds retain the shared Adapter PostgreSQL TLS requirement. The `postgres-test` feature permits explicitly configured plaintext only for isolated test databases. From 3210aff2f76be54220f26a138e402a8a65f5ae8b Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Thu, 19 Nov 2026 22:54:53 +0000 Subject: [PATCH 25/40] docs(adapter): say the operator supplies the Mifos provider pack The mifos-payment-hub pack is not in this repository or published yet. Say the operator supplies a reviewed pack matching the pin, and show --payment-provider-pack on adapter serve in the example and on the Adapter configure page. Signed-off-by: Jeremi Joslin --- .../src/content/docs/configure/adapter.mdx | 12 ++++++++++++ .../examples/payment-collections/README.md | 19 ++++++++++++++++--- 2 files changed, 28 insertions(+), 3 deletions(-) diff --git a/docs/site/src/content/docs/configure/adapter.mdx b/docs/site/src/content/docs/configure/adapter.mdx index 17898ddce7..02acb632ff 100644 --- a/docs/site/src/content/docs/configure/adapter.mdx +++ b/docs/site/src/content/docs/configure/adapter.mdx @@ -1125,6 +1125,18 @@ An uncertain submission stays held, and Coordinator can reconcile the original a The `mifos-legacy-signature` host profile signs the exact Bulk request and verifies the raw acknowledgement and the expected tenant before interpreting it. Request signing and response verification use separate pinned Transit keys, and Operations status reads use a separate bearer credential. +A disbursement connection pins its provider pack by id, version and digest. +Pass that pack to the host with `--payment-provider-pack`, and repeat the option for every pack an active connection or a retained attempt still pins: + +```sh +adapter serve --runtime-config /absolute/path/runtime.yaml \ + --payments-config /absolute/path/payments.yaml \ + --payment-provider-pack /absolute/path/mifos-payment-hub/pack.yaml +``` + +Registry Stack does not publish a Mifos Payment Hub EE pack yet, so the operator supplies a reviewed pack whose bytes match the pin. +`adapterctl payments check` takes the same pack with `--provider-pack` and checks the pin offline. + The separate confirmation operation accepts only a disbursement identifier. The Adapter reports verified provider completion through its restricted BReg Action, using the original instruction facts and a separately keyed exact command. The resulting confirmation records what the provider reported; credit to the recipient and settlement require separate authoritative evidence. diff --git a/products/adapter/examples/payment-collections/README.md b/products/adapter/examples/payment-collections/README.md index b79ccba8ed..fa6760ca81 100644 --- a/products/adapter/examples/payment-collections/README.md +++ b/products/adapter/examples/payment-collections/README.md @@ -7,8 +7,10 @@ It does not accept real payments or claim general GovStack Payments conformance. The [contract and capability comparison](CONTRACT.md) names the exact HTTP surface, ownership and differences from the earlier composition capability. The separate `payments.mifos.example.yaml` adds an authoritative G2P -disbursement connection pinned to the public `mifos-payment-hub` pack. It is -an operator configuration example, not evidence of a live Mifos deployment. +disbursement connection pinned to a `mifos-payment-hub` provider pack. That +pack is not in this repository and is not published yet: the operator supplies +a reviewed pack whose id, version and digest match the pin. The file is an +operator configuration example, not evidence of a live Mifos deployment. A service creates the authoritative bill. The Coordinator workflow then uses native payment operations: @@ -69,7 +71,8 @@ Build matching `adapter` and `adapterctl` binaries from this checkout, using the repository's external Cargo target directory. Check the configuration against the exact pack pinned in `providerPack`, without resolving credentials or contacting a provider. The pack path must contain bytes whose id, version -and digest match that pin: +and digest match that pin; for the Mifos example, that is the operator-supplied +`mifos-payment-hub` pack: ```sh adapterctl payments check /absolute/path/payments.mifos.yaml \ @@ -85,6 +88,16 @@ adapter serve --runtime-config /absolute/path/runtime.yaml \ --payments-config /absolute/path/payments.yaml ``` +A configuration that pins a provider pack, such as the Mifos disbursement +example, also names that pack. Repeat `--payment-provider-pack` for every +pack an active connection or a retained attempt still pins: + +```sh +adapter serve --runtime-config /absolute/path/runtime.yaml \ + --payments-config /absolute/path/payments.mifos.yaml \ + --payment-provider-pack /absolute/path/mifos-payment-hub/pack.yaml +``` + Pass the same `--payments-config` beside an existing `--project` to share a record facade's listener and database. Payment routes have their own fixed contract; they do not require a record profile or a generic HTTP workflow From 05bf2761be2daad78012bbafdeb7de77381638a1 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Thu, 19 Nov 2026 22:54:59 +0000 Subject: [PATCH 26/40] docs(coordinator): say the disbursement example runs offline only Only the collection example runs against the simulator. The disbursement example is checked and tested with coordinatorctl scenarios; no simulator pack or Adapter example backs its connection. Signed-off-by: Jeremi Joslin --- docs/site/src/content/docs/configure/coordinator.mdx | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/site/src/content/docs/configure/coordinator.mdx b/docs/site/src/content/docs/configure/coordinator.mdx index f7778eeaff..67c68bd5fe 100644 --- a/docs/site/src/content/docs/configure/coordinator.mdx +++ b/docs/site/src/content/docs/configure/coordinator.mdx @@ -841,7 +841,8 @@ The request and read operations expose the completion `disbursement`, which keep Only a verified `provider-confirmed` disbursement lets `payments.record-provider-confirmation/v1` succeed. Provider confirmation records what the provider reported; it does not claim credit to the recipient or final settlement, and a timeout establishes none of those facts. -The [payment collection](https://github.com/registrystack/registry-stack/tree/main/products/coordinator/examples/payment-collections) and [disbursement](https://github.com/registrystack/registry-stack/tree/main/products/coordinator/examples/g2p-disbursements) examples show both workflows against the synthetic payment simulator. +The [payment collection example](https://github.com/registrystack/registry-stack/tree/main/products/coordinator/examples/payment-collections) runs against the synthetic payment simulator through the Adapter payment host. +The [disbursement example](https://github.com/registrystack/registry-stack/tree/main/products/coordinator/examples/g2p-disbursements) is checked and tested offline with `coordinatorctl` scenarios only: the simulator has no disbursement pack, and no Adapter example defines its `g2p-disbursements` connection. {/* Evidence: crates/registry-coordinator/src/operations.rs payments.request-collection/v1, payments.request-disbursement/v1; From baf69b068fbdd5d56a98e31c308d950328563e1d Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Thu, 19 Nov 2026 22:55:15 +0000 Subject: [PATCH 27/40] docs(adapter): describe disbursements in the release notes The changelog and example limits read as if no live provider ships. Add the disbursement entry (operations, provider packs, --payment-provider-pack, bearer and mifos-legacy-signature authentication), say live collection providers where collections are meant, and state that live Mifos signing through a real Transit engine is unverified, so a live disbursement must not move real money until that follow-up lands. Signed-off-by: Jeremi Joslin --- products/adapter/CHANGELOG.md | 19 +++++++++++++++++-- .../examples/payment-collections/README.md | 5 ++++- 2 files changed, 21 insertions(+), 3 deletions(-) diff --git a/products/adapter/CHANGELOG.md b/products/adapter/CHANGELOG.md index 5509469042..f972bca507 100644 --- a/products/adapter/CHANGELOG.md +++ b/products/adapter/CHANGELOG.md @@ -111,8 +111,23 @@ Retained attempts preserve their original binding and exact commands across response loss and restart. Only a confirmed, correlated receipt can mark the authoritative bill paid. One attempt is permitted per bill version, - including after definitive failure; live providers, replacement attempts, - refunds and settlement are outside this slice. + including after definitive failure. Collections are simulation-only: a + collection binding other than the simulator with `simulation: true` is + refused with `adapter.payment.collection-simulation-only`. Live collection + providers, replacement attempts, refunds and settlement are outside this + slice. +- The same host serves typed G2P disbursements: request a disbursement from an + approved BReg instruction, read its correlated provider observation, and + report verified provider confirmation through a restricted BReg Action. An + uncertain submission is never sent again. Disbursement connections pin a + provider pack, passed to `adapter serve` with a repeatable + `--payment-provider-pack`, and authenticate with `bearer` or, for Mifos + Payment Hub EE, `mifos-legacy-signature`, which signs the exact Bulk request + through a pinned Transit key and reads Operations status under a separate + bearer credential. Live Mifos signing through a real Transit engine is not + verified yet; do not let a live disbursement move real money until that + verification lands. A provider confirmation is not proof of beneficiary + credit or settlement. - `adapterctl payments check` validates connections offline and `adapterctl payments contract` exports their typed HTTP contract. Generated schemas, a native Coordinator workflow, the restricted BReg fee fixture, diff --git a/products/adapter/examples/payment-collections/README.md b/products/adapter/examples/payment-collections/README.md index fa6760ca81..23f49a53f5 100644 --- a/products/adapter/examples/payment-collections/README.md +++ b/products/adapter/examples/payment-collections/README.md @@ -158,7 +158,10 @@ connection/service scope. This slice permits one attempt per bill version, including after a definitive failure. There is no replacement-attempt operation, refund, settlement, -callback handler or live-provider connector. Attempts and command receipts +callback handler or live collection provider. Disbursements can bind a live +provider pack, but live Mifos signing through a real Transit engine is not +verified yet: do not let a live disbursement move real money until that +verification lands. Attempts and command receipts have no automatic expiry; they contain restricted bill/payer facts needed for recovery and require protected database storage and backup. Generic facade retention does not erase these records. From 3fa0b13985afa29f8db9286710f471ffe16bceb8 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Thu, 19 Nov 2026 22:56:26 +0000 Subject: [PATCH 28/40] docs(payments): explain resuming an unresolved payment run Starting the same workflow again with the same bill or instruction identity reattaches to the version's existing attempt, and record-receipt returns a receipt already recorded. A declined, cancelled or expired collection, or a failed disbursement, keeps the version bound to its attempt; a new version is the way to try again. Signed-off-by: Jeremi Joslin --- docs/site/src/content/docs/operate/coordinator.mdx | 9 ++++++++- .../coordinator/examples/g2p-disbursements/README.md | 9 +++++++++ .../coordinator/examples/payment-collections/README.md | 10 ++++++++++ 3 files changed, 27 insertions(+), 1 deletion(-) diff --git a/docs/site/src/content/docs/operate/coordinator.mdx b/docs/site/src/content/docs/operate/coordinator.mdx index 22bff1d8e6..88ec886957 100644 --- a/docs/site/src/content/docs/operate/coordinator.mdx +++ b/docs/site/src/content/docs/operate/coordinator.mdx @@ -1036,9 +1036,16 @@ An uncertain `payments.request-disbursement/v1` stays held. The separate `payments.record-receipt/v1` and `payments.record-provider-confirmation/v1` reporting commands may use `retry-same` with their frozen body and key. Investigate an unresolved original-request receipt with the Adapter operator before any same-command recovery or cancellation decision. +A run that ended without a settled payment, such as one whose wait timed out, is resumed by starting the same workflow again with the same bill or instruction identity and version. +The Adapter reattaches the new run to that version's existing attempt instead of creating a second one, and `payments.record-receipt/v1` returns a receipt already recorded for it. +A declined, cancelled or expired collection, or a failed disbursement, leaves the bill or instruction bound to its attempt, because the Adapter permits one attempt per version. +Issue a new bill or instruction version to try again. + {/* Evidence: crates/registry-coordinator/tests/payment_adapter.rs collection_request_and_recovery_use_the_exact_original_command, - uncertain_disbursement_submission_never_becomes_a_fresh_send. */} + uncertain_disbursement_submission_never_becomes_a_fresh_send; + crates/registry-adapter/src/payments/service.rs find_bill; + crates/registry-adapter/src/payments/g2p_service.rs find_instruction. */} ### Waits diff --git a/products/coordinator/examples/g2p-disbursements/README.md b/products/coordinator/examples/g2p-disbursements/README.md index c0ab77ae00..578ee33cd3 100644 --- a/products/coordinator/examples/g2p-disbursements/README.md +++ b/products/coordinator/examples/g2p-disbursements/README.md @@ -25,6 +25,15 @@ instruction and key. An uncertain `record-provider-confirmation` may use `retry-same`, which resends only the saved reporting command under its saved key. Neither recovery path permits a fresh provider submission. +A run that ended `disbursement-unresolved` is resumed by starting this workflow +again with the same `instructionRecordId` and `instructionVersion`. The Adapter +reattaches the new run to that instruction version's existing attempt; it never +submits a second disbursement for it. + +A failed disbursement leaves the instruction bound to that attempt: the Adapter +permits one attempt per instruction version. A new attempt needs a new +approved instruction version. + ## Check and package From the repository root, use binaries built from this checkout: diff --git a/products/coordinator/examples/payment-collections/README.md b/products/coordinator/examples/payment-collections/README.md index c2fa592cf6..96f27772d6 100644 --- a/products/coordinator/examples/payment-collections/README.md +++ b/products/coordinator/examples/payment-collections/README.md @@ -23,6 +23,16 @@ read-only original-request lookup. Recover `record-receipt` with or send a fresh command. This also applies to an ambiguous `adapter.payment.provider-protocol` response after dispatch. +A run that ended `collection-unresolved` is resumed by starting this workflow +again with the same `billId` and `billVersion`. The Adapter reattaches the new +run to the bill version's existing attempt instead of creating a second one, +and a later `record-receipt` returns the receipt already recorded for it. + +A declined, cancelled or expired collection (`collection-failed`) leaves the +bill bound to that attempt: the Adapter permits one attempt per bill version. +To let the payer try again, the service issues a new bill version and starts a +run for it. + ## Check and package From the repository root, use binaries built from this checkout: From 3411773c873b4e35f4fc099b881ee6978b5aaa4b Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Thu, 19 Nov 2026 22:58:09 +0000 Subject: [PATCH 29/40] fix(coordinator): point a held receipt-backed mutation to reconcile retry-same on a held payments.request-disbursement/v1 told the operator to inspect or cancel, although the operation offers a read-only original-request lookup. When the operation supports a read receipt, the refusal now names reconcile; unkeyed mutations and evaluations keep their advice. The mutation-uncertain problem detail covers both cases. Signed-off-by: Jeremi Joslin --- crates/registry-coordinator/src/problem.rs | 2 +- crates/registry-coordinator/src/store.rs | 43 +++++++++++++++++++--- docs/site/src/data/coordinator-api.yaml | 2 +- 3 files changed, 39 insertions(+), 8 deletions(-) diff --git a/crates/registry-coordinator/src/problem.rs b/crates/registry-coordinator/src/problem.rs index f80b25869b..6445dca2ff 100644 --- a/crates/registry-coordinator/src/problem.rs +++ b/crates/registry-coordinator/src/problem.rs @@ -411,7 +411,7 @@ impl ProblemCode { "The start input does not satisfy the workflow's declared input schema and value bounds." } Self::MutationUncertain => { - "An unkeyed mutation may have completed at its provider, so the run never sends it again." + "A mutation may have completed at its provider, so the run never sends it again. Reconcile it when its operation offers a read-only receipt lookup; otherwise inspect or cancel the run." } Self::OperationNotAuthorized => { "The caller's policy does not allow this operation." diff --git a/crates/registry-coordinator/src/store.rs b/crates/registry-coordinator/src/store.rs index 17c4ac7f45..143da455cb 100644 --- a/crates/registry-coordinator/src/store.rs +++ b/crates/registry-coordinator/src/store.rs @@ -664,6 +664,21 @@ fn refused(code: &'static str, message: &'static str) -> CoordinatorError { CoordinatorError::new(code, message) } +/// The refusal for `retry-same` on held work whose operation must never be +/// sent again after an unknown outcome, or `None` when a retry is allowed. +fn unknown_retry_refusal(operation: crate::protocol::Operation) -> Option { + if operation.can_retry_after_unknown() { + return None; + } + Some(if operation.is_evaluation() { + refused("evaluation-uncertain", "the evaluation may have completed remotely; preserve its original request and inspect or cancel the held run without reevaluating") + } else if operation.supports_read_receipt() { + refused("mutation-uncertain", "the mutation may have completed remotely; reconcile the held run through its read-only original-request lookup without replaying the effect") + } else { + refused("mutation-uncertain", "the unkeyed mutation may have completed remotely; preserve the held run and inspect or cancel it without replaying the effect") + }) +} + fn restore_held() -> CoordinatorError { refused("restore-hold", "execution is held until the prior deployment is externally fenced and recovery is reviewed") } @@ -2286,12 +2301,8 @@ impl Store { .map_err(|finding| Definition::run_refused(&finding, run, &status.workflow))?; if row.get::<_, bool>(3) { if let Some(Step::Call { call, .. }) = definition.workflow.steps.get(&status.step) { - if !call.operation.can_retry_after_unknown() { - return Err(if call.operation.is_evaluation() { - refused("evaluation-uncertain", "the evaluation may have completed remotely; preserve its original request and inspect or cancel the held run without reevaluating") - } else { - refused("mutation-uncertain", "the unkeyed mutation may have completed remotely; preserve the held run and inspect or cancel it without replaying the effect") - }); + if let Some(refusal) = unknown_retry_refusal(call.operation) { + return Err(refusal); } } } @@ -3520,6 +3531,26 @@ mod tests { use registry_platform_testing::MIGRATION_PIN_RULE; use sha2::{Digest, Sha256}; + #[test] + fn an_uncertain_mutation_with_a_read_receipt_is_sent_to_reconcile() { + use crate::protocol::Operation; + let held = unknown_retry_refusal(Operation::RequestDisbursement) + .expect("a held disbursement cannot replay its command"); + assert_eq!(held.code, "mutation-uncertain"); + assert!(held.message.contains("reconcile"), "{held:?}"); + assert!(!held.message.contains("inspect or cancel"), "{held:?}"); + let unkeyed = + unknown_retry_refusal(Operation::ReleaseHold).expect("an unkeyed release is held"); + assert!(unkeyed.message.contains("inspect or cancel"), "{unkeyed:?}"); + assert_eq!( + unknown_retry_refusal(Operation::EvaluateDecision) + .expect("an evaluation is held") + .code, + "evaluation-uncertain" + ); + assert!(unknown_retry_refusal(Operation::RecordProviderConfirmation).is_none()); + } + /// The protected state schema a version creates is fixed once a release /// ships it: existing databases are never altered, so an edit would give /// fresh installs a different shape at the same version. The digest covers diff --git a/docs/site/src/data/coordinator-api.yaml b/docs/site/src/data/coordinator-api.yaml index 25eab971a5..e7ded41629 100644 --- a/docs/site/src/data/coordinator-api.yaml +++ b/docs/site/src/data/coordinator-api.yaml @@ -23,7 +23,7 @@ - ['`idempotency.key-invalid`', '400', 'Supply an Idempotency-Key header of 1 to 256 bytes.'] - ['`idempotency.key-reused`', '409', 'This idempotency key already names a different workflow revision or input.'] - ['`input.invalid`', '400', 'The start input does not satisfy the workflow''s declared input schema and value bounds.'] - - ['`mutation.uncertain`', '409', 'An unkeyed mutation may have completed at its provider. Preserve the held run and inspect or cancel it without replaying the effect.'] + - ['`mutation.uncertain`', '409', 'A mutation may have completed at its provider, so the run never sends it again. Reconcile it when its operation offers a read-only receipt lookup, such as a disbursement request; otherwise inspect or cancel the held run.'] - ['`operation.not-authorized`', '403', 'The caller''s policy does not allow this operation.'] - ['`receipt.expired`', '409', 'The original command''s receipt can no longer be recovered. This is not evidence that the command was not sent.'] - ['`reconcile.raced`', '409', 'The run''s progress changed while it was being reconciled. Inspect it again.'] From c42873c349d67c752aae8335c00f4a435759a65c Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Thu, 19 Nov 2026 22:59:30 +0000 Subject: [PATCH 30/40] fix(adapter): audit accepted payment requests under their attempt The collection and disbursement request and request-receipt handlers audited a successful release with no attempt, stored as the nil UUID. Pass the accepted collection or disbursement id; refusals still carry none. Signed-off-by: Jeremi Joslin --- crates/registry-adapter/src/payments/http.rs | 63 +++++++++++++++++--- 1 file changed, 56 insertions(+), 7 deletions(-) diff --git a/crates/registry-adapter/src/payments/http.rs b/crates/registry-adapter/src/payments/http.rs index b30cce646d..10637c2b9a 100644 --- a/crates/registry-adapter/src/payments/http.rs +++ b/crates/registry-adapter/src/payments/http.rs @@ -28,9 +28,9 @@ use axum::{ }; use registry_adapter_core::AdapterRuntimeConfig; use registry_payment_protocol::{ - DisbursementAccepted, DisbursementState, DisbursementStatus, Money, PaymentProblem, - PaymentProblemCode as Error, ProviderConfirmation, RecordProviderConfirmation, RecordReceipt, - RequestCollection, RequestDisbursement, + CollectionAccepted, DisbursementAccepted, DisbursementState, DisbursementStatus, Money, + PaymentProblem, PaymentProblemCode as Error, ProviderConfirmation, RecordProviderConfirmation, + RecordReceipt, RequestCollection, RequestDisbursement, }; use registry_platform_config::{ RuntimeConfigLoader, RuntimeEnvelope, SecretProvider, SecretResolver, @@ -491,7 +491,7 @@ async fn request( &state, &caller, "request", - None, + audited_attempt(&result), true, StatusCode::ACCEPTED, result, @@ -516,7 +516,7 @@ async fn request_receipt( &state, &caller, "request-receipt", - None, + audited_attempt(&result), false, StatusCode::OK, result, @@ -714,7 +714,7 @@ async fn request_disbursement( &state, &caller, "request-disbursement", - None, + audited_attempt(&result), true, StatusCode::ACCEPTED, result, @@ -755,7 +755,7 @@ async fn disbursement_receipt( &state, &caller, "request-disbursement-receipt", - None, + audited_attempt(&result), false, StatusCode::OK, result, @@ -879,6 +879,24 @@ async fn finish( .map_err(HttpError) } +/// The attempt an accepted request names, recorded in its audit event. +trait AuditedAttempt { + fn attempt_id(&self) -> Uuid; +} +impl AuditedAttempt for CollectionAccepted { + fn attempt_id(&self) -> Uuid { + self.collection_id + } +} +impl AuditedAttempt for DisbursementAccepted { + fn attempt_id(&self) -> Uuid { + self.disbursement_id + } +} +fn audited_attempt(result: &Result) -> Option { + result.as_ref().ok().map(AuditedAttempt::attempt_id) +} + struct HttpError(Error); impl IntoResponse for HttpError { fn into_response(self) -> Response { @@ -920,6 +938,37 @@ fn refused(message: &str) -> ServeError { mod tests { use super::*; + #[test] + fn a_released_acceptance_is_audited_under_its_attempt() { + let collection = CollectionAccepted { + collection_id: Uuid::new_v4(), + bill_id: Uuid::new_v4(), + bill_version: 1, + binding_revision: "a".repeat(64), + simulation: true, + }; + let disbursement = DisbursementAccepted { + disbursement_id: Uuid::new_v4(), + instruction_record_id: Uuid::new_v4(), + instruction_id: Uuid::new_v4(), + instruction_version: 1, + binding_revision: "b".repeat(64), + simulation: false, + }; + assert_eq!( + audited_attempt(&Ok(collection.clone())), + Some(collection.collection_id) + ); + assert_eq!( + audited_attempt(&Ok(disbursement.clone())), + Some(disbursement.disbursement_id) + ); + assert_eq!( + audited_attempt::(&Err(Error::OutcomeUnknown)), + None + ); + } + #[test] fn startup_auth_match_is_exact_for_each_generic_payment_direction() { let pack = PaymentProviderPack::from_yaml( From 60c0d213d391b815b903b338c417555be6094691 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Thu, 19 Nov 2026 23:01:04 +0000 Subject: [PATCH 31/40] docs(payments): document disbursement routes and Mifos set-up List the four disbursement routes in the payment contract. Say the simulator upgrades v1 and v2 state to v3, and that its hosted page is a standalone aid the Adapter and Coordinator do not reach yet. Add one set-up paragraph to the Adapter configure page: Transit custody (a non-exportable service-created signer, an imported public verifier), the Payment Hub EE channel and operations apps shipping with authorisation off, and draining Bound attempts before raising min_encryption_version. Signed-off-by: Jeremi Joslin --- docs/site/src/content/docs/configure/adapter.mdx | 7 +++++++ .../adapter/examples/payment-collections/CONTRACT.md | 4 ++++ tools/payment-simulator/README.md | 12 +++++++----- 3 files changed, 18 insertions(+), 5 deletions(-) diff --git a/docs/site/src/content/docs/configure/adapter.mdx b/docs/site/src/content/docs/configure/adapter.mdx index 02acb632ff..4ece794937 100644 --- a/docs/site/src/content/docs/configure/adapter.mdx +++ b/docs/site/src/content/docs/configure/adapter.mdx @@ -1137,6 +1137,13 @@ adapter serve --runtime-config /absolute/path/runtime.yaml \ Registry Stack does not publish a Mifos Payment Hub EE pack yet, so the operator supplies a reviewed pack whose bytes match the pin. `adapterctl payments check` takes the same pack with `--provider-pack` and checks the pin offline. +Before a Mifos disbursement connection goes live, set up its signing and the provider's access control. +Create the request-signing key inside Transit, so it is non-exportable and service-created, and import only the provider's public key as the separate response-verification key; the Adapter pins each key's SPKI digest and version and refuses other custody. +The released Payment Hub EE channel and operations apps ship with authorisation turned off, so enable bearer authorisation on them, or enforce it at a trusted gateway, before the Adapter's Operations credential means anything. +An attempt reaches `Bound` before it is signed and sent, so let every `Bound` disbursement attempt dispatch before you raise the signing key's `min_encryption_version`; a raised minimum otherwise holds those attempts. +The [Mifos connector README](https://github.com/registrystack/registry-stack/blob/main/crates/registry-payment-mifos-connector/README.md) and the [platform crypto README](https://github.com/registrystack/registry-stack/blob/main/crates/registry-platform-crypto/README.md) carry the exact profile and Transit details. +Live signing through a real Transit engine is not verified yet, so do not let a live disbursement move real money until it is. + The separate confirmation operation accepts only a disbursement identifier. The Adapter reports verified provider completion through its restricted BReg Action, using the original instruction facts and a separately keyed exact command. The resulting confirmation records what the provider reported; credit to the recipient and settlement require separate authoritative evidence. diff --git a/products/adapter/examples/payment-collections/CONTRACT.md b/products/adapter/examples/payment-collections/CONTRACT.md index c9e4bd467c..53a3bfc756 100644 --- a/products/adapter/examples/payment-collections/CONTRACT.md +++ b/products/adapter/examples/payment-collections/CONTRACT.md @@ -26,6 +26,10 @@ amounts, provider outcomes, tenant/biller routing and Action names are refused. | Recovery lookup | `POST /collections/receipt` | Original request and key | 200 if acceptance is known; lookup never dispatches | | `payments.read-collection/v1` | `GET /collections/{collectionId}` | Collection identifier | 200 with exact identity, money and current validated state | | `payments.record-receipt/v1` | `POST /collections/{collectionId}/record-receipt` | Matching `collectionId`; `Idempotency-Key` header | 200 only after exact BReg receipt readback | +| `payments.request-disbursement/v1` | `POST /disbursements` | `instructionRecordId`, positive `instructionVersion`; `Idempotency-Key` header | 202, durable disbursement identity after provider acceptance; an uncertain send is held, never resent | +| Recovery lookup | `POST /disbursements/receipt` | Original request and key | 200 if acceptance is known; lookup never dispatches | +| `payments.read-disbursement/v1` | `GET /disbursements/{disbursementId}` | Disbursement identifier | 200 with exact identity, money and current validated provider observation | +| `payments.record-provider-confirmation/v1` | `POST /disbursements/{disbursementId}/record-provider-confirmation` | Matching `disbursementId`; `Idempotency-Key` header | 200 only after the provider confirmation is reported to the instruction registry | `adapterctl payments contract FILE` exports these routes and the generated wire schemas. `registry-payment-protocol` owns the DTOs and the bounded problem diff --git a/tools/payment-simulator/README.md b/tools/payment-simulator/README.md index 32363859ef..ec0f1f5872 100644 --- a/tools/payment-simulator/README.md +++ b/tools/payment-simulator/README.md @@ -163,8 +163,10 @@ mode, the existing `advance` command advances both G2P and P2G in two steps. ## Send a citizen to pay A citizen-facing front end can hand the citizen to a hosted page and get them -back. Start `serve` with the front end's return URL, then add `X-Return-URL` to -`POST /rtpRequest`: +back. The hosted page is a standalone aid for such a front end: the Adapter +payment host and Coordinator do not reach it yet. The Adapter creates requests +without `X-Return-URL` and polls them. Start `serve` with the front end's return +URL, then add `X-Return-URL` to `POST /rtpRequest`: ```sh uv run payment-simulator serve --database .state/payments.sqlite \ @@ -214,9 +216,9 @@ least 16 characters. Keep token and SQLite files in ignored `.state/`. Callbacks are accepted as configured wire fields but **are not delivered**. Use polling. Receipts are retained for the lifetime of this disposable database. There is no receipt expiry, reset API, real rail, production identity -provider, high availability or container publishing. An -unsupported database version is refused; only the additive v1-to-v2 upgrade is -provided. Programme funding and real citizen checkout are outside this mock. The hosted +provider, high availability or container publishing. `serve` +upgrades a v1 or v2 state file to v3 in place, additively; any other database +version is refused. Programme funding and real citizen checkout are outside this mock. The hosted page is a synthetic stand-in with no card or bank entry. Do not use real beneficiary data or expose this development server as a payment service. From a48990978c3f8c3aef90cc35969f861c3e6a142f Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Thu, 19 Nov 2026 23:02:01 +0000 Subject: [PATCH 32/40] fix(breg): limit the issuer to the bill fields issuance needs The service-issuer profile could read the payer identity, payer financial address, payment attempt, provider binding and reference, and digests. Issuance guards only the bill identity, tariff, amount, currency, simulation flag, payment state and receipt identifier; keep those and the issuance identifier. Signed-off-by: Jeremi Joslin --- products/breg/examples/payment-fee-issuance/registry.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/products/breg/examples/payment-fee-issuance/registry.yaml b/products/breg/examples/payment-fee-issuance/registry.yaml index ba14a8f818..69d6d39156 100644 --- a/products/breg/examples/payment-fee-issuance/registry.yaml +++ b/products/breg/examples/payment-fee-issuance/registry.yaml @@ -286,7 +286,7 @@ accessProfiles: records: - recordType: service-fee-bill operations: [get] - readableFields: [institution-id, service-id, request-id, payer-id, payer-financial-address, tariff-id, tariff-version, tariff-digest, bill-version, bill-digest, amount-minor, currency, currency-scale, simulation, payment-state, payment-attempt-id, provider-binding-revision, payment-receipt-id, provider-reference, receipt-digest, issuance-id] + readableFields: [institution-id, service-id, request-id, tariff-id, tariff-version, tariff-digest, bill-version, amount-minor, currency, currency-scale, simulation, payment-state, payment-receipt-id, issuance-id] rowBoundaries: unrestricted actions: - action: issue-paid-service From a5e86cb58703ad5d0045127259f0e98f212196b1 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Thu, 19 Nov 2026 23:07:20 +0000 Subject: [PATCH 33/40] chore: regenerate the identifier catalogue Carry the simulation-only payments schema digest and the revised mutation-uncertain problem detail. Signed-off-by: Jeremi Joslin --- .../identifiers/generated/catalog.v1.json | 96 +++++++++---------- 1 file changed, 48 insertions(+), 48 deletions(-) diff --git a/products/identifiers/generated/catalog.v1.json b/products/identifiers/generated/catalog.v1.json index b02edde10f..2c9340e6a7 100644 --- a/products/identifiers/generated/catalog.v1.json +++ b/products/identifiers/generated/catalog.v1.json @@ -1467,7 +1467,7 @@ "description": "Starts stay held after a restore until an operator releases the admission hold.", "source": { "path": "crates/registry-coordinator/src/problem.rs", - "sha256": "5dcf42811a37fccaa9cd975c4845c0b3c2d695a66db26fb58fd2a828b41d55e7" + "sha256": "b6fdc242c2c238e6831f070d28284ec937ff079617a8c486e033376745a2864a" }, "problem": { "code": "admission.held", @@ -1486,7 +1486,7 @@ "description": "This instance runs in recovery-only mode and admits no runs. Send starts to the ordinary service.", "source": { "path": "crates/registry-coordinator/src/problem.rs", - "sha256": "5dcf42811a37fccaa9cd975c4845c0b3c2d695a66db26fb58fd2a828b41d55e7" + "sha256": "b6fdc242c2c238e6831f070d28284ec937ff079617a8c486e033376745a2864a" }, "problem": { "code": "admission.recovery-only", @@ -1505,7 +1505,7 @@ "description": "The operation may have completed, but its audited result could not be released. Inspect the run before repeating the operation.", "source": { "path": "crates/registry-coordinator/src/problem.rs", - "sha256": "5dcf42811a37fccaa9cd975c4845c0b3c2d695a66db26fb58fd2a828b41d55e7" + "sha256": "b6fdc242c2c238e6831f070d28284ec937ff079617a8c486e033376745a2864a" }, "problem": { "code": "audit.response-unavailable", @@ -1524,7 +1524,7 @@ "description": "The bearer credential is missing, invalid, or expired.", "source": { "path": "crates/registry-coordinator/src/problem.rs", - "sha256": "5dcf42811a37fccaa9cd975c4845c0b3c2d695a66db26fb58fd2a828b41d55e7" + "sha256": "b6fdc242c2c238e6831f070d28284ec937ff079617a8c486e033376745a2864a" }, "problem": { "code": "authentication.refused", @@ -1543,7 +1543,7 @@ "description": "The run's original connection settings differ from this service's runtime configuration.", "source": { "path": "crates/registry-coordinator/src/problem.rs", - "sha256": "5dcf42811a37fccaa9cd975c4845c0b3c2d695a66db26fb58fd2a828b41d55e7" + "sha256": "b6fdc242c2c238e6831f070d28284ec937ff079617a8c486e033376745a2864a" }, "problem": { "code": "binding.conflict", @@ -1562,7 +1562,7 @@ "description": "Connection settings that runs in progress use differ from this service's runtime configuration.", "source": { "path": "crates/registry-coordinator/src/problem.rs", - "sha256": "5dcf42811a37fccaa9cd975c4845c0b3c2d695a66db26fb58fd2a828b41d55e7" + "sha256": "b6fdc242c2c238e6831f070d28284ec937ff079617a8c486e033376745a2864a" }, "problem": { "code": "binding.live-conflict", @@ -1581,7 +1581,7 @@ "description": "That step is not waiting.", "source": { "path": "crates/registry-coordinator/src/problem.rs", - "sha256": "5dcf42811a37fccaa9cd975c4845c0b3c2d695a66db26fb58fd2a828b41d55e7" + "sha256": "b6fdc242c2c238e6831f070d28284ec937ff079617a8c486e033376745a2864a" }, "problem": { "code": "check.not-waiting", @@ -1600,7 +1600,7 @@ "description": "The workflow's workflow definition, one of its mappings or one of its functions refused the request.", "source": { "path": "crates/registry-coordinator/src/problem.rs", - "sha256": "5dcf42811a37fccaa9cd975c4845c0b3c2d695a66db26fb58fd2a828b41d55e7" + "sha256": "b6fdc242c2c238e6831f070d28284ec937ff079617a8c486e033376745a2864a" }, "problem": { "code": "definition.refused", @@ -1619,7 +1619,7 @@ "description": "An apply changed the active packages after this service started. Restart it with the runtime file that apply used.", "source": { "path": "crates/registry-coordinator/src/problem.rs", - "sha256": "5dcf42811a37fccaa9cd975c4845c0b3c2d695a66db26fb58fd2a828b41d55e7" + "sha256": "b6fdc242c2c238e6831f070d28284ec937ff079617a8c486e033376745a2864a" }, "problem": { "code": "deployment.activation-changed", @@ -1638,7 +1638,7 @@ "description": "The deployment's activation, runtime configuration or state key custody check failed.", "source": { "path": "crates/registry-coordinator/src/problem.rs", - "sha256": "5dcf42811a37fccaa9cd975c4845c0b3c2d695a66db26fb58fd2a828b41d55e7" + "sha256": "b6fdc242c2c238e6831f070d28284ec937ff079617a8c486e033376745a2864a" }, "problem": { "code": "deployment.refused", @@ -1657,7 +1657,7 @@ "description": "An evaluation may have completed at its provider, so the run is never evaluated again.", "source": { "path": "crates/registry-coordinator/src/problem.rs", - "sha256": "5dcf42811a37fccaa9cd975c4845c0b3c2d695a66db26fb58fd2a828b41d55e7" + "sha256": "b6fdc242c2c238e6831f070d28284ec937ff079617a8c486e033376745a2864a" }, "problem": { "code": "evaluation.uncertain", @@ -1676,7 +1676,7 @@ "description": "The signed event must satisfy the accepted canonical envelope and typed event contract.", "source": { "path": "crates/registry-coordinator/src/problem.rs", - "sha256": "5dcf42811a37fccaa9cd975c4845c0b3c2d695a66db26fb58fd2a828b41d55e7" + "sha256": "b6fdc242c2c238e6831f070d28284ec937ff079617a8c486e033376745a2864a" }, "problem": { "code": "event.invalid", @@ -1695,7 +1695,7 @@ "description": "Restore the configured event source signing key and its enabled secret provider before retrying delivery.", "source": { "path": "crates/registry-coordinator/src/problem.rs", - "sha256": "5dcf42811a37fccaa9cd975c4845c0b3c2d695a66db26fb58fd2a828b41d55e7" + "sha256": "b6fdc242c2c238e6831f070d28284ec937ff079617a8c486e033376745a2864a" }, "problem": { "code": "event.source-unavailable", @@ -1714,7 +1714,7 @@ "description": "The signed event exceeds the event value profile: 131072 canonical bytes, 32 levels of nesting, 4096 values, 256 items per array, 256 members per object, and 16384 bytes per string. Have the producer project fewer or smaller fields into the event.", "source": { "path": "crates/registry-coordinator/src/problem.rs", - "sha256": "5dcf42811a37fccaa9cd975c4845c0b3c2d695a66db26fb58fd2a828b41d55e7" + "sha256": "b6fdc242c2c238e6831f070d28284ec937ff079617a8c486e033376745a2864a" }, "problem": { "code": "event.too-large", @@ -1733,7 +1733,7 @@ "description": "Send a fresh signed delivery from the exact configured source to its accepted trigger.", "source": { "path": "crates/registry-coordinator/src/problem.rs", - "sha256": "5dcf42811a37fccaa9cd975c4845c0b3c2d695a66db26fb58fd2a828b41d55e7" + "sha256": "b6fdc242c2c238e6831f070d28284ec937ff079617a8c486e033376745a2864a" }, "problem": { "code": "event.unauthenticated", @@ -1752,7 +1752,7 @@ "description": "Execution is under restore hold until an operator releases it.", "source": { "path": "crates/registry-coordinator/src/problem.rs", - "sha256": "5dcf42811a37fccaa9cd975c4845c0b3c2d695a66db26fb58fd2a828b41d55e7" + "sha256": "b6fdc242c2c238e6831f070d28284ec937ff079617a8c486e033376745a2864a" }, "problem": { "code": "execution.held", @@ -1771,7 +1771,7 @@ "description": "Supply an Idempotency-Key header of 1 to 256 bytes.", "source": { "path": "crates/registry-coordinator/src/problem.rs", - "sha256": "5dcf42811a37fccaa9cd975c4845c0b3c2d695a66db26fb58fd2a828b41d55e7" + "sha256": "b6fdc242c2c238e6831f070d28284ec937ff079617a8c486e033376745a2864a" }, "problem": { "code": "idempotency.key-invalid", @@ -1790,7 +1790,7 @@ "description": "This idempotency key already started a run with different input.", "source": { "path": "crates/registry-coordinator/src/problem.rs", - "sha256": "5dcf42811a37fccaa9cd975c4845c0b3c2d695a66db26fb58fd2a828b41d55e7" + "sha256": "b6fdc242c2c238e6831f070d28284ec937ff079617a8c486e033376745a2864a" }, "problem": { "code": "idempotency.key-reused", @@ -1809,7 +1809,7 @@ "description": "The start input does not satisfy the workflow's declared input schema and value bounds.", "source": { "path": "crates/registry-coordinator/src/problem.rs", - "sha256": "5dcf42811a37fccaa9cd975c4845c0b3c2d695a66db26fb58fd2a828b41d55e7" + "sha256": "b6fdc242c2c238e6831f070d28284ec937ff079617a8c486e033376745a2864a" }, "problem": { "code": "input.invalid", @@ -1825,10 +1825,10 @@ "compatibilityLine": "v1alpha1", "owner": "coordinator", "title": "Mutation outcome uncertain", - "description": "An unkeyed mutation may have completed at its provider, so the run never sends it again.", + "description": "A mutation may have completed at its provider, so the run never sends it again. Reconcile it when its operation offers a read-only receipt lookup; otherwise inspect or cancel the run.", "source": { "path": "crates/registry-coordinator/src/problem.rs", - "sha256": "5dcf42811a37fccaa9cd975c4845c0b3c2d695a66db26fb58fd2a828b41d55e7" + "sha256": "b6fdc242c2c238e6831f070d28284ec937ff079617a8c486e033376745a2864a" }, "problem": { "code": "mutation.uncertain", @@ -1847,7 +1847,7 @@ "description": "The caller's policy does not allow this operation.", "source": { "path": "crates/registry-coordinator/src/problem.rs", - "sha256": "5dcf42811a37fccaa9cd975c4845c0b3c2d695a66db26fb58fd2a828b41d55e7" + "sha256": "b6fdc242c2c238e6831f070d28284ec937ff079617a8c486e033376745a2864a" }, "problem": { "code": "operation.not-authorized", @@ -1866,7 +1866,7 @@ "description": "The original command's receipt can no longer be recovered. This is not evidence that the command was not sent.", "source": { "path": "crates/registry-coordinator/src/problem.rs", - "sha256": "5dcf42811a37fccaa9cd975c4845c0b3c2d695a66db26fb58fd2a828b41d55e7" + "sha256": "b6fdc242c2c238e6831f070d28284ec937ff079617a8c486e033376745a2864a" }, "problem": { "code": "receipt.expired", @@ -1885,7 +1885,7 @@ "description": "The run's progress changed while it was being reconciled. Inspect it again.", "source": { "path": "crates/registry-coordinator/src/problem.rs", - "sha256": "5dcf42811a37fccaa9cd975c4845c0b3c2d695a66db26fb58fd2a828b41d55e7" + "sha256": "b6fdc242c2c238e6831f070d28284ec937ff079617a8c486e033376745a2864a" }, "problem": { "code": "reconcile.raced", @@ -1904,7 +1904,7 @@ "description": "Reconcile applies only to a held mutation with a prepared command, its original binding and no active lease.", "source": { "path": "crates/registry-coordinator/src/problem.rs", - "sha256": "5dcf42811a37fccaa9cd975c4845c0b3c2d695a66db26fb58fd2a828b41d55e7" + "sha256": "b6fdc242c2c238e6831f070d28284ec937ff079617a8c486e033376745a2864a" }, "problem": { "code": "reconcile.refused", @@ -1923,7 +1923,7 @@ "description": "The held operation has no original-result lookup.", "source": { "path": "crates/registry-coordinator/src/problem.rs", - "sha256": "5dcf42811a37fccaa9cd975c4845c0b3c2d695a66db26fb58fd2a828b41d55e7" + "sha256": "b6fdc242c2c238e6831f070d28284ec937ff079617a8c486e033376745a2864a" }, "problem": { "code": "reconcile.unsupported", @@ -1942,7 +1942,7 @@ "description": "The request body exceeds the accepted size: 65536 bytes for a JSON request, or 1048576 bytes for a signed event delivery.", "source": { "path": "crates/registry-coordinator/src/problem.rs", - "sha256": "5dcf42811a37fccaa9cd975c4845c0b3c2d695a66db26fb58fd2a828b41d55e7" + "sha256": "b6fdc242c2c238e6831f070d28284ec937ff079617a8c486e033376745a2864a" }, "problem": { "code": "request.body-too-large", @@ -1961,7 +1961,7 @@ "description": "The request could not be read as a Coordinator request.", "source": { "path": "crates/registry-coordinator/src/problem.rs", - "sha256": "5dcf42811a37fccaa9cd975c4845c0b3c2d695a66db26fb58fd2a828b41d55e7" + "sha256": "b6fdc242c2c238e6831f070d28284ec937ff079617a8c486e033376745a2864a" }, "problem": { "code": "request.invalid", @@ -1980,7 +1980,7 @@ "description": "The list limit must be between 1 and 100.", "source": { "path": "crates/registry-coordinator/src/problem.rs", - "sha256": "5dcf42811a37fccaa9cd975c4845c0b3c2d695a66db26fb58fd2a828b41d55e7" + "sha256": "b6fdc242c2c238e6831f070d28284ec937ff079617a8c486e033376745a2864a" }, "problem": { "code": "request.limit-out-of-range", @@ -1999,7 +1999,7 @@ "description": "The route exists but not for this method.", "source": { "path": "crates/registry-coordinator/src/problem.rs", - "sha256": "5dcf42811a37fccaa9cd975c4845c0b3c2d695a66db26fb58fd2a828b41d55e7" + "sha256": "b6fdc242c2c238e6831f070d28284ec937ff079617a8c486e033376745a2864a" }, "problem": { "code": "request.method-not-allowed", @@ -2018,7 +2018,7 @@ "description": "The requested route does not exist.", "source": { "path": "crates/registry-coordinator/src/problem.rs", - "sha256": "5dcf42811a37fccaa9cd975c4845c0b3c2d695a66db26fb58fd2a828b41d55e7" + "sha256": "b6fdc242c2c238e6831f070d28284ec937ff079617a8c486e033376745a2864a" }, "problem": { "code": "request.not-found", @@ -2037,7 +2037,7 @@ "description": "The reason or recovery reference must be a bounded reference without personal data or control characters.", "source": { "path": "crates/registry-coordinator/src/problem.rs", - "sha256": "5dcf42811a37fccaa9cd975c4845c0b3c2d695a66db26fb58fd2a828b41d55e7" + "sha256": "b6fdc242c2c238e6831f070d28284ec937ff079617a8c486e033376745a2864a" }, "problem": { "code": "request.reason-invalid", @@ -2056,7 +2056,7 @@ "description": "The retention cutoff must be in the past and the limit between 1 and 100.", "source": { "path": "crates/registry-coordinator/src/problem.rs", - "sha256": "5dcf42811a37fccaa9cd975c4845c0b3c2d695a66db26fb58fd2a828b41d55e7" + "sha256": "b6fdc242c2c238e6831f070d28284ec937ff079617a8c486e033376745a2864a" }, "problem": { "code": "request.retention-invalid", @@ -2075,7 +2075,7 @@ "description": "The request body could not be processed.", "source": { "path": "crates/registry-coordinator/src/problem.rs", - "sha256": "5dcf42811a37fccaa9cd975c4845c0b3c2d695a66db26fb58fd2a828b41d55e7" + "sha256": "b6fdc242c2c238e6831f070d28284ec937ff079617a8c486e033376745a2864a" }, "problem": { "code": "request.unprocessable", @@ -2094,7 +2094,7 @@ "description": "The request body is not JSON.", "source": { "path": "crates/registry-coordinator/src/problem.rs", - "sha256": "5dcf42811a37fccaa9cd975c4845c0b3c2d695a66db26fb58fd2a828b41d55e7" + "sha256": "b6fdc242c2c238e6831f070d28284ec937ff079617a8c486e033376745a2864a" }, "problem": { "code": "request.unsupported-media-type", @@ -2113,7 +2113,7 @@ "description": "This recovery action requires execution to be under restore hold.", "source": { "path": "crates/registry-coordinator/src/problem.rs", - "sha256": "5dcf42811a37fccaa9cd975c4845c0b3c2d695a66db26fb58fd2a828b41d55e7" + "sha256": "b6fdc242c2c238e6831f070d28284ec937ff079617a8c486e033376745a2864a" }, "problem": { "code": "restore.hold-required", @@ -2132,7 +2132,7 @@ "description": "Held work no longer matches its protected definition or prepared command.", "source": { "path": "crates/registry-coordinator/src/problem.rs", - "sha256": "5dcf42811a37fccaa9cd975c4845c0b3c2d695a66db26fb58fd2a828b41d55e7" + "sha256": "b6fdc242c2c238e6831f070d28284ec937ff079617a8c486e033376745a2864a" }, "problem": { "code": "restore.lease-incompatible", @@ -2151,7 +2151,7 @@ "description": "Execution history must be complete and the prior deployment fenced before recovery is reviewed.", "source": { "path": "crates/registry-coordinator/src/problem.rs", - "sha256": "5dcf42811a37fccaa9cd975c4845c0b3c2d695a66db26fb58fd2a828b41d55e7" + "sha256": "b6fdc242c2c238e6831f070d28284ec937ff079617a8c486e033376745a2864a" }, "problem": { "code": "restore.review-required", @@ -2170,7 +2170,7 @@ "description": "Held work remains unresolved, so the restore hold cannot be released.", "source": { "path": "crates/registry-coordinator/src/problem.rs", - "sha256": "5dcf42811a37fccaa9cd975c4845c0b3c2d695a66db26fb58fd2a828b41d55e7" + "sha256": "b6fdc242c2c238e6831f070d28284ec937ff079617a8c486e033376745a2864a" }, "problem": { "code": "restore.unresolved", @@ -2189,7 +2189,7 @@ "description": "Retry-same applies only to held work before its original deadline.", "source": { "path": "crates/registry-coordinator/src/problem.rs", - "sha256": "5dcf42811a37fccaa9cd975c4845c0b3c2d695a66db26fb58fd2a828b41d55e7" + "sha256": "b6fdc242c2c238e6831f070d28284ec937ff079617a8c486e033376745a2864a" }, "problem": { "code": "retry.refused", @@ -2208,7 +2208,7 @@ "description": "This service's Coordinator version cannot interpret the run's pinned definition.", "source": { "path": "crates/registry-coordinator/src/problem.rs", - "sha256": "5dcf42811a37fccaa9cd975c4845c0b3c2d695a66db26fb58fd2a828b41d55e7" + "sha256": "b6fdc242c2c238e6831f070d28284ec937ff079617a8c486e033376745a2864a" }, "problem": { "code": "run.definition-incompatible", @@ -2227,7 +2227,7 @@ "description": "No run with this identifier is visible to the caller.", "source": { "path": "crates/registry-coordinator/src/problem.rs", - "sha256": "5dcf42811a37fccaa9cd975c4845c0b3c2d695a66db26fb58fd2a828b41d55e7" + "sha256": "b6fdc242c2c238e6831f070d28284ec937ff079617a8c486e033376745a2864a" }, "problem": { "code": "run.not-visible", @@ -2246,7 +2246,7 @@ "description": "Retention erased this run's payloads, so it can no longer be retried or reconciled.", "source": { "path": "crates/registry-coordinator/src/problem.rs", - "sha256": "5dcf42811a37fccaa9cd975c4845c0b3c2d695a66db26fb58fd2a828b41d55e7" + "sha256": "b6fdc242c2c238e6831f070d28284ec937ff079617a8c486e033376745a2864a" }, "problem": { "code": "run.payload-erased", @@ -2265,7 +2265,7 @@ "description": "Coordinator could not complete the request.", "source": { "path": "crates/registry-coordinator/src/problem.rs", - "sha256": "5dcf42811a37fccaa9cd975c4845c0b3c2d695a66db26fb58fd2a828b41d55e7" + "sha256": "b6fdc242c2c238e6831f070d28284ec937ff079617a8c486e033376745a2864a" }, "problem": { "code": "runtime.failure", @@ -2284,7 +2284,7 @@ "description": "A dependency of the Coordinator, such as its database, audit stream or token verifier, is unavailable. Try again after the service recovers.", "source": { "path": "crates/registry-coordinator/src/problem.rs", - "sha256": "5dcf42811a37fccaa9cd975c4845c0b3c2d695a66db26fb58fd2a828b41d55e7" + "sha256": "b6fdc242c2c238e6831f070d28284ec937ff079617a8c486e033376745a2864a" }, "problem": { "code": "service.unavailable", @@ -2303,7 +2303,7 @@ "description": "This deployment does not serve the named workflow.", "source": { "path": "crates/registry-coordinator/src/problem.rs", - "sha256": "5dcf42811a37fccaa9cd975c4845c0b3c2d695a66db26fb58fd2a828b41d55e7" + "sha256": "b6fdc242c2c238e6831f070d28284ec937ff079617a8c486e033376745a2864a" }, "problem": { "code": "workflow.not-served", @@ -2322,7 +2322,7 @@ "description": "The expected workflow revision differs from the active revision or the original admission.", "source": { "path": "crates/registry-coordinator/src/problem.rs", - "sha256": "5dcf42811a37fccaa9cd975c4845c0b3c2d695a66db26fb58fd2a828b41d55e7" + "sha256": "b6fdc242c2c238e6831f070d28284ec937ff079617a8c486e033376745a2864a" }, "problem": { "code": "workflow.revision-mismatch", @@ -4729,7 +4729,7 @@ }, "artifact": { "path": "products/adapter/schemas/payments.v1alpha1.schema.json", - "sha256": "230c16652707819427147a0772e4a2f490fba60ec43984e2392b496684bc458d", + "sha256": "573d4746769720f23b417674c77e1915c007baf502d88637cc0a38b75daaa205", "mediaType": "application/schema+json" } }, From 31c71ec1704426c866cfaf21bd58e215e3592da2 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Thu, 26 Nov 2026 20:58:32 +0100 Subject: [PATCH 34/40] chore(payments): sync artifacts with the 0.49 workspace Signed-off-by: Jeremi Joslin --- Cargo.lock | 8 ++++---- products/identifiers/generated/catalog.v1.json | 8 ++++---- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 34c80d5165..f6c815cd09 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -7696,7 +7696,7 @@ dependencies = [ [[package]] name = "registry-payment-client" -version = "0.46.1" +version = "0.49.0" dependencies = [ "axum", "registry-payment-protocol", @@ -7714,7 +7714,7 @@ dependencies = [ [[package]] name = "registry-payment-mifos-connector" -version = "0.46.1" +version = "0.49.0" dependencies = [ "registry-platform-crypto", "registry-platform-httputil", @@ -7731,7 +7731,7 @@ dependencies = [ [[package]] name = "registry-payment-protocol" -version = "0.46.1" +version = "0.49.0" dependencies = [ "jsonschema", "schemars", @@ -7743,7 +7743,7 @@ dependencies = [ [[package]] name = "registry-payment-simulator-connector" -version = "0.46.1" +version = "0.49.0" dependencies = [ "registry-payment-protocol", "registry-platform-httputil", diff --git a/products/identifiers/generated/catalog.v1.json b/products/identifiers/generated/catalog.v1.json index 2c9340e6a7..7a8f107615 100644 --- a/products/identifiers/generated/catalog.v1.json +++ b/products/identifiers/generated/catalog.v1.json @@ -5319,11 +5319,11 @@ "description": "Registry Coordinator portable project authoring JSON Schema.", "source": { "path": "crates/registry-coordinator/src/authoring.rs", - "sha256": "d9bc331b223ade980f9b54ff2b29eecd285108d468ab86f23d73ff47d443aa20" + "sha256": "1bb41563fd58ad1544df962d17d94172fe76c027128020095da08b5ba63ae733" }, "artifact": { "path": "products/coordinator/generated/project/project.schema.json", - "sha256": "be3682d24686b500e6421946dc2de94dd5aea293f1dd42fa447098ac71740204", + "sha256": "69e53bda51ef36c2540769d13af80eaa09f6768b44d8379b79fe0886c7a53555", "mediaType": "application/schema+json" } }, @@ -5337,11 +5337,11 @@ "description": "Registry Coordinator runtime configuration JSON Schema.", "source": { "path": "crates/registry-coordinator/src/runtime.rs", - "sha256": "a0424a3812eb8fbe1398214ab6ee15f888f9a92da21143ea08e0a9f1df3d47d1" + "sha256": "b819cb03b63fd52ba179f2ed4062c2c26ec1da3dd57278abe3819db21d6898ad" }, "artifact": { "path": "products/coordinator/generated/runtime/runtime.schema.json", - "sha256": "8752417782957e2be39377ce0932c23b1b9b5027a69a81585752805a66e18bdf", + "sha256": "6597f692f6eec4c68b186613eaae85ca5d99d8d87985a2653dafa7613f8596c6", "mediaType": "application/schema+json" } }, From 68c1a3f3e0e1f44f5bc96fe76f92499d7a32bafd Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Thu, 26 Nov 2026 21:11:34 +0100 Subject: [PATCH 35/40] test(payments): verify legacy signing with OpenBao Transit Signed-off-by: Jeremi Joslin --- .github/workflows/ci.yml | 2 + crates/registry-adapter/tests/g2p_provider.rs | 280 ++++++++++++++++++ products/adapter/scripts/check-contracts.sh | 5 + .../adapter/scripts/test-payments-openbao.sh | 266 +++++++++++++++++ 4 files changed, 553 insertions(+) create mode 100755 products/adapter/scripts/test-payments-openbao.sh diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index ac855b6ed8..dda895aa05 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1414,6 +1414,8 @@ jobs: env: CARGO_TARGET_DIR: ${{ github.workspace }}/target ADAPTER_CONTRACTS_CLEAN_BETWEEN_LANES: "1" + ADAPTER_TEST_OPENBAO_TRANSIT: ${{ needs.changes.outputs.full_sweep == 'true' || github.event_name == 'merge_group' || contains(github.event.pull_request.labels.*.name, 'ci:full') }} + OPENBAO_PULL: "true" run: products/adapter/scripts/check-contracts.sh - name: Registry Adapter facade recovery runner diff --git a/crates/registry-adapter/tests/g2p_provider.rs b/crates/registry-adapter/tests/g2p_provider.rs index 2fcf5ba87d..3707f80bdc 100644 --- a/crates/registry-adapter/tests/g2p_provider.rs +++ b/crates/registry-adapter/tests/g2p_provider.rs @@ -28,10 +28,13 @@ use registry_payment_mifos_connector::{legacy_signature_digest, LegacySignatureH use registry_platform_config::{SecretProvider, SecretResolver}; use registry_platform_yaml::SecretReference; use serde_json::{json, Value}; +use sha2::{Digest, Sha256}; use std::{ collections::BTreeMap, + io::Write, os::unix::fs::PermissionsExt, path::{Path, PathBuf}, + process::{Command, Stdio}, sync::{Arc, Mutex}, }; use tokio::{ @@ -250,6 +253,127 @@ struct LegacyHttpState { seen: Arc>>, } +#[derive(Clone)] +struct OpenBaoProviderState { + fixture: Arc, + request_public_key: PathBuf, + response_private_key: PathBuf, + seen: Arc>>, +} + +#[tokio::test] +#[ignore = "requires products/adapter/scripts/test-payments-openbao.sh"] +async fn real_openbao_transit_signs_requests_and_refuses_a_changed_response() { + let socket_path = required_openbao_path("REGISTRY_PAYMENTS_OPENBAO_SOCKET"); + let request_public_key = required_openbao_path("REGISTRY_PAYMENTS_OPENBAO_REQUEST_PUBLIC_KEY"); + let response_private_key = + required_openbao_path("REGISTRY_PAYMENTS_OPENBAO_RESPONSE_PRIVATE_KEY"); + let response_public_key = + required_openbao_path("REGISTRY_PAYMENTS_OPENBAO_RESPONSE_PUBLIC_KEY"); + let fixture = Arc::new(legacy_fixture()); + let seen = Arc::new(Mutex::new(Vec::new())); + let router = Router::new() + .route("/openbao/submit", post(openbao_valid)) + .route("/openbao/changed", post(openbao_changed_body)) + .with_state(OpenBaoProviderState { + fixture: fixture.clone(), + request_public_key: request_public_key.clone(), + response_private_key, + seen: seen.clone(), + }); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let origin = format!("http://{}/", listener.local_addr().unwrap()); + let http_server = tokio::spawn(async move { + axum::serve(listener, router).await.unwrap(); + }); + + let secret_directory = tempfile::tempdir().unwrap(); + write_secret( + secret_directory.path().join("operations-token"), + b"test-only-operations-bearer", + ); + let resolver = + Arc::new(SecretResolver::new([SecretProvider::File], secret_directory.path()).unwrap()); + let provider_binding = binding( + &origin, + G2pHttpAuth::MifosLegacySignature { + tenant: fixture_text(&fixture, "tenant").to_owned(), + signing_key_identity: "transit:mifos-request:v1".to_owned(), + signing_key: Box::new(openbao_transit_key( + &socket_path, + "mifos-request", + &request_public_key, + )), + response_key_identity: "transit:mifos-response:v1".to_owned(), + response_key: Box::new(openbao_transit_key( + &socket_path, + "mifos-response", + &response_public_key, + )), + operations_credential_identity: "mifos-operations-client".to_owned(), + operations_credential_ref: SecretReference::new("secret:file/operations-token") + .unwrap(), + }, + ); + let provider = HttpG2pProvider::initialize(resolver, std::slice::from_ref(&provider_binding)) + .await + .expect("real OpenBao Transit keys satisfy the pinned custody contract"); + let pack = pin(); + let intent = snapshot(provider_binding.clone(), pack.clone()) + .provider_intent(&instruction()) + .unwrap(); + let exact_body = registry_platform_canonical_json::canonicalize_json(&json!({ + "requestId": "batch-request-1", + "correlationId": intent.correlation_id, + "amount": "1000.00" + })) + .unwrap(); + + let valid = legacy_request( + pack.clone(), + PaymentEndpointRole::DisbursementSubmit, + PaymentHttpMethod::Post, + "/openbao/submit", + Some(exact_body.clone()), + ); + let response = provider + .preflight_submit(&provider_binding, &intent, &valid) + .await + .unwrap() + .send() + .await + .unwrap(); + assert_eq!(response.status, StatusCode::ACCEPTED.as_u16()); + assert_eq!(response.body, fixture_text(&fixture, "body").as_bytes()); + + let changed = legacy_request( + pack, + PaymentEndpointRole::DisbursementSubmit, + PaymentHttpMethod::Post, + "/openbao/changed", + Some(exact_body), + ); + let prepared = provider + .preflight_submit(&provider_binding, &intent, &changed) + .await + .unwrap(); + assert!(matches!( + prepared.send().await, + Err(G2pProviderError::OutcomeUnknown) + )); + + let requests = seen.lock().unwrap(); + assert_eq!(requests.len(), 2); + assert!(requests.iter().all(|request| { + request.tenant.as_deref() == Some("pilot") + && request.correlation_id.as_deref() == Some(intent.correlation_id.as_str()) + && request.signature.is_some() + && request.authorization.is_none() + })); + drop(requests); + http_server.abort(); +} + #[tokio::test] async fn mifos_legacy_signature_host_signs_exact_requests_and_verifies_before_mapping() { let fixture = Arc::new(legacy_fixture()); @@ -522,6 +646,124 @@ async fn capture_uncertain( vec![b'x'; 131_073] } +async fn openbao_valid( + State(state): State, + uri: Uri, + headers: HeaderMap, + body: Bytes, +) -> Response { + openbao_response(state, uri, headers, body, false) +} + +async fn openbao_changed_body( + State(state): State, + uri: Uri, + headers: HeaderMap, + body: Bytes, +) -> Response { + openbao_response(state, uri, headers, body, true) +} + +fn openbao_response( + state: OpenBaoProviderState, + uri: Uri, + headers: HeaderMap, + body: Bytes, + change_body_after_signing: bool, +) -> Response { + verify_openbao_request(&state.request_public_key, &headers, &body); + capture(&state.seen, "POST", uri, headers, body); + + let signed_body = fixture_text(&state.fixture, "body"); + let digest = legacy_signature_digest(LegacySignatureHeaders::empty(), signed_body.as_bytes()) + .expect("synthetic response digest"); + let signature = openssl_raw_rsa_sign(&state.response_private_key, digest.as_bytes()); + let response_body = if change_body_after_signing { + fixture_text(&state.fixture, "changedBody") + } else { + signed_body + }; + let encoded_signature = STANDARD.encode(signature); + legacy_response( + StatusCode::ACCEPTED, + response_body, + &[fixture_text(&state.fixture, "tenant")], + &[encoded_signature.as_str()], + ) +} + +fn verify_openbao_request(public_key: &Path, headers: &HeaderMap, body: &[u8]) { + let correlation_id = headers + .get("X-CorrelationID") + .and_then(|value| value.to_str().ok()) + .expect("signed request correlation ID"); + let tenant = headers + .get("Platform-TenantId") + .and_then(|value| value.to_str().ok()) + .expect("signed request tenant"); + let signature = headers + .get("X-SIGNATURE") + .and_then(|value| value.to_str().ok()) + .and_then(|value| STANDARD.decode(value).ok()) + .expect("canonical base64 request signature"); + let digest = legacy_signature_digest( + LegacySignatureHeaders::bulk_request(correlation_id, tenant), + body, + ) + .expect("synthetic request digest"); + assert_eq!( + openssl_raw_rsa_recover(public_key, &signature), + digest.as_bytes(), + "the independent provider double must verify the exact Adapter request" + ); +} + +fn openssl_raw_rsa_sign(private_key: &Path, input: &[u8]) -> Vec { + openssl_pkeyutl( + &["-sign", "-inkey"], + private_key, + &["-pkeyopt", "rsa_padding_mode:pkcs1"], + input, + ) +} + +fn openssl_raw_rsa_recover(public_key: &Path, signature: &[u8]) -> Vec { + openssl_pkeyutl( + &["-verifyrecover", "-pubin", "-inkey"], + public_key, + &["-pkeyopt", "rsa_padding_mode:pkcs1"], + signature, + ) +} + +fn openssl_pkeyutl(before_key: &[&str], key: &Path, after_key: &[&str], input: &[u8]) -> Vec { + let mut command = Command::new("openssl"); + command + .arg("pkeyutl") + .args(before_key) + .arg(key) + .args(after_key); + let mut child = command + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .expect("openssl pkeyutl is installed"); + child + .stdin + .take() + .expect("openssl stdin") + .write_all(input) + .expect("write bounded synthetic signing input"); + let output = child.wait_with_output().expect("wait for openssl pkeyutl"); + assert!( + output.status.success(), + "openssl pkeyutl failed: {}", + String::from_utf8_lossy(&output.stderr) + ); + output.stdout +} + async fn legacy_valid( State(state): State, uri: Uri, @@ -758,6 +1000,44 @@ fn released_transit_key( .unwrap() } +fn required_openbao_path(name: &str) -> PathBuf { + let path = std::env::var_os(name).unwrap_or_else(|| panic!("{name} must be set by the runner")); + let path = PathBuf::from(path); + assert!(path.is_absolute(), "{name} must be an absolute path"); + path +} + +fn openbao_transit_key( + socket_path: &Path, + key: &str, + public_key: &Path, +) -> G2pTransitRsaNoOidKeyBinding { + let output = Command::new("openssl") + .args(["pkey", "-pubin", "-in"]) + .arg(public_key) + .args(["-outform", "DER"]) + .output() + .expect("openssl pkey is installed"); + assert!( + output.status.success(), + "openssl pkey failed: {}", + String::from_utf8_lossy(&output.stderr) + ); + let digest = Sha256::digest(&output.stdout) + .iter() + .map(|byte| format!("{byte:02x}")) + .collect::(); + serde_json::from_value(json!({ + "socketPath": socket_path, + "mount": "transit", + "key": key, + "version": 1, + "publicKeyDigest": format!("sha256:{digest}"), + "attemptTimeoutMilliseconds": 5000 + })) + .unwrap() +} + fn public_key_pem(encoded: &str) -> String { let mut pem = String::from("-----BEGIN PUBLIC KEY-----\n"); for line in encoded.as_bytes().chunks(64) { diff --git a/products/adapter/scripts/check-contracts.sh b/products/adapter/scripts/check-contracts.sh index 04bc95fc7e..41714250ad 100755 --- a/products/adapter/scripts/check-contracts.sh +++ b/products/adapter/scripts/check-contracts.sh @@ -56,6 +56,11 @@ PATH="$HOME/.cargo/bin:$PATH" cargo test -p registry-adapterctl --locked --featu clear_completed_adapter_lane PATH="$HOME/.cargo/bin:$PATH" cargo clippy --locked -p registry-adapter -p registry-adapter-engine --all-targets -- -D warnings PATH="$HOME/.cargo/bin:$PATH" cargo test --locked -p registry-adapter -p registry-adapter-engine +# The full CI lane proves the legacy payment signature against a real local +# Transit and its token-injecting Unix proxy before this target is cleared. +if [[ "${ADAPTER_TEST_OPENBAO_TRANSIT:-false}" == true ]]; then + products/adapter/scripts/test-payments-openbao.sh +fi clear_completed_adapter_lane PATH="$HOME/.cargo/bin:$PATH" cargo clippy --locked -p registry-adapter -p registry-adapter-engine --features registry-adapter/job-file,registry-adapter-engine/job-file --all-targets -- -D warnings PATH="$HOME/.cargo/bin:$PATH" cargo test --locked -p registry-adapter -p registry-adapter-engine --features registry-adapter/job-file,registry-adapter-engine/job-file diff --git a/products/adapter/scripts/test-payments-openbao.sh b/products/adapter/scripts/test-payments-openbao.sh new file mode 100755 index 0000000000..c0dc0fcde9 --- /dev/null +++ b/products/adapter/scripts/test-payments-openbao.sh @@ -0,0 +1,266 @@ +#!/usr/bin/env bash +set -euo pipefail + +readonly default_openbao_image='ghcr.io/openbao/openbao:2.6.5@sha256:09f1eaaee351c329d75a5a89654d6e1ad4792998650c3cbf0c3513a76d9d9b6e' +readonly openbao_image="${OPENBAO_IMAGE:-$default_openbao_image}" + +if [[ ! "$openbao_image" =~ @sha256:[[:xdigit:]]{64}$ ]]; then + printf 'OPENBAO_IMAGE must be pinned by repository digest\n' >&2 + exit 2 +fi +if [[ "${OPENBAO_PREFLIGHT_ONLY:-false}" != true ]] && + [[ -z "${CARGO_TARGET_DIR:-}" || "$CARGO_TARGET_DIR" != /* ]]; then + printf 'CARGO_TARGET_DIR must be an absolute path outside the worktree\n' >&2 + exit 2 +fi +for command in curl docker jq openssl; do + if ! command -v "$command" >/dev/null 2>&1; then + printf 'required command is unavailable: %s\n' "$command" >&2 + exit 2 + fi +done +if [[ "${OPENBAO_PREFLIGHT_ONLY:-false}" != true ]] && ! command -v cargo >/dev/null 2>&1; then + printf 'required command is unavailable: cargo\n' >&2 + exit 2 +fi +if ! docker image inspect "$openbao_image" >/dev/null 2>&1; then + if [[ "${OPENBAO_PULL:-false}" != true ]]; then + printf 'pinned OpenBao image is not local; rerun with OPENBAO_PULL=true: %s\n' "$openbao_image" >&2 + exit 2 + fi + docker pull "$openbao_image" >/dev/null +fi + +script_directory="$(dirname -- "$(realpath "${BASH_SOURCE[0]}")")" +readonly script_directory +repository_root="$(git --no-optional-locks -C "$script_directory" rev-parse --show-toplevel)" +readonly repository_root +scratch="$(mktemp -d "${TMPDIR:-/tmp}/registry-payments-openbao.XXXXXX")" +readonly scratch +chmod 0700 "$scratch" +host_uid="$(id -u)" +readonly host_uid +host_gid="$(id -g)" +readonly host_gid +suffix="$(basename "$scratch" | tr -cd '[:alnum:]')" +readonly suffix +readonly server_name="registry-payments-openbao-server-$suffix" +readonly proxy_name="registry-payments-openbao-proxy-$suffix" +server_started=false +proxy_started=false + +cleanup() { + local status=$? + trap - EXIT INT TERM + if [[ "$proxy_started" == true ]]; then + docker container rm --force "$proxy_name" >/dev/null 2>&1 || true + fi + if [[ "$server_started" == true ]]; then + docker container rm --force "$server_name" >/dev/null 2>&1 || true + fi + rm -r "$scratch" + exit "$status" +} +trap cleanup EXIT +trap 'exit 130' INT +trap 'exit 143' TERM +umask 077 + +openssl genpkey -algorithm RSA -pkeyopt rsa_keygen_bits:2048 \ + -out "$scratch/response-private.pem" >/dev/null 2>&1 +openssl pkey -in "$scratch/response-private.pem" -pubout \ + -out "$scratch/response-public.pem" >/dev/null 2>&1 + +cat >"$scratch/adapter-payments.hcl" <<'POLICY' +path "transit/keys/mifos-request" { + capabilities = ["read"] +} +path "transit/sign/mifos-request/none" { + capabilities = ["update"] +} +path "transit/verify/mifos-request/none" { + capabilities = ["update"] +} +path "transit/keys/mifos-response" { + capabilities = ["read"] +} +path "transit/verify/mifos-response/none" { + capabilities = ["update"] +} +POLICY + +root_token="$(openssl rand -hex 32)" +readonly root_token +BAO_DEV_ROOT_TOKEN_ID="$root_token" docker run --detach --rm --pull=never \ + --name "$server_name" \ + --network none \ + --log-driver none \ + --user "$host_uid:$host_gid" \ + --cap-drop ALL \ + --env BAO_DEV_ROOT_TOKEN_ID \ + --env BAO_DEV_LISTEN_ADDRESS=127.0.0.1:8200 \ + --volume "$scratch:/fixtures" \ + "$openbao_image" server -dev -dev-no-store-token >/dev/null +server_started=true + +openbao() { + BAO_TOKEN="$root_token" docker exec \ + --env BAO_ADDR=http://127.0.0.1:8200 \ + --env BAO_TOKEN \ + "$server_name" bao "$@" +} + +ready=false +for _ in {1..50}; do + if openbao status >/dev/null 2>&1; then + ready=true + break + fi + sleep 0.1 +done +if [[ "$ready" != true ]]; then + printf 'OpenBao development server did not become ready\n' >&2 + exit 1 +fi + +cat >"$scratch/proxy.hcl" <<'CONFIG' +auto_auth { + method "token_file" { + config = { + token_file_path = "/fixtures/proxy-token" + } + } + sink "file" { + config = { + path = "/fixtures/proxy-sink-token" + } + } +} + +api_proxy { + use_auto_auth_token = "force" +} + +listener "unix" { + address = "/fixtures/transit.sock" + socket_mode = "0600" + require_request_header = true +} + +listener "tcp" { + address = "127.0.0.1:8300" + tls_disable = true + require_request_header = true +} + +vault { + address = "http://127.0.0.1:8200" +} +CONFIG + +openbao secrets enable -path=transit transit >/dev/null +openbao write transit/keys/mifos-request \ + type=rsa-2048 exportable=false allow_plaintext_backup=false >/dev/null +openbao write transit/keys/mifos-response/import \ + type=rsa-2048 public_key=@/fixtures/response-public.pem >/dev/null +openbao read -format=json transit/keys/mifos-request | + jq -er '.data.keys["1"].public_key' >"$scratch/request-public.pem" +openbao policy write adapter-payments /fixtures/adapter-payments.hcl >/dev/null +openbao token create -format=json -orphan -policy=adapter-payments -ttl=15m | + jq -er '.auth.client_token' >"$scratch/proxy-token" + +docker run --detach --rm --pull=never \ + --name "$proxy_name" \ + --network "container:$server_name" \ + --log-driver none \ + --user "$host_uid:$host_gid" \ + --cap-drop ALL \ + --volume "$scratch:/fixtures" \ + "$openbao_image" proxy -config=/fixtures/proxy.hcl -log-level=warn >/dev/null +proxy_started=true + +proxy_tcp_read() { + docker exec "$server_name" wget -qO- \ + --header='X-Vault-Request: true' \ + "http://127.0.0.1:8300/v1/transit/keys/$1" +} + +ready=false +for _ in {1..50}; do + if request_metadata="$(proxy_tcp_read mifos-request 2>/dev/null)"; then + ready=true + break + fi + sleep 0.1 +done +if [[ "$ready" != true ]]; then + printf 'OpenBao Proxy did not serve request-key metadata\n' >&2 + exit 1 +fi +if [[ ! -S "$scratch/transit.sock" ]]; then + printf 'OpenBao Proxy did not create its Unix socket\n' >&2 + exit 1 +fi + +host_unix_socket=true +if unix_request_metadata="$(curl --fail --silent \ + --unix-socket "$scratch/transit.sock" \ + --header 'X-Vault-Request: true' \ + http://localhost/v1/transit/keys/mifos-request 2>/dev/null)"; then + request_metadata="$unix_request_metadata" + if ! response_metadata="$(curl --fail --silent \ + --unix-socket "$scratch/transit.sock" \ + --header 'X-Vault-Request: true' \ + http://localhost/v1/transit/keys/mifos-response 2>/dev/null)"; then + printf 'OpenBao Proxy Unix listener did not serve response-key metadata\n' >&2 + exit 1 + fi +else + host_unix_socket=false + if ! response_metadata="$(proxy_tcp_read mifos-response 2>/dev/null)"; then + printf 'OpenBao Proxy did not serve response-key metadata\n' >&2 + exit 1 + fi +fi +jq -e '.data.imported_key == false + and .data.derived == false + and .data.exportable == false + and .data.allow_plaintext_backup == false + and .data.supports_signing == true + and .data.type == "rsa-2048" + and .data.keys["1"].public_key != null' \ + <<<"$request_metadata" >/dev/null +jq -e '.data.imported_key == true + and .data.derived == false + and .data.exportable == false + and .data.allow_plaintext_backup == false + and .data.supports_signing == true + and .data.type == "rsa-2048" + and .data.keys["1"].public_key != null' \ + <<<"$response_metadata" >/dev/null + +if [[ "${OPENBAO_PREFLIGHT_ONLY:-false}" == true ]]; then + if [[ "$host_unix_socket" == true ]]; then + printf 'real OpenBao Transit and Unix Proxy preflight passed\n' + else + printf 'real OpenBao Transit and Proxy preflight passed; host Unix sockets require Linux\n' + fi + exit 0 +fi +if [[ "$host_unix_socket" != true ]]; then + printf 'the Rust integration test requires Linux for a bind-mounted container Unix socket\n' >&2 + exit 1 +fi + +REGISTRY_PAYMENTS_OPENBAO_SOCKET="$scratch/transit.sock" \ + REGISTRY_PAYMENTS_OPENBAO_REQUEST_PUBLIC_KEY="$scratch/request-public.pem" \ + REGISTRY_PAYMENTS_OPENBAO_RESPONSE_PRIVATE_KEY="$scratch/response-private.pem" \ + REGISTRY_PAYMENTS_OPENBAO_RESPONSE_PUBLIC_KEY="$scratch/response-public.pem" \ + CARGO_INCREMENTAL=0 \ + CARGO_PROFILE_DEV_DEBUG=0 \ + CARGO_PROFILE_TEST_DEBUG=0 \ + PATH="$HOME/.cargo/bin:$PATH" \ + cargo test --locked --manifest-path "$repository_root/Cargo.toml" \ + -p registry-adapter --test g2p_provider \ + real_openbao_transit_signs_requests_and_refuses_a_changed_response \ + -- --exact --ignored From ca05ea8d7b1080a8526b41d5ccc8a6f203b56b25 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Thu, 26 Nov 2026 21:21:22 +0100 Subject: [PATCH 36/40] docs(payments): distinguish signing tests from sandbox acceptance Signed-off-by: Jeremi Joslin --- docs/site/src/content/docs/configure/adapter.mdx | 6 +++++- products/adapter/CHANGELOG.md | 8 ++++---- products/adapter/README.md | 6 +++--- .../examples/payment-collections/README.md | 15 ++++++++------- 4 files changed, 20 insertions(+), 15 deletions(-) diff --git a/docs/site/src/content/docs/configure/adapter.mdx b/docs/site/src/content/docs/configure/adapter.mdx index 4ece794937..29d445fb14 100644 --- a/docs/site/src/content/docs/configure/adapter.mdx +++ b/docs/site/src/content/docs/configure/adapter.mdx @@ -1142,7 +1142,9 @@ Create the request-signing key inside Transit, so it is non-exportable and servi The released Payment Hub EE channel and operations apps ship with authorisation turned off, so enable bearer authorisation on them, or enforce it at a trusted gateway, before the Adapter's Operations credential means anything. An attempt reaches `Bound` before it is signed and sent, so let every `Bound` disbursement attempt dispatch before you raise the signing key's `min_encryption_version`; a raised minimum otherwise holds those attempts. The [Mifos connector README](https://github.com/registrystack/registry-stack/blob/main/crates/registry-payment-mifos-connector/README.md) and the [platform crypto README](https://github.com/registrystack/registry-stack/blob/main/crates/registry-platform-crypto/README.md) carry the exact profile and Transit details. -Live signing through a real Transit engine is not verified yet, so do not let a live disbursement move real money until it is. +Full Linux CI exercises the signing and acknowledgement checks with OpenBao Transit over its Unix proxy. +The test uses a synthetic provider. +Run a sandbox disbursement with your pinned Mifos deployment and its configured Transit proxy before enabling live transfers. The separate confirmation operation accepts only a disbursement identifier. The Adapter reports verified provider completion through its restricted BReg Action, using the original instruction facts and a separately keyed exact command. @@ -1166,6 +1168,8 @@ Payment audit events carry no values and commit before an effect or a response i crates/registry-adapter/tests/payment_config.rs live_mifos_collections_are_refused_as_simulation_only; crates/registry-adapter/src/payments/service.rs; crates/registry-adapter/src/payments/g2p_model.rs mifos-legacy-signature; + crates/registry-adapter/tests/g2p_provider.rs real_openbao_transit_signs_requests_and_refuses_a_changed_response; + products/adapter/scripts/test-payments-openbao.sh; crates/registry-adapter/tests/payment_service.rs; crates/registry-adapter/tests/payment_store.rs; products/adapter/scripts/check_dependency_direction.py. */} diff --git a/products/adapter/CHANGELOG.md b/products/adapter/CHANGELOG.md index f972bca507..8f56d8b73d 100644 --- a/products/adapter/CHANGELOG.md +++ b/products/adapter/CHANGELOG.md @@ -124,10 +124,10 @@ `--payment-provider-pack`, and authenticate with `bearer` or, for Mifos Payment Hub EE, `mifos-legacy-signature`, which signs the exact Bulk request through a pinned Transit key and reads Operations status under a separate - bearer credential. Live Mifos signing through a real Transit engine is not - verified yet; do not let a live disbursement move real money until that - verification lands. A provider confirmation is not proof of beneficiary - credit or settlement. + bearer credential. Full Linux CI exercises the signature with OpenBao and + a synthetic provider. Verify your deployed provider pack and Mifos route + in a sandbox before moving money. Verify beneficiary credit and settlement + separately. - `adapterctl payments check` validates connections offline and `adapterctl payments contract` exports their typed HTTP contract. Generated schemas, a native Coordinator workflow, the restricted BReg fee fixture, diff --git a/products/adapter/README.md b/products/adapter/README.md index 223907d504..32f746f71d 100644 --- a/products/adapter/README.md +++ b/products/adapter/README.md @@ -33,9 +33,9 @@ Operations completion does not authorize a paid fee-bill receipt. The Transit Unix socket must be an absolute local path protected by deployment ACLs and a trusted proxy policy. Adapter pins the mount, key name, version and -SPKI SHA-256 digest for separate signing and response-verification keys. The -repository's fake Transit regression checks the wire contract, but does not -establish live OpenBao `/none` plus `prehashed` interoperability. +SPKI SHA-256 digest for separate signing and response-verification keys. +Full Linux CI exercises `/none` with `prehashed: true` through OpenBao Transit +and its Unix proxy. The test uses a synthetic provider. For a provider pack upgrade, repeat `--payment-provider-pack` with the current pack and every retained pack still needed by an unfinished attempt. The host diff --git a/products/adapter/examples/payment-collections/README.md b/products/adapter/examples/payment-collections/README.md index 23f49a53f5..44997d8403 100644 --- a/products/adapter/examples/payment-collections/README.md +++ b/products/adapter/examples/payment-collections/README.md @@ -64,8 +64,9 @@ Replace the example Transit SPKI digests, key versions, key names, socket path, origins and secret references with deployment-owned values. The socket must be an absolute local Unix socket protected by ACLs and a trusted proxy policy. The host validates the pinned key metadata at startup and never receives -private key bytes. Repository tests use a fake Transit endpoint and do not -establish live OpenBao `/none` plus `prehashed` interoperability. +private key bytes. The Linux signing test uses OpenBao Transit over its +Unix proxy. A synthetic provider checks request signatures and supplies +signed acknowledgements. Build matching `adapter` and `adapterctl` binaries from this checkout, using the repository's external Cargo target directory. Check the configuration @@ -159,11 +160,11 @@ connection/service scope. This slice permits one attempt per bill version, including after a definitive failure. There is no replacement-attempt operation, refund, settlement, callback handler or live collection provider. Disbursements can bind a live -provider pack, but live Mifos signing through a real Transit engine is not -verified yet: do not let a live disbursement move real money until that -verification lands. Attempts and command receipts -have no automatic expiry; they contain restricted bill/payer facts needed for -recovery and require protected database storage and backup. Generic facade +provider pack. Before you enable live transfers, use your pinned provider +pack to run a sandbox disbursement with Mifos and its Transit proxy. +Attempts and command receipts have no automatic expiry. They contain +restricted bill and payer facts needed for recovery. Protect their PostgreSQL +storage and backups. Generic facade retention does not erase these records. The focused `payment_service` PostgreSQL tests exercise recovery using From cebcf12763113e144cb93aec9eccdb7a1d9c74d7 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Thu, 26 Nov 2026 21:52:40 +0100 Subject: [PATCH 37/40] fix(payments): update native acceptance for Registry Stack 0.49 Signed-off-by: Jeremi Joslin --- .../tests/refactor_cli_contract.rs | 17 +++++++++++++ .../adapter/scripts/test-payment-native.mjs | 4 ++-- .../examples/g2p-disbursement/registry.yaml | 18 +++++++------- .../payment-fee-issuance/registry.yaml | 24 +++++++++---------- .../payment-fee-issuance/run-native.sh | 2 +- 5 files changed, 41 insertions(+), 24 deletions(-) diff --git a/crates/registry-bregctl/tests/refactor_cli_contract.rs b/crates/registry-bregctl/tests/refactor_cli_contract.rs index 8b253738d9..dbffa11b9b 100644 --- a/crates/registry-bregctl/tests/refactor_cli_contract.rs +++ b/crates/registry-bregctl/tests/refactor_cli_contract.rs @@ -104,6 +104,23 @@ fn compiled() -> registry_breg::CompiledRegistry { ) .unwrap() } + +#[test] +fn payment_examples_pass_authoring_checks() { + for name in ["payment-fee-issuance", "g2p-disbursement"] { + let project = root().join("products/breg/examples").join(name); + let output = run(&["--format", "json", "check", project.to_str().unwrap()]); + assert!( + output.status.success(), + "{name}: {}\n{}", + String::from_utf8_lossy(&output.stdout), + String::from_utf8_lossy(&output.stderr) + ); + let report: Value = serde_json::from_slice(&output.stdout).unwrap(); + assert_eq!(report["ok"], true, "{name}"); + } +} + #[test] fn model_and_actions_share_the_compiled_definition_inspector() { let registry = compiled(); diff --git a/products/adapter/scripts/test-payment-native.mjs b/products/adapter/scripts/test-payment-native.mjs index d24deefc25..9962b260fa 100644 --- a/products/adapter/scripts/test-payment-native.mjs +++ b/products/adapter/scripts/test-payment-native.mjs @@ -212,7 +212,7 @@ print(json.dumps({'path':str(root), 'python':platform.python_version(), 'files': await privateFile(paymentsPath, configuration); await privateFile(runtimePath, { apiVersion: 'id.registrystack.org/formats/adapter/runtime/v1alpha1', kind: 'AdapterRuntimeConfig', id: `payment-native-${suffix}`, endpoints: [], listener: { bind: `127.0.0.1:${adapterPort}` }, secretProviders: { file: { root: secrets } }, - database: { runtimeUrlRef: 'secret:file/adapter-runtime', migrationUrlRef: 'secret:file/adapter-migration', trustedRootCertificateRef: 'secret:file/postgres-ca' }, + database: { runtimeUrlRef: 'secret:file/adapter-runtime', migrationUrlRef: 'secret:file/adapter-migration', caBundleRef: 'secret:file/postgres-ca' }, oidc: { issuer: issuer.issuer, audience: 'urn:registry:payment-adapter', jwksSource: { type: 'static', documentRef: 'secret:file/jwks' } }, allowedClients: ['coordinator-payments'], allowedPrivateCidrs: ['127.0.0.0/8'], audit: { retentionDays: 90 } }); await preflightAndGrant(adapterDb, runtimePath, paymentsPath, 'adapter'); @@ -277,7 +277,7 @@ print(json.dumps({'path':str(root), 'python':platform.python_version(), 'files': const packaged = ctl(['package', '--project', join(repository, 'products/coordinator/examples/payment-collections'), '--output', packagePath]); const coordinatorRuntime = join(root, 'coordinator-runtime.yaml'); await privateFile(coordinatorRuntime, { apiVersion: 'id.registrystack.org/formats/coordinator/runtime/v1alpha1', kind: 'CoordinatorRuntimeConfig', - secretProviders: { file: { root: secrets } }, database: { runtimeUrlRef: 'secret:file/coordinator-runtime', migrationUrlRef: 'secret:file/coordinator-migration', trustedRootCertificateRef: 'secret:file/postgres-ca' }, + secretProviders: { file: { root: secrets } }, database: { runtimeUrlRef: 'secret:file/coordinator-runtime', migrationUrlRef: 'secret:file/coordinator-migration', caBundleRef: 'secret:file/postgres-ca' }, namespace: 'coordinator_payment_native', connections: { 'licence-fees': { type: 'payments', baseUrl: coordinatorProxy.url, paymentConnection: 'licence-fees', resultCheckSeconds: 60, authorization: { tokenEndpoint: `${issuer.origin}/token`, clientAssertionAudience: issuer.issuer, clientId: 'coordinator-payments', signingKeyRef: 'secret:file/coordinator-payments-jwk', resource: 'urn:registry:payment-adapter', scopes: ['payments:collect'] } } }, deployment: { databaseId: `coordinator-payment-${suffix}`, runtimeRole: coordinatorDb.runtime, diff --git a/products/breg/examples/g2p-disbursement/registry.yaml b/products/breg/examples/g2p-disbursement/registry.yaml index 1b1abdbe08..95beaabdd9 100644 --- a/products/breg/examples/g2p-disbursement/registry.yaml +++ b/products/breg/examples/g2p-disbursement/registry.yaml @@ -14,17 +14,17 @@ package: sourceRevision: g2p-disbursement-0.1.0 datasets: - - id: g2p-disbursements + g2p-disbursements: display: label: G2P disbursements description: Authoritative instruction, payout binding, and provider-reported completion facts. vocabularies: - - id: disbursement-state + disbursement-state: values: [instruction-ready, attempt-bound, provider-confirmed] recordTypes: - - id: disbursement-instruction + disbursement-instruction: route: disbursement-instructions primaryDataset: g2p-disbursements mutationMode: mutable @@ -78,7 +78,7 @@ recordTypes: - {id: provider-result-digest, apiName: providerResultDigest, type: string, required: false, minimumLength: 64, maximumLength: 64, pattern: '^[0-9a-f]{64}$', classification: internal} actions: - - id: create-disbursement-instruction + create-disbursement-instruction: display: label: Create disbursement instruction description: Freeze one authority-owned instruction before payment processing begins. @@ -119,7 +119,7 @@ actions: currency-scale: {fromInput: currency-scale} disbursement-state: {value: instruction-ready} - - id: bind-payout-attempt + bind-payout-attempt: display: label: Bind payout attempt description: Bind exactly one Adapter attempt and provider configuration before dispatch. @@ -168,7 +168,7 @@ actions: provider-binding-revision: {fromInput: provider-binding-revision} disbursement-state: {value: attempt-bound} - - id: record-provider-confirmation + record-provider-confirmation: display: label: Record provider confirmation description: Record the exact provider-reported completion for the one frozen payout attempt. @@ -224,7 +224,7 @@ actions: disbursement-state: {value: provider-confirmed} accessProfiles: - - id: disbursement-authority + disbursement-authority: actorKind: service principalClaim: registry_principal requesterClients: [benefit-service] @@ -243,7 +243,7 @@ accessProfiles: - {recordType: disbursement-instruction, rowBoundaries: unrestricted} results: [instruction] - - id: payment-adapter-binder + payment-adapter-binder: actorKind: service principalClaim: registry_principal requesterClients: [payment-adapter] @@ -262,7 +262,7 @@ accessProfiles: - {recordType: disbursement-instruction, rowBoundaries: unrestricted} results: [instruction] - - id: payment-adapter-reporter + payment-adapter-reporter: actorKind: service principalClaim: registry_principal requesterClients: [payment-adapter] diff --git a/products/breg/examples/payment-fee-issuance/registry.yaml b/products/breg/examples/payment-fee-issuance/registry.yaml index 69d6d39156..2fb86a0479 100644 --- a/products/breg/examples/payment-fee-issuance/registry.yaml +++ b/products/breg/examples/payment-fee-issuance/registry.yaml @@ -14,17 +14,17 @@ package: sourceRevision: payment-fee-issuance-0.1.0 datasets: - - id: service-billing + service-billing: display: label: Service billing description: Authoritative service fee, collection binding, receipt, and single-use issuance facts. vocabularies: - - id: payment-state + payment-state: values: [due-unbound, attempt-bound, paid, issued] recordTypes: - - id: service-fee-bill + service-fee-bill: route: service-fee-bills primaryDataset: service-billing mutationMode: mutable @@ -83,7 +83,7 @@ recordTypes: - {id: issuance-id, apiName: issuanceId, type: uuid, required: false, classification: internal} actions: - - id: create-fee-bill + create-fee-bill: display: label: Create service fee bill description: Create the one authoritative bill for a service request from the service-owned synthetic tariff. @@ -119,7 +119,7 @@ actions: simulation: {fromInput: simulation} payment-state: {value: due-unbound} - - id: bind-payment-attempt + bind-payment-attempt: display: label: Bind payment collection attempt description: Freeze one Adapter collection and provider binding before provider dispatch. @@ -170,7 +170,7 @@ actions: provider-binding-revision: {fromInput: provider-binding-revision} payment-state: {value: attempt-bound} - - id: record-payment-receipt + record-payment-receipt: display: label: Record exact payment receipt description: Record one receipt only when every bill, collection, provider, and money fact matches the frozen binding. @@ -227,7 +227,7 @@ actions: receipt-digest: {fromInput: receipt-digest} payment-state: {value: paid} - - id: issue-paid-service + issue-paid-service: display: label: Issue paid service description: Mark the service request issued once, only for its exact paid bill and receipt. @@ -262,7 +262,7 @@ actions: payment-state: {value: issued} accessProfiles: - - id: service-biller + service-biller: actorKind: service principalClaim: registry_principal requesterClients: [issuance-service] @@ -276,7 +276,7 @@ accessProfiles: - {recordType: service-fee-bill, rowBoundaries: unrestricted} results: [bill] - - id: service-issuer + service-issuer: actorKind: service principalClaim: registry_principal requesterClients: [issuance-service] @@ -295,7 +295,7 @@ accessProfiles: - {recordType: service-fee-bill, rowBoundaries: unrestricted} results: [bill] - - id: payment-adapter-binder + payment-adapter-binder: actorKind: service principalClaim: registry_principal requesterClients: [payment-adapter] @@ -314,7 +314,7 @@ accessProfiles: - {recordType: service-fee-bill, rowBoundaries: unrestricted} results: [bill] - - id: payment-adapter-reporter + payment-adapter-reporter: actorKind: service principalClaim: registry_principal requesterClients: [payment-adapter] @@ -333,7 +333,7 @@ accessProfiles: - {recordType: service-fee-bill, rowBoundaries: unrestricted} results: [bill] - - id: coordinator-bill-reader + coordinator-bill-reader: actorKind: service principalClaim: registry_principal requesterClients: [service-coordinator] diff --git a/products/breg/examples/payment-fee-issuance/run-native.sh b/products/breg/examples/payment-fee-issuance/run-native.sh index b0bf72d0db..c956c8dcf1 100755 --- a/products/breg/examples/payment-fee-issuance/run-native.sh +++ b/products/breg/examples/payment-fee-issuance/run-native.sh @@ -307,7 +307,7 @@ secretProviders: database: runtimeUrlRef: $runtime_ref migrationUrlRef: $migration_ref - trustedRootCertificateRef: secret:file/postgres-ca + caBundleRef: secret:file/postgres-ca pool: {maximumConnections: 4, waitTimeoutMilliseconds: 2000, createTimeoutMilliseconds: 2000, recycleTimeoutMilliseconds: 2000} roles: {migration: $migration_role, runtime: $runtime_role} package: {root: $package_root} From 5ea40fe341f3e18aecd63453d55ee026e1f128e2 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Thu, 26 Nov 2026 21:59:31 +0100 Subject: [PATCH 38/40] docs(payments): list payment support under unreleased Signed-off-by: Jeremi Joslin --- products/adapter/CHANGELOG.md | 57 ++++++++++++++++--------------- products/coordinator/CHANGELOG.md | 33 +++++++++--------- 2 files changed, 46 insertions(+), 44 deletions(-) diff --git a/products/adapter/CHANGELOG.md b/products/adapter/CHANGELOG.md index 8f56d8b73d..2d29f41802 100644 --- a/products/adapter/CHANGELOG.md +++ b/products/adapter/CHANGELOG.md @@ -2,6 +2,35 @@ ## Unreleased +- `adapter serve --payments-config` hosts typed synthetic payment collection + operations on the shared listener and PostgreSQL store, including without + a record project. Connections bind institution/service scope, admitted + callers, provider tenant/biller and separate BReg reporting credentials. + Retained attempts preserve their original binding and exact commands across + response loss and restart. Only a confirmed, correlated receipt can mark + the authoritative bill paid. One attempt is permitted per bill version, + including after definitive failure. Collections are simulation-only: a + collection binding other than the simulator with `simulation: true` is + refused with `adapter.payment.collection-simulation-only`. Live collection + providers, replacement attempts, refunds and settlement are outside this + slice. +- The same host serves typed G2P disbursements: request a disbursement from an + approved BReg instruction, read its correlated provider observation, and + report verified provider confirmation through a restricted BReg Action. An + uncertain submission is never sent again. Disbursement connections pin a + provider pack, passed to `adapter serve` with a repeatable + `--payment-provider-pack`, and authenticate with `bearer` or, for Mifos + Payment Hub EE, `mifos-legacy-signature`, which signs the exact Bulk request + through a pinned Transit key and reads Operations status under a separate + bearer credential. Full Linux CI exercises the signature with OpenBao and + a synthetic provider. Verify your deployed provider pack and Mifos route + in a sandbox before moving money. Verify beneficiary credit and settlement + separately. +- `adapterctl payments check` validates connections offline and + `adapterctl payments contract` exports their typed HTTP contract. Generated + schemas, a native Coordinator workflow, the restricted BReg fee fixture, + and a joined native acceptance runner accompany the payment host. + ## 0.47.0 - 2026-11-21 - Accept an optional `project.label` and `project.description` in the project @@ -104,34 +133,6 @@ - A reviewed projection operation serves BReg's read-only external views. See the BReg changelog and the [external projections pack](examples/external-projections/README.md). -- `adapter serve --payments-config` hosts typed synthetic payment collection - operations on the shared listener and PostgreSQL store, including without - a record project. Connections bind institution/service scope, admitted - callers, provider tenant/biller and separate BReg reporting credentials. - Retained attempts preserve their original binding and exact commands across - response loss and restart. Only a confirmed, correlated receipt can mark - the authoritative bill paid. One attempt is permitted per bill version, - including after definitive failure. Collections are simulation-only: a - collection binding other than the simulator with `simulation: true` is - refused with `adapter.payment.collection-simulation-only`. Live collection - providers, replacement attempts, refunds and settlement are outside this - slice. -- The same host serves typed G2P disbursements: request a disbursement from an - approved BReg instruction, read its correlated provider observation, and - report verified provider confirmation through a restricted BReg Action. An - uncertain submission is never sent again. Disbursement connections pin a - provider pack, passed to `adapter serve` with a repeatable - `--payment-provider-pack`, and authenticate with `bearer` or, for Mifos - Payment Hub EE, `mifos-legacy-signature`, which signs the exact Bulk request - through a pinned Transit key and reads Operations status under a separate - bearer credential. Full Linux CI exercises the signature with OpenBao and - a synthetic provider. Verify your deployed provider pack and Mifos route - in a sandbox before moving money. Verify beneficiary credit and settlement - separately. -- `adapterctl payments check` validates connections offline and - `adapterctl payments contract` exports their typed HTTP contract. Generated - schemas, a native Coordinator workflow, the restricted BReg fee fixture, - and a joined native acceptance runner accompany the payment host. ## 0.46.0 - 2026-11-08 diff --git a/products/coordinator/CHANGELOG.md b/products/coordinator/CHANGELOG.md index 2754252143..4739f682dd 100644 --- a/products/coordinator/CHANGELOG.md +++ b/products/coordinator/CHANGELOG.md @@ -2,6 +2,23 @@ ## Unreleased +- Add native Adapter payment collection operations: request a collection from + an authoritative bill id and version, read its typed state, and record a + verified receipt under a separate idempotent command. Collection requests + support read-only original-key reconciliation. The host-owned `collection` + completion keeps accepted, pending, and unknown states waiting, correlates + every read to the accepted bill and binding, and settles the collection + attempt only on confirmed or failed state. Only Adapter-verified confirmed + state can produce a registry receipt. +- Add native G2P disbursement operations: submit one approved immutable + instruction, observe its typed provider state, and report a verified + provider confirmation under a separate same-command key. An uncertain + submission stays held and permits only read-only original-command + reconciliation, never a fresh provider send. The host-owned `disbursement` + completion keeps accepted, pending, and unknown states waiting, correlates + every read to the accepted instruction and binding, and settles only on + provider-confirmed or failed state. + ## 0.47.0 - 2026-11-21 - BREAKING: a `CoordinatorProject`'s human `label` and `description` move from @@ -96,22 +113,6 @@ and `coordinator --recovery-only` inspects it with admissions and dispatch disabled. Migration: set the audience member to the authorization server's issuer identifier, exactly as its metadata publishes it. -- Add native Adapter payment collection operations: request a collection from - an authoritative bill id and version, read its typed state, and record a - verified receipt under a separate idempotent command. Collection requests - support read-only original-key reconciliation. The host-owned `collection` - completion keeps accepted, pending, and unknown states waiting, correlates - every read to the accepted bill and binding, and settles the collection - attempt only on confirmed or failed state. Only Adapter-verified confirmed - state can produce a registry receipt. -- Add native G2P disbursement operations: submit one approved immutable - instruction, observe its typed provider state, and report a verified - provider confirmation under a separate same-command key. An uncertain - submission stays held and permits only read-only original-command - reconciliation, never a fresh provider send. The host-owned `disbursement` - completion keeps accepted, pending, and unknown states waiting, correlates - every read to the accepted instruction and binding, and settles only on - provider-confirmed or failed state. ## 0.46.0 - 2026-11-08 From 6279a4093d215e8642fc81d8e86db3a734976998 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Thu, 26 Nov 2026 22:50:26 +0100 Subject: [PATCH 39/40] test(payments): serve the OpenBao fixture over its Unix socket Signed-off-by: Jeremi Joslin --- .../adapter/scripts/test-payments-openbao.sh | 33 ++++++++++--------- 1 file changed, 18 insertions(+), 15 deletions(-) diff --git a/products/adapter/scripts/test-payments-openbao.sh b/products/adapter/scripts/test-payments-openbao.sh index c0dc0fcde9..39ea7ab863 100755 --- a/products/adapter/scripts/test-payments-openbao.sh +++ b/products/adapter/scripts/test-payments-openbao.sh @@ -141,9 +141,10 @@ api_proxy { use_auto_auth_token = "force" } +# Adapter's Transit client uses HTTP over this private Unix socket. listener "unix" { address = "/fixtures/transit.sock" - socket_mode = "0600" + tls_disable = true require_request_header = true } @@ -185,6 +186,13 @@ proxy_tcp_read() { "http://127.0.0.1:8300/v1/transit/keys/$1" } +proxy_unix_read() { + curl --disable --fail --silent --show-error --noproxy '*' --max-time 5 \ + --unix-socket "$scratch/transit.sock" \ + --header 'X-Vault-Request: true' \ + "http://localhost/v1/transit/keys/$1" +} + ready=false for _ in {1..50}; do if request_metadata="$(proxy_tcp_read mifos-request 2>/dev/null)"; then @@ -201,26 +209,25 @@ if [[ ! -S "$scratch/transit.sock" ]]; then printf 'OpenBao Proxy did not create its Unix socket\n' >&2 exit 1 fi +chmod 0600 "$scratch/transit.sock" host_unix_socket=true -if unix_request_metadata="$(curl --fail --silent \ - --unix-socket "$scratch/transit.sock" \ - --header 'X-Vault-Request: true' \ - http://localhost/v1/transit/keys/mifos-request 2>/dev/null)"; then +if unix_request_metadata="$(proxy_unix_read mifos-request 2>"$scratch/unix-read-error")"; then request_metadata="$unix_request_metadata" - if ! response_metadata="$(curl --fail --silent \ - --unix-socket "$scratch/transit.sock" \ - --header 'X-Vault-Request: true' \ - http://localhost/v1/transit/keys/mifos-response 2>/dev/null)"; then + if ! response_metadata="$(proxy_unix_read mifos-response)"; then printf 'OpenBao Proxy Unix listener did not serve response-key metadata\n' >&2 exit 1 fi -else +elif [[ "${OPENBAO_PREFLIGHT_ONLY:-false}" == true ]]; then host_unix_socket=false if ! response_metadata="$(proxy_tcp_read mifos-response 2>/dev/null)"; then printf 'OpenBao Proxy did not serve response-key metadata\n' >&2 exit 1 fi +else + printf 'OpenBao Proxy Unix listener did not serve request-key metadata\n%s\n' \ + "$(<"$scratch/unix-read-error")" >&2 + exit 1 fi jq -e '.data.imported_key == false and .data.derived == false @@ -243,14 +250,10 @@ if [[ "${OPENBAO_PREFLIGHT_ONLY:-false}" == true ]]; then if [[ "$host_unix_socket" == true ]]; then printf 'real OpenBao Transit and Unix Proxy preflight passed\n' else - printf 'real OpenBao Transit and Proxy preflight passed; host Unix sockets require Linux\n' + printf 'real OpenBao Transit and TCP Proxy preflight passed (host Unix listener unverified)\n' fi exit 0 fi -if [[ "$host_unix_socket" != true ]]; then - printf 'the Rust integration test requires Linux for a bind-mounted container Unix socket\n' >&2 - exit 1 -fi REGISTRY_PAYMENTS_OPENBAO_SOCKET="$scratch/transit.sock" \ REGISTRY_PAYMENTS_OPENBAO_REQUEST_PUBLIC_KEY="$scratch/request-public.pem" \ From 0e46e149af065a6eed51ab8b7128cbd9be848710 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Thu, 26 Nov 2026 23:41:24 +0100 Subject: [PATCH 40/40] fix(payments): enforce bounded JSON request objects Signed-off-by: Jeremi Joslin --- crates/registry-adapter/src/payments/http.rs | 66 +++++++++++++++++-- .../adapter/scripts/test-payment-native.mjs | 5 +- 2 files changed, 66 insertions(+), 5 deletions(-) diff --git a/crates/registry-adapter/src/payments/http.rs b/crates/registry-adapter/src/payments/http.rs index 10637c2b9a..0356db8157 100644 --- a/crates/registry-adapter/src/payments/http.rs +++ b/crates/registry-adapter/src/payments/http.rs @@ -43,6 +43,8 @@ use std::{ }; use uuid::Uuid; +const MAX_PAYMENT_BODY_BYTES: usize = 4096; + struct HttpState { authenticator: Authenticator, service: PaymentService, @@ -402,7 +404,7 @@ pub async fn load_router( "/v1/payments/{connection}/disbursements/{disbursement}/record-provider-confirmation", post(record_provider_confirmation), ) - .layer(DefaultBodyLimit::max(4096)) + .layer(DefaultBodyLimit::max(MAX_PAYMENT_BODY_BYTES)) .with_state(state)) } @@ -460,11 +462,23 @@ fn single_header<'a>(headers: &'a HeaderMap, name: &str) -> Result<&'a str, Http _ => Err(HttpError(Error::InvalidRequest)), } } -fn body(headers: &HeaderMap, uri: &Uri, body: &[u8]) -> Result { - if uri.query().is_some() || single_header(headers, "content-type")? != "application/json" { +fn body(headers: &HeaderMap, uri: &Uri, bytes: &[u8]) -> Result { + if bytes.len() > MAX_PAYMENT_BODY_BYTES + || uri.query().is_some() + || single_header(headers, "content-type")? != "application/json" + { + return Err(HttpError(Error::InvalidRequest)); + } + // The payment wire contract requires named fields in a JSON object. + if !bytes.trim_ascii_start().starts_with(b"{") { return Err(HttpError(Error::InvalidRequest)); } - serde_json::from_slice(body).map_err(|_| HttpError(Error::InvalidRequest)) + let mut decoder = serde_json::Deserializer::from_slice(bytes); + let request = T::deserialize(&mut decoder).map_err(|_| HttpError(Error::InvalidRequest))?; + decoder + .end() + .map_err(|_| HttpError(Error::InvalidRequest))?; + Ok(request) } fn collection(value: &str) -> Result { Uuid::parse_str(value) @@ -938,6 +952,50 @@ fn refused(message: &str) -> ServeError { mod tests { use super::*; + #[test] + fn payment_body_requires_a_closed_json_object() { + let mut headers = HeaderMap::new(); + headers.insert("content-type", HeaderValue::from_static("application/json")); + let uri = Uri::from_static("/v1/payments/test/collections"); + let bill_id = "018fab00-0000-7000-8000-000000000001"; + let object = format!(r#"{{"billId":"{bill_id}","billVersion":9007199254740991}}"#); + assert_eq!( + body::(&headers, &uri, object.as_bytes()).ok(), + Some(RequestCollection { + bill_id: bill_id.parse().unwrap(), + bill_version: 9_007_199_254_740_991, + }) + ); + let padded = format!("\n \t{object}\r\n"); + assert!(body::(&headers, &uri, padded.as_bytes()).is_ok()); + + for invalid in [ + format!(r#"["{bill_id}",1]"#), + format!(r#"{{"billId":"{bill_id}","billVersion":1,"billVersion":2}}"#), + format!(r#"{{"billId":"{bill_id}","billVersion":1,"amount":1}}"#), + format!(r#"{{"billId":"{bill_id}","billVersion":"1"}}"#), + format!("{object} null"), + format!("\u{000c}{object}"), + ] { + assert!( + matches!( + body::(&headers, &uri, invalid.as_bytes()), + Err(HttpError(Error::InvalidRequest)) + ), + "unexpected result for {invalid}" + ); + } + + let mut at_limit = object.into_bytes(); + at_limit.resize(MAX_PAYMENT_BODY_BYTES, b' '); + assert!(body::(&headers, &uri, &at_limit).is_ok()); + at_limit.push(b' '); + assert!(matches!( + body::(&headers, &uri, &at_limit), + Err(HttpError(Error::InvalidRequest)) + )); + } + #[test] fn a_released_acceptance_is_audited_under_its_attempt() { let collection = CollectionAccepted { diff --git a/products/adapter/scripts/test-payment-native.mjs b/products/adapter/scripts/test-payment-native.mjs index 9962b260fa..8dda40813b 100644 --- a/products/adapter/scripts/test-payment-native.mjs +++ b/products/adapter/scripts/test-payment-native.mjs @@ -221,9 +221,12 @@ print(json.dumps({'path':str(root), 'python':platform.python_version(), 'files': const bill = await createBill('recovery'); await issue(bill, 'absent-receipt', 'unpaid-issue', [412]); await collect(bill, 'extra-facts', [422], paymentToken, { amount: 1, paid: true }); + const positionalIntent = [bill.billId, bill.billVersion]; + await exchange('POST', collectionPath, { token: paymentToken, body: positionalIntent, key: 'wrong-body-shape', expected: [422] }); await collect(bill, 'missing-scope', [403], issuer.token('payment-coordinator', 'urn:registry:payment-adapter', '')); await collect(bill, 'citizen', [401], null); - assert.equal(ledger().requestCount, 0); check('unpaid issuance, forged financial fields and unauthorized callers refused'); + await exchange('POST', collectionPath, { body: positionalIntent, key: 'unauthenticated', expected: [401] }); + assert.equal(ledger().requestCount, 0); check('unpaid issuance, invalid request bodies and unauthorized callers refused'); registryProxy.drop(`/v1/actions/${fixture.bind.action}`); await collect(bill, 'original', [503]); assert.equal(ledger().requestCount, 0);